如何解决匹配签名哈希以匹配应用程序代码中的哈希以进行单元测试
我有一个端点,它接收一个 payload
,标头中有 timestamp
和 signature
值。除此之外,我还有一个保存在别处的 SecretKey
。
为了验证负载来自可信来源,我执行以下操作:
public bool Authenticate(payload,timestamp,signature)
{
// concat the timestamp header value with the serialized payload
var stringified = string.Concat(timestamp,JsonConvert.SerializeObject(payload));
// retrieve secret key
string secretKey = getSecretKey();
// compute hash
var hash = new HMACSHA256(secretKey.ConvertStringToByteArray());
var output = hash.ComputeHash(valuetoDigest.ConvertStringToByteArray());
return output == signature.ConvertStringToByteArray();
}
// an extension method I wrote that converts the string to Byte[]
public static Byte[] ConvertStringToByteArray(this string input)
{
var encoding = new UTF8Encoding();
return encoding.GetBytes(input);
}
在我的测试中,如何获取负载标头中包含的哈希值 (signature
) 以匹配我使用 secretKey
计算的哈希值,从而满足 return output == signature.ConvertStringToByteArray()
条件?
编辑:更新方法
public bool Authenticate(MyData payload,string timestamp,string signature)
{
// concat the timestamp header value with the serialized payload
var stringified = string.Concat(timestamp,JsonConvert.SerializeObject(payload));
// retrieve secret key
string secretKey = getSecretKey();
// compute hash
var hash = GetAuthHash(stringified,secretKey);
// do string comparison on the hash and the signature
return hash == signature;
}
public class MyData
{
public string id {get;set;}
public string name {get;set;}
}
public string GetAuthHash(string message,string secret)
{
var encoding = new UTF8Encoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。