CluelessKid CluelessKid - 5 months ago 59x
Java Question

AES encryption output does not match

Trying to figure out why it won't AES-encrypt a string to the same output in

Original Java Source:

byte[] key = "mySecretKey".getBytes(Charset.forName("UTF-8"));

private static byte[] encrypt(byte[] key, byte[] input) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(1, skeySpec);
return cipher.doFinal(input);

String resultEncrypted = encrypt(key, "UnprotectedStringToEncrypt".getBytes(Charset.forName("UTF-8")));

//OUTPUT: [B@66fcc070

This is what I've tried besides many others so far:
VB.NET (not same output as java's)

Public Shared Function AES_Encrypt(ByVal input As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim encrypted As String = ""
AES.Key = System.Text.Encoding.UTF8.GetBytes("yt8yeqdXxpUyoUk3")
AES.Mode = CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(input)
encrypted = System.Text.Encoding.UTF8.GetString(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
MsgBox("Exception:" & vbcrlf & vbcrlf & ex.toString)
End Try
Return encrypted
End Function

Dim resultEncrypted as String = AES_Encrypt("UnprotectedStringToEncrypt")

'Output: �7��aS�2�p���Jg��gz����t��f�P�

Problem #1: The characters are obviously NOT in UTF8. Something wrong with the encoding even tough everything is set.
Problem #2: The AES encryption itself. Does NOT match with JAVA's correct output.

I tried to figure this one out for a while now.
I appreciate any kind of advice/help leading to the right way - THX!


[B@66fcc070 is not the correct output. The VB code appears to have the correct output.

If you take the UTF-8 bytes of this string: "UnprotectedStringToEncrypt"

And you use the UTF-8 bytes of this string as the key: "yt8yeqdXxpUyoUk3"

Then the AES ECB encrypt products this ciphertext:



[226, 55, 201, 227, 97, 83, 150, 50, 219, 112, 254, 145, 167, 74, 103, 135, 145, 103, 17, 122, 185, 190, 247, 205, 116, 215, 232, 102, 229, 80, 16, 155]

This is reproducible on any platform with any implementation of AES and will always produce the same ciphertext.

Your output: �7��aS�2�p���Jg��gz����t��f�P�

Has 7, a, S, p, J, g, z, t, f, and P in the correct positions. I can't tell if the ciphertext matches because of the � characters.

Your Java code is producing incorrect output (or at least, displaying incorrect output).