什么是PHP等效的PHP函数hash_hmac() [英] What is the .NET equivalent of the PHP function hash_hmac()

查看:252
本文介绍了什么是PHP等效的PHP函数hash_hmac()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些代码从PHP移植到.NET(我不是一个PHP开发人员),它看起来很简单,除了以下行:

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

如何将此函数移植到.NET?

How can I port this function to .NET?

base64编码如下,但是如何复制hash_hmac()?

The base64 encoding is done as follows, but how do I replicate hash_hmac()?

Convert.ToBase64String (System.Text.Encoding.ASCII.GetBytes(tmpString));

谢谢!

推荐答案

最后我设法创建一个基于HMACSHA1类的解决方案:

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 :压缩代码有点 - 对于这么多帮助函数。

UPDATED: Compacted code a bit - no need for so many helper functions.

这篇关于什么是PHP等效的PHP函数hash_hmac()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆