【问题标题】:Using Java to decrypt openssl aes-256-cbc using provided key and iv使用 Java 使用提供的密钥和 iv 解密 openssl aes-256-cbc
【发布时间】:2013-03-13 17:40:50
【问题描述】:

我一直在寻找一个 Java 代码示例来执行以下操作,但没有成功。我正在为我的特殊情况寻找解决方案。

已使用“testtest”作为密码生成密钥和 IV:

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

一个文件(命名文本)已在 Linux 上使用 openssl 命令加密:

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

可以使用以下方法成功解密:

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

我可以访问加密文件、salt、密钥和 iv。我不相信我会收到密码。另外,我已经安装了无限强度 JCE 政策。到目前为止,我只找到了另一个 java 程序进行加密并生成这些参数的示例。对于我的情况,我必须使用给我的 salt、key 和 iv 值来解密文件。 Java可以做到这一点吗?请记住我受此配置约束,非常感谢您的时间和帮助。

【问题讨论】:

    标签: java openssl


    【解决方案1】:

    你应该使用这样的东西:

    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();
        }
    }
    

    【讨论】:

    • 答案中的 decodeHex() 有一个微妙的错误。当编码值以“00”开头时,相应的字节就消失了。考虑使用 Apache Commons 等知名库进行十六进制解码。 (我在stackoverflow.com/questions/13990941/… 找到了一个例子)
    • 你是正确的@ways,我后来也遇到了这个问题。我将使用正确的解码器更新示例。
    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2022-06-11
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多