问题
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:
public function hash($message, $secret)
{
    return base64_encode(hash_hmac('sha1', $message, $secret));
}
How can I port this function to .NET?
The base64 encoding is done as follows, but how do I replicate hash_hmac()?
Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(tmpString));
Thanks!
回答1:
If you're looking for an HMAC then you should be using a class that derive from [System.Security.Cryptography.HMAC][1].
hash_hmac('sha1', $message, $secret)
In that case it would be [System.Security.Cryptography.HMACSHA1][2].
UPDATE (simpler code, not ASCII dependent)
static string Hash (string message, byte[] secretKey)
{
    using (HMACSHA1 hmac = new HMACSHA1(secretKey))
    {
        return Convert.ToBase64String(
           hmac.ComputeHash(System.Text.UTF8.GetBytes(message));
    }
}
    回答2:
Use a HashAlgorithm, namely the SHA1CryptoServiceProvider, for instance:
byte[] SHA1Hash (byte[] data)
{
    using (var sha1 = new SHA1CryptoServiceProvider()) 
    {
        return sha1.ComputeHash(data);
    }
}
    回答3:
In the end I managed to create a solution based on the HMACSHA1 class:
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.
来源:https://stackoverflow.com/questions/8063004/what-is-the-net-equivalent-of-the-php-function-hash-hmac