2013-03-24 451 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

相關問題