在C#中生成HMAC-SHA1 [英] generate HMAC-SHA1 in C#

查看:516
本文介绍了在C#中生成HMAC-SHA1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#使用REST API。

I am trying to make use of a REST API using C#.

API创建者在下面提供了用于创建hmac的伪代码。

The API creator has provided below pseudo code for hmac creation.

var key1 = sha1(body);
var key2 = key1 . SECRET_KEY;
var key3 = sha1(key2);
var signature = base64_encode(key3);

在上面的伪代码中,body是html request body string,而SECRET_KEY

In the above pseudo code , body is html request body string , and SECRET_KEY is the secret key provided by REST API provider.

据我所知,我需要使用System.Security.Cryptography.HMACSHA1类
来实现这一点。

As per my knowledge , I need to use System.Security.Cryptography.HMACSHA1 class to implement this.

但是无法完全在C#中实现上述逻辑。

But am not able to completely implement above logic in C#.

有什么建议吗?

推荐答案

将上面的代码直接映射到C#就像是这样:

Direct mapping of above code to C# would be something like:

static string ComputeSignature(byte[] body, byte[] secret) {
    using (var sha1 = SHA1.Create())
    {
        var key1 = sha1.ComputeHash(body);
        var key2 = key1.Concat(secret).ToArray();
        var key3 = sha1.ComputeHash(key2);
        return Convert.ToBase64String(key3);
    }
}

如果将请求正文作为字符串,请将其转换使用正确的编码转换为字节数组,例如:

If you have request body as a string, convert it to byte array using proper encoding, for example:

var body = Encoding.UTF8.GetBytes(bodyAsString);

如果您的秘密作为字符串-这取决于api开发人员期望它如何转换为字节数组。很可能已经是十六进制或base64编码的字符串。

If you have your secret as string - that depends on how api developer expects it to be converted to byte array. Most likely it's already HEX or base64-encoded string.

这篇关于在C#中生成HMAC-SHA1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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