2013-03-24 154 views
14

我一直在寻找一个Java代码示例来执行以下操作,但不成功。我正在为我的特殊情况寻找解决方案。使用Java解密openssl aes-256-cbc使用提供的密钥和iv

甲密钥和IV已使用 “TESTTEST” 密码生成:

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

的文件(命名为文本)已经使用openssl指令加密在Linux:

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 

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

回答

19

你应该使用这样的事情:

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

作品!非常感谢你。 – user2203629 2013-03-24 12:17:20

+12

不客气,那真是个好消息。您应该将此答案标记为已接受,然后表明已解决问题。 – laz 2013-03-24 16:45:01

+2

答案中的decodeHex()中存在一个微妙的错误。当编码值以'00'开始时,相应的字节就会消失。 考虑使用像Apache Commons这样的知名库进行十六进制解码。 (我发现一个例子在http://stackoverflow.com/questions/13990941/how-to-convert-hex-string-to-java-string) – ways 2015-03-20 08:33:30

相关问题