AES Encryption in Java and Decryption in C#

Your code has one big problem: It is mixing the character encodings!

In Java you are calling key.getBytes(), without arguments. This method returns the UTF-8 or CP1252/ISO 8859-1 encoded data depending on your operating system and the default charset in Java.

On C# side you are using Encoding.Unicode.GetBytes(key)“Unicode” in .Net is a synonym for double byte characters alias UTF-16 (Little-Endian). Therefore you are using a different key in C#.

You should be able to see the difference by comparing the number of bytes in Java and C#:

Java: "=abcd!#Axd*G!pxP".getBytes().length = 16

C#: Encoding.Unicode.GetBytes("=abcd!#Axd*G!pxP").Length = 32

I strongly recommend you to use byte arrays instead of Strings for defining a cryptographic key.

Update: Another difference is that you are setting an initialization vector (IV) in C# which you don’t do in Java. As you are using ECB the IV should not be used but if you change to CBC for example this makes a big difference.

Leave a Comment