[英]What is the .NET equivalent of the PHP function hash_hmac()
I'm porting some code from PHP to .NET (I'm not a PHP developer) and it all looks pretty straightforward apart from the following line: 我正在将一些代码从PHP移植到.NET(我不是PHP开发人员),除了以下几行之外,它们看起来都非常简单:
public function hash($message, $secret)
{
return base64_encode(hash_hmac('sha1', $message, $secret));
}
How can I port this function to .NET? 如何将该功能移植到.NET?
The base64 encoding is done as follows, but how do I replicate hash_hmac()? base64编码按以下方式完成,但是如何复制hash_hmac()?
Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(tmpString));
Thanks! 谢谢!
If you're looking for an HMAC then you should be using a class that derive from [System.Security.Cryptography.HMAC][1]
. 如果您正在寻找HMAC,则应该使用从
[System.Security.Cryptography.HMAC][1]
派生的类。
hash_hmac('sha1', $message, $secret)
hash_hmac('sha1',$ message,$ secret)
In that case it would be [System.Security.Cryptography.HMACSHA1][2]
. 在这种情况下,它将是
[System.Security.Cryptography.HMACSHA1][2]
。
UPDATE (simpler code, not ASCII dependent) UPDATE(简单代码,不依赖ASCII)
static string Hash (string message, byte[] secretKey)
{
using (HMACSHA1 hmac = new HMACSHA1(secretKey))
{
return Convert.ToBase64String(
hmac.ComputeHash(System.Text.UTF8.GetBytes(message));
}
}
Use a HashAlgorithm
, namely the SHA1CryptoServiceProvider
, for instance: 使用
HashAlgorithm
,即SHA1CryptoServiceProvider
,例如:
byte[] SHA1Hash (byte[] data)
{
using (var sha1 = new SHA1CryptoServiceProvider())
{
return sha1.ComputeHash(data);
}
}
In the end I managed to create a solution based on the HMACSHA1 class: 最后,我设法创建了一个基于HMACSHA1类的解决方案:
private string Hash(string message, byte[] secretKey)
{
byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(message);
byte[] hashBytes;
using (HMACSHA1 hmac = new HMACSHA1(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);
}
UPDATED : Compacted code a bit - no need for so many helper functions. 更新 :压缩了一点代码-不需要那么多的辅助函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.