C# 和 Java 的哈希结果是不同的



我正在尝试散列数据"文本"以从Java服务传输到C#服务。 我使用 SHA256 作为哈希算法,但尽管值和盐相同,但结果并非如此。

这是我的 C# 代码段

public string Sign(string textToHash, string salt){
byte[] convertedHash = new byte[salt.Length / 2];
for (int i = 0; i < salt.Length / 2; i++)
convertedHash[i] = (byte)int.Parse(salt.Substring(i * 2, 2), NumberStyles.HexNumber);

HMAC hasher = new HMACSHA256(convertedHash);

string hexHash = "";
using (hasher)
{
byte[] hashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes(textToHash));
foreach (byte b in hashValue)
{
hexHash += b.ToString("X2");
}
}
return hexHash;
}

而且,这是Java代码片段

public static String sign(String textToHash, String salt){

byte[] convertedHash = new byte[salt.length() / 2];
for (int i = 0; i < salt.length() / 2; i++)
{
convertedHash[i] = (byte)Integer.parseInt(salt.substring(i * 2, i * 2 + 2),16);
}
String hashedText = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(convertedHash);
byte[] bytes = md.digest(textToHash.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte aByte : bytes) {
sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
}
hashedText = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hashedText;
}

在Java中,我也尝试过

convertedHash = salt.getBytes();

但我也得到了不同的结果。

测试:

salt = ABCDEFG
text = hashme

在 C# 中的结果

70B38047C28FFEDCF7275C428E65310671CADB65F11A5C9A8CFBB3CF52112BA3

在爪哇中的结果

a8bc36606aade01591a1d12c8b3c87aca1fe55def79740def03a90b49f2c6b7c

因此,有关结果为何不同的任何帮助。

提前谢谢。

为了模仿Java哈希,我在C#中使用了SHA256Managed而不是HMACSHA256

public static string Sign(string data, string salt)
{
UTF8Encoding encoder = new UTF8Encoding();
SHA256Managed sha256hasher = new SHA256Managed();
byte[] convertedHash = new byte[salt.Length / 2];
for (int i = 0; i < salt.Length / 2; i++)
convertedHash[i] = (byte)int.Parse(salt.Substring(i * 2, 2), NumberStyles.HexNumber);
byte[] dataBytes = encoder.GetBytes(data);
byte[] bytes = new byte[convertedHash.Length + dataBytes.Length];

Array.Copy(convertedHash, bytes, convertedHash.Length);
Array.Copy(dataBytes, 0, bytes, convertedHash.Length, dataBytes.Length);
byte[] hashedBytes = sha256hasher.ComputeHash(bytes);
return hashedBytes.Aggregate("", (current, t) => current + t.ToString("X2"));
}

HMACSHA256不是纯粹的SHA-256.

相关内容

最新更新