AES Encryption in Java and Decryption in C#

后端 未结 4 806
终归单人心
终归单人心 2020-11-30 06:19

Hello I\'ve Encrypted Hex string and Key that has been encrypted using standard AES Algorithm. Code:

        final String key = \"=abcd!#Axd*G!pxP\";
                


        
4条回答
  •  忘掉有多难
    2020-11-30 06:54

    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.

提交回复
热议问题