NickG
NickG

Reputation: 9802

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:

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!

Upvotes: 1

Views: 3124

Answers (3)

NickG
NickG

Reputation: 9802

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.

Upvotes: 1

poupou
poupou

Reputation: 43543

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));
    }
}

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

Use a HashAlgorithm, namely the SHA1CryptoServiceProvider, for instance:

byte[] SHA1Hash (byte[] data)
{
    using (var sha1 = new SHA1CryptoServiceProvider()) 
    {
        return sha1.ComputeHash(data);
    }
}

Upvotes: 1

Related Questions