I am facing an issue while trying to integrate HMACSHA256 (hashing) in different programmng languages. I have tried to implement the standard algorith with standard predefined methods in Java and C# and I am getting different results in different languages. Please see below my implementations in Java and C#:
Java:
public static String convertSHAWithSalt(String value, String salt)
throws NoSuchAlgorithmException, InvalidKeyException {
String data = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt.getBytes(StandardCharsets.UTF_8));
byte[] bytes = md.digest(value.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
data = sb.toString();
System.out.println(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
Result for string value 'abcd' and an empty salt value: 88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589
C#:
public static string createHash(string message, string secret)
{
byte[] keyByte = System.Text.Encoding.UTF8.GetBytes(secret);
byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(message);
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return BitConverter.ToString(hashmessage).Replace("-", "").ToLower();
}
Result for string value 'abcd' and an empty salt value: 527ff4c28c22a090fe39908139363e81b8fb10d0695a135518006abfa21cf5a2
Please suggest why there is a difference in both of the results. I have also tried the below implementation in java but it is not working for empty salt value:
public static String convertSHAWithSalt(String value, String salt)
throws NoSuchAlgorithmException, InvalidKeyException {
String data = "";
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretkey = new SecretKeySpec(salt.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256Hmac.init(secretkey);
data = bytesToHex(sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
System.out.println(data);
}