ColdFusion Java使用AES算法为相同的字符串输出不同的编码

时间:2013-03-11 10:11:34

标签: java coldfusion encryption

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

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

}

1 个答案:

答案 0 :(得分: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;
}