Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion Java Different encoding output for same string with AES algorithm

I have a ColdFusion method for the decryption of a string: PFN123. It uses the AES algorithm, HEX encoding and has a length of 128 bits. The output is:

    32952063062A232355AABB63E129EA9F 

I have written equivalent java code for AES encryption and decryption. However it produces a different result:

    07e342ad4b59b276cbb6418248aaf886.

I don't understand why the results are different for same algorithm and encoding scheme. Can anyone explain why? Thanks in advance.

Java Code:

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

}
like image 661
Satish Sharma Avatar asked Nov 04 '22 02:11

Satish Sharma


1 Answers

Thanks for the support. I have found my answer. ColdFusion is storing the key in its Base64 decoded bytes. So in java we have to generate the key by decoding via BASE64Decoder:

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

    return key;
}
like image 170
Satish Sharma Avatar answered Nov 13 '22 07:11

Satish Sharma