匹配签名哈希以匹配应用程序代码中的哈希以进行单元测试

问题描述

我有一个端点,它接收一个 payload,标头中有 timestampsignature 值。除此之外,我还有一个保存在别处的 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 (将#修改为@)