Calculating SHA-1 hash values in Java and c#
Calculating SHA-1 hash values in Java and c#
I'm trying to copy the logic of a Java application in a c# application This is partly because the Sha - 1 hash of the password is generated Unfortunately, I can't get the same results from Java and C #
C# Output : 64 0a b2 ba e0 7b ed c4 c1 63 f6 79 a7 46 f7 ab 7f b5 d1 fa Java Output: 164 10a b2 ba e0 17b ed c4 c1 163 f6 179 a7 146 f7 ab 17f b5 d1 fa
To figure out what happened, I've been using debugger in eclipse and visual studio
1. Check values of byte[] key: Java: { 84,101,115,116 } C# : { 84,116 } 2. Check value of byte[] hash: Java: { 100 10 -78 -70 -32 123 ... } C# : { 100 10 78 186 224 123 ... }
I've read other posts on this topic, mainly referring to input string encoding, but these don't seem to help me My guess is that this is related to signed and unsigned bytes, but I haven't made much progress on this track Any help would be appreciated
thank you,
Karle
Java version:
public void testHash() { String password = "Test"; byte[] key = password.getBytes(); MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = md.digest(key); String result = ""; for ( byte b : hash ) { result += Integer.toHexString(b + 256) + " "; } System.out.println(result); }
C# version:
public void testHash() { String password = "Test"; byte[] key = System.Text.Encoding.Default.GetBytes(password); SHA1 sha1 = SHA1Managed.Create(); byte[] hash = sha1.ComputeHash(key); String result; foreach ( byte b in hash ) { result += Convert.ToInt32(b).ToString("x2") + " "; } Console.WriteLine(result); }
Solution
In the Java version, do not use B 256; Instead, use b& 255 Sha - 1 part is very good. It's just a matter of printout Java's byte type is signed: it returns a value between - 128 and 127 To get the corresponding unsigned value, you must add 256 only if the value is negative
Bitwise and (i.e. "& 255") with 255 operates the correct conversion. At the binary level, this value truncates the value to its 8 least significant bits