简体   繁体   English

使用Java使用提供的密钥和iv解密openssl aes-256-cbc

[英]Using Java to decrypt openssl aes-256-cbc using provided key and iv

I have been searching for a Java code example to do the following but have been unsuccessful. 我一直在寻找一个Java代码示例来执行以下操作,但一直没有成功。 I'm looking for a solution for my particular situation. 我正在为我的特殊情况寻找解决方案。

A key and IV have been generated using "testtest" for a password: 使用“testtest”为密码生成密钥和IV:

openssl enc -aes-256-cbc -P 
salt=2855243412E30BD7
key=E4A38479A2349177EAE6038A018483318350E7F5430BDC8F82F1974715CB54E5
iv=629E2E1500B6BA687A385D410D5B08E3

A file(named text) has been encrypted on Linux using openssl command: 使用openssl命令在Linux上加密了一个文件(命名文本):

openssl enc -aes-256-cbc -K 
E4A38479A2349177EAE6038A018483318350E7F5430BDC8F82F1974715CB54E5 -iv
629E2E1500B6BA687A385D410D5B08E3 -e -in text -out text_ENCRYPTED

It can be decrypted successfully using: 它可以使用以下方法成功解密:

openssl enc -aes-256-cbc -K 
E4A38479A2349177EAE6038A018483318350E7F5430BDC8F82F1974715CB54E5 -iv 
629E2E1500B6BA687A385D410D5B08E3 -d -in text_ENCRYPTED -out text_DECRYPTED

I have access to the encrypted file, the salt, the key and the iv. 我可以访问加密文件,盐,密钥和iv。 I do not believe I'm going to receive the password. 我不相信我会收到密码。 Also, i have installed the unlimited strength JCE policy. 此外,我已经安装了无限强度的JCE政策。 So far I have only found examples where another java program does the encryption and generates these parameters. 到目前为止,我只找到了另一个java程序进行加密并生成这些参数的示例。 For my case I must use the salt, key and iv values given to me to decrypt a file. 对于我的情况,我必须使用给我的salt,key和iv值来解密文件。 Is this possible with Java? 这可能与Java有关吗? Please remember I'm bound by this configuration, thank you very much for your time and help. 请记住我受这个配置的约束,非常感谢您的时间和帮助。

You should use something like this: 你应该使用这样的东西:

InputStream cipherInputStream = null;
try {
    final StringBuilder output = new StringBuilder();
    final byte[] secretKey = javax.xml.bind.DatatypeConverter.parseHexBinary("E4A38479A2349177EAE6038A018483318350E7F5430BDC8F82F1974715CB54E5");
    final byte[] initVector = javax.xml.bind.DatatypeConverter.parseHexBinary("629E2E1500B6BA687A385D410D5B08E3");
    final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey, "AES"), new IvParameterSpec(initVector, 0, cipher.getBlockSize()));
    cipherInputStream = new CipherInputStream(new FileInputStream("text_ENCRYPTED"), cipher);

    final String charsetName = "UTF-8";

    final byte[] buffer = new byte[8192];
    int read = cipherInputStream.read(buffer);

    while (read > -1) {
        output.append(new String(buffer, 0, read, charsetName));
        read = cipherInputStream.read(buffer);
    }

    System.out.println(output);
} finally {
    if (cipherInputStream != null) {
        cipherInputStream.close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM