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

user3635271 picture user3635271 · May 14, 2014 · Viewed 10.8k times · Source

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.)

Answer

user3814929 picture user3814929 · Sep 25, 2018

With different C# encoding

public static string SHA512_ComputeHash(string text, string secretKey)
{
    var hash = new StringBuilder(); ;
    byte[] secretkeyBytes = Encoding.UTF8.GetBytes(secretKey);
    byte[] inputBytes = Encoding.UTF8.GetBytes(text);
    using (var hmac = new HMACSHA512(secretkeyBytes))
    {
        byte[] hashValue = hmac.ComputeHash(inputBytes);
        foreach (var theByte in hashValue)
        {
            hash.Append(theByte.ToString("x2"));
        }
    }

    return hash.ToString();
}