I am getting different values when using shA256.ComputeHash(hexByte)
from C# and
byte[] hash = digest.digest();
in Java. I get the same values in C# and Java when converting stringToHexByte()
. Please see how I do it below.
C#
protected static string ComputeHash(string str)
{
if (str.Length % 2 == 1)
str += "0";
SHA256 shA256 = (SHA256) new SHA256CryptoServiceProvider();
str += "110983".ToString();
byte[] hexByte = StringToHexByte(str); // hexByte same as JAVA hexByte
byte[] hash = shA256.ComputeHash(hexByte);
return string.Empty();
}
protected static byte[] StringToHexByte(string str)
{
int length1 = str.Length / 2;
byte[] numArray = new byte[length1];
int length2 = str.Length;
for (int index = 0; index <= length1 - 1; ++index)
numArray[index] = length2 - index * 2 <= 1 ?
byte.Parse(str.Substring(index * 2, 2)) :
byte.Parse(str.Substring(index * 2, 2));
return numArray;
}
Java
private static String computeHash(String str) throws NoSuchAlgorithmException
{
if (str.length() % 2 == 1)
str += "0";
str += "110983".toString();
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] hexByte = stringToHexByteLcs(str); // hexByte same as C# hexByte
digest.update(hexByte);
byte[] hash = digest.digest();
String str1 = convertToHexString(hash, 0, hash.length)
}
private static byte[] stringToHexByteLcs(String str) {
int length1 = str.length()/2;
byte[] numArray = new byte[length1];
int length2 = str.length();
for (int index = 0; index < length1; ++index) {
numArray[index] = Byte.parseByte(length2 - index * 2 <= 1 ?
new String(str.getBytes(), index * 2, 2) :
new String(str.getBytes(), index * 2, 2));
}
return numArray;
}
I get the same number of arrays, but the values are different. In Java I get negative values while in C# all are positive values.
C#
Java