Java MD5 hashing does not match C # MD5 hashing

I know very little about encryption / hashing.

I need to hash an encryption key. An example in Java is this:

String encryptionKey = "test"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(encryptionKey.getBytes("UTF-8"), 0, encryptionKey.length()); byte[] encryptionKeyBytes = messageDigest.digest(); 

Now correct me if I am wrong, but the code above hashes the line with the MD5 algorithm.

And I want to get the same result when I have the same line in C #.

My current C # code looks like this ...

 string encryptionKey = "test"; var md5 = MD5.Create(); var keyBytes = Encoding.UTF8.GetBytes(encryptionKey); byte[] encryptionKeyBytes = md5.ComputeHash(keyBytes); 

But the final byte results do not match.

Java gets ...

 [0] 9 [1] -113 [2] 107 [3] -51 [4] 70 [5] 33 [6] -45 [7] 115 [8] -54 [9] -34 [10] 78 [11] -125 [12] 38 [13] 39 [14] -76 [15] -10 

C # gets ...

  [0] 9 byte [1] 143 byte [2] 107 byte [3] 205 byte [4] 70 byte [5] 33 byte [6] 211 byte [7] 115 byte [8] 202 byte [9] 222 byte [10] 78 byte [11] 131 byte [12] 38 byte [13] 39 byte [14] 180 byte [15] 246 byte 

I need my C # code to get the same result as Java code (and not vice versa), any ideas?

Thanks.

+4
source share
1 answer

Actually, the results are identical. Like other integral types, the byte value can be interpreted as signed or unsigned. For example, 10001111 corresponds to 143 (your second C # value) if it is interpreted as unsigned. However, if interpreted as signed (using the twos add-on ), its value will be -113 (your second Java value).

So the mismatch is apparently caused by the fact that your values ​​are formatted as signed in Java, but unsigned in C #. If you want to get signed bytes in C #, you can use:

 sbyte[] encryptionKeyBytesSigned = encryptionKeyBytes.Select(b => (sbyte)b).ToArray(); 

However, be careful that this is not just a formatting problem that only occurs when your values ​​are displayed. When saving to a file, both results must be identical.

+11
source

All Articles