I'm trying to hash the same string in C# and in Java.
C# hash method:
public static string hashValue (string value)
{
byte[] input = null;
HashAlgorithm digest = HashAlgorithm.Create("SHA-512");
input = digest.ComputeHash(Encoding.UTF8.GetBytes(value));
return System.Text.UTF8Encoding.UTF8.GetString(input);
}
The output, in a WPF TextBox, for this is looking like: ""�?N[��"��2��D��j��t!z}7�H�p�J����GƼOp�EnBfHڄ�X���" .
The same function, in Java, is returning the result: "[B@41e2db20".
The Java hash method like this:
public static String hashValue(String value) {
byte[] input = null;
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-512");
try {
input = digest.digest(value.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return input.toString();
}
Can you please let me know what I'm doing wrong? Why is the result looking that weird in C#?
Your C# result is looking "weird" because you've converted the random bytes of a hash into a UTF-8 string. That isn't going to result in anything pretty-looking, since many of the byte values will map to unprintable characters.
You may wish to convert the hash to hexadecimal instead. For that, use the DatatypeConverter class:
return DatatypeConverter.printHexBinary(input);
I'm not sure the C# equivalent - but check Google.
For the record, the Java equivalent of your current C# code would be:
return new String(input, "UTF-8");
Currently you are calling .toString(), which for a Java byte array results in a call to the Object.toString() method. This prints the type and hashcode of the object, but not the contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With