2013-03-11 37 views
5

我有一个用于解密字符串的ColdFusion方法:PFN123。它使用AES算法,HEX编码,长度为128位。输出是:ColdFusion Java与AES算法相同的字符串的不同编码输出

32952063062A232355AABB63E129EA9F 

我写了用于AES加密和解密的等效java代码。然而它产生了不同的结果:

07e342ad4b59b276cbb6418248aaf886. 

我不明白为什么结果对于相同的算法和编码方案是不同的。 任何人都可以解释为什么?提前致谢。

Java代码:

import java.security.Key; 

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 

import org.apache.commons.codec.binary.Hex; 

public class AESEncryptionDecryptionTest { 

    private static final String ALGORITHM  = "AES"; 
    private static final String myEncryptionKey = "OIXQUULC7khaJzzOOHRqgw=="; 
    private static final String UNICODE_FORMAT = "UTF8"; 

    public static String encrypt(String valueToEnc) throws Exception { 
     Key key = generateKey(); 
     Cipher c = Cipher.getInstance(ALGORITHM); 
     c.init(Cipher.ENCRYPT_MODE, key); 
     byte[] encValue = c.doFinal(valueToEnc.getBytes(UNICODE_FORMAT)); 
     String encryptedValue = new Hex().encodeHexString(encValue); 
     return encryptedValue; 
    } 

    public static String decrypt(String encryptedValue) throws Exception { 
     Key key = generateKey(); 
     Cipher c = Cipher.getInstance(ALGORITHM); 
     c.init(Cipher.DECRYPT_MODE, key); 
     byte[] decordedValue = new Hex().decode(encryptedValue.getBytes()); 
     byte[] decValue = c.doFinal(decordedValue);//////////LINE 50 
     String decryptedValue = new String(decValue); 
     return decryptedValue; 
    } 

    private static Key generateKey() throws Exception { 
     byte[] keyAsBytes; 
     keyAsBytes = myEncryptionKey.getBytes(); 
     Key key = new SecretKeySpec(keyAsBytes, ALGORITHM); 
     return key; 
    } 

    public static void main(String[] args) throws Exception { 

     String value = "PFN123"; 
     String valueEnc = AESEncryptionDecryptionTest.encrypt(value); 
     String valueDec = AESEncryptionDecryptionTest.decrypt(valueEnc); 

     System.out.println("Plain Text : " + value); 
     System.out.println("Encrypted : " + valueEnc); 
     System.out.println("Decrypted : " + valueDec); 
    } 

} 
+0

什么额外的ColdFusion是我在Java中很想念它的解密隐式方法做? – 2013-03-11 11:59:25

+0

它可以使用另一种编码比UTF8,使用不同的块链模式,使用不同的填充(当然还有另一个输入键,但我想你检查了)。 – 2013-03-11 12:25:28

+0

是通过所有组合尝试了所有三个选项....我的问题是我必须在coldFusion中加密一个字符串,然后用Java解密它。 – 2013-03-11 12:33:52

回答

2

感谢您的支持。我找到了我的答案。 ColdFusion将密钥存储在Base64解码字节中。因此,在Java中,我们必须通过经BASE64Decoder解码来生成密钥:

private static Key generateKey() throws Exception 
{ 
    byte[] keyValue; 
    keyValue = new BASE64Decoder().decodeBuffer(passKey); 
    Key key = new SecretKeySpec(keyValue, ALGORITHM); 

    return key; 
} 
相关问题