Search code examples
c#javahashhmacsha512

Hash value generation using hmac/sha512 in java and c#


in c#

public static string HashToString(string message, byte[] key)

{

  byte[] b=new HMACSHA512(key).ComputeHash(Encoding.UTF8.GetBytes(message));

  return Convert.ToBase64String(b);

}

client.DefaultRequestHeaders.Add("X-Hash", hash);

var encryptedContent = DataMotion.Security.Encrypt(key, Convert.FromBase64String(iv), serializedModel);

var request = client.PostAsync(ApiUrlTextBox.Text,encryptedContent,new JsonMediaTypeFormatter());

in java:

protected String hashToString(String serializedModel, byte[] key) {

String result = null;

Mac sha512_HMAC;

try {

  sha512_HMAC = Mac.getInstance("HmacSHA512");      

  SecretKeySpec secretkey = new SecretKeySpec(key, "HmacSHA512");

  sha512_HMAC.init(secretkey);

   byte[] mac_data = sha512_HMAC.doFinal(serializedModel.getBytes("UTF-8"));        

   result = Base64.encodeBase64String(mac_data);

}catch(Exception e){
}
}

o/p: ye+AZPqaKrU14pui4U5gBCiAbegNvLVjzVdGK3rwG9QVzqKfIgyWBDTncORkNND3DA8jPba5xmC7B5OUwZEKlQ==

i have written hashtostring method in java based on c# code. is this currect? (output is different because every time process is dynamic in both cases.)


Solution

  • Both java and C# code are giving same result(same hash code). You should check again.

    Replace following line in java code at end

    result = Base64.getEncoder().encodeToString(mac_data);