C# 在C中生成HMAC-SHA1#
我正在尝试使用C#使用RESTAPI API创建者为hmac创建提供了以下伪代码C# 在C中生成HMAC-SHA1#,c#,cryptography,C#,Cryptography,我正在尝试使用C#使用RESTAPI API创建者为hmac创建提供了以下伪代码 var key1 = sha1(body); var key2 = key1 . SECRET_KEY; var key3 = sha1(key2); var signature = base64_encode(key3); 在上面的伪代码中,body是html请求body字符串和SECRET_KEY 是REST API提供程序提供的密钥 据我所知,我需要使用System.Security.Cryptograph
var key1 = sha1(body);
var key2 = key1 . SECRET_KEY;
var key3 = sha1(key2);
var signature = base64_encode(key3);
在上面的伪代码中,body是html请求body字符串和SECRET_KEY
是REST API提供程序提供的密钥
据我所知,我需要使用System.Security.Cryptography.HMACSHA1类
为了实现这一点
但我无法在C#中完全实现上述逻辑
有什么建议吗?将上述代码直接映射到C#将类似于:
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);
}
}
如果将请求正文作为字符串,请使用适当的编码将其转换为字节数组,例如:
var body = Encoding.UTF8.GetBytes(bodyAsString);
若您将秘密作为字符串—这取决于api开发人员希望如何将其转换为字节数组。很可能它已经是十六进制或base64编码的字符串。在c#中使其工作的问题是需要考虑十六进制格式,然后在某些情况下,为了使其工作,最终结果应该是小写的(例如,如果您将其用于quickblox api或其他东西)
private string GetHashedMessage(string\u secret)
{
System.Text.asciencoding encoding=新的System.Text.asciencoding();
byte[]keyByte=encoding.GetBytes(_secret);
String _message=“您需要散列的消息”;
HMACSHA1 HMACSHA1=新的HMACSHA1(密钥字节);
byte[]messageBytes=encoding.GetBytes(_message);
byte[]hashmessage=hmacsha1.ComputeHash(messageBytes);
返回ByteToString(hashmessage.ToLower();
}
公共字符串ByteToString(字节[]buff)
{
字符串sbinary=“”;
for(int i=0;i
参考:
private string GetHashedMessage(String _secret)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(_secret);
String _message= "Your message that needs to be hashed";
HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
byte[] messageBytes = encoding.GetBytes(_message);
byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
return ByteToString(hashmessage).ToLower();
}
public string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2"); // hex format
}
return (sbinary);
}