Hash value generation using hmac/sha512 in java and c#
12,385
Solution 1
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);
Solution 2
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();
}
Author by
user3635271
Updated on June 08, 2022Comments
-
user3635271 almost 2 years
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.)