TXAggie00
TXAggie00

Reputation: 67

Java AES Encryption getting different results

I have searched quite a bit and have yet to gain any clarity on my particular issue. I have a process using node.js that encrypts some data elements and stores the hex string output. So as to not go into great detail on that particular process, the results are the same as the following online tool here.

If you were to enter the following into that tool:

Enter text to be Encrypted:  "666326911"
Select Mode: "CBC"
Key Size in Bits: "256"
Enter IV: (Leave blank)
Enter Secret Key: "c88ba867994f440963f55b727cdd3cb7"
Output Text Format: "Hex"

The Encryption output would give you "C08F3DD7F5F7ACD0FC3710ADDFBF596C". This result matches my process.

I now have a need to use java to encrypt data the same way. My code gives me completely different results, and I can't seem to pinpoint where my error occurs. Here is the java code I am using:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key key = new SecretKeySpec(Hex.decodeHex("c88ba867994f440963f55b727cdd3cb7"), "AES");
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
cipher.init(Cipher.ENCRYPT_MODE,key,iv);
byte[] testString = "666326911".getBytes("UTF-8");
byte[] encrypted = cipher.doFinal(testString);
System.out.println("Encrypt Hex: "+Hex.encodeHexString(encrypted));

This code gives me a result of "DA6711D88635E82B68673D9C077B070F". Can anyone tell me where my obvious mistake or incorrect assumption is?

Thanks, Scott

EDIT:

Changing the code to:

SecretKeySpec key = new SecretKeySpec("c88ba867994f440963f55b727cdd3cb7".getBytes("UTF-8"), "AES");

results in an "InvalidKeyException: Illegal key size"

Upvotes: 2

Views: 1987

Answers (1)

skandigraun
skandigraun

Reputation: 925

The problem seems to be with the SecretKeyspec.

On the online tool you are using it as a plain String.

Here you are treating it as a hex number, and decode it first.

If you try

Key key = new SecretKeySpec("c88ba867994f440963f55b727cdd3cb7".getBytes(), "AES");

then you should get the same results.


This is a copy-paste of the code I'm using:

try {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    Key key = new SecretKeySpec("c88ba867994f440963f55b727cdd3cb7".getBytes("UTF-8"), "AES");
    IvParameterSpec iv = new IvParameterSpec(new byte[16]);
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);

    byte[] testString = "666326911".getBytes("UTF-8");

    byte[] encrypted = cipher.doFinal(testString);
    System.out.println("Encrypt Hex: " + Hex.encodeHexString(encrypted));
} catch (Exception e) {
    System.err.println("Uh-ohh...");
    e.printStackTrace();
}

And the output is:

Encrypt Hex: c08f3dd7f5f7acd0fc3710addfbf596c

Process finished with exit code 0

Upvotes: 3

Related Questions