hash_hmac method c#
-
I'm trying to find analog a function.
hash_hmac('sha512'..
for c#. Found the next code.var rez= Hash("privet", GetBytes(12345));
c#
Nzg3OGNmMmJhZGRiOTM4NTY1NTc4MjgwOGE3ZDNlNDFlMDBhNTBkMGY1NWFhMzJlM2RiNDkxZTUwMjQ5ODZkOTUwMWUyOWU0YzY1YTNlY2UwYzI0N2VmZGI5NmMxZjVlNGEwOTdhMGJlYmI2YzFlYTk1MmZjYjM5YWY0M2RlZTY=
And php
$sign = hash_hmac('sha512', 'privet', '12345');
f7ff9475713b9ec97b4042502e472e9c081bcd5ae6ae419ad7f3603933e772fb29cb51599964643fe5f16cc692a2be7410878f5a76d1570947f570c26e0cc8f8
Where am I wrong, friends?
private string Hash(string message, byte[] secretKey) { byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(message); byte[] hashBytes; using (HMACSHA512 hmac = new HMACSHA512(secretKey)) { hashBytes = hmac.ComputeHash(msgBytes); } var sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) sb.Append(hashBytes[i].ToString("x2")); string hexString = sb.ToString(); byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(hexString); return System.Convert.ToBase64String(toEncodeAsBytes); }
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
-
Use the usual.
Encoding.GetBytes
To get a white key. And get the result.hexString
I don't know how it is, don't encode his bikes again like base64. This is a working option that gives the same result you have in PHP:private static string Hash(string message, string secretKey) { var encoding = System.Text.Encoding.UTF8; byte[] msgBytes = encoding.GetBytes(message); var keyBytes = encoding.GetBytes(secretKey); using (HMACSHA512 hmac = new HMACSHA512(keyBytes)) { byte[] hashBytes = hmac.ComputeHash(msgBytes);
var sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) sb.Append(hashBytes[i].ToString("x2")); return sb.ToString(); }
}
static void Main(string[] args)
{
Console.WriteLine(Hash("privet", "12345"));
}