我正在将一些代码从PHP移植到。net(我不是PHP开发人员),除了下面这行,这一切看起来都很简单:
public function hash($message, $secret)
{
return base64_encode(hash_hmac('sha1', $message, $secret));
}
我如何将这个函数移植到。net ?
base64编码如下所示,但我如何复制hash_hmac()?
Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(tmpString));
谢谢!
如果你正在寻找一个HMAC那么你应该使用一个从[System.Security.Cryptography.HMAC][1]
派生的类。
hash_hmac('sha1', $message, $secret)
在这种情况下,它将是[System.Security.Cryptography.HMACSHA1][2]
。
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));
}
}
使用HashAlgorithm
,即SHA1CryptoServiceProvider
,例如:
byte[] SHA1Hash (byte[] data)
{
using (var sha1 = new SHA1CryptoServiceProvider())
{
return sha1.ComputeHash(data);
}
}
最后,我设法创建了一个基于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);
}
更新:代码压缩了一点-不需要那么多的辅助函数