Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

asp.net - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...