0

我正在尝试使用 Webhook 并在目标框架 4.6.2 的 webapi 中使用 HMAC 进行验证,但它失败了。我正在这样做。在 post 方法中,我有这个 validateHMAC 方法,其余的代码过程如下

    bool  isvalid = ValidateHMAC();

     private bool ValidateHMAC()
    {
        string hmacSignature1 = string.Empty;
        System.Net.Http.Headers.HttpRequestHeaders headers = Request.Headers;
        if (headers.Contains("X-DocuSign-Signature-1"))
        {
            hmacSignature1 = headers.GetValues("X-DocuSign-Signature-1").First();
        }

        string requestFromPost = string.Empty;

        using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
        {
            reader.BaseStream.Position = 0;
            requestFromPost = reader.ReadToEnd();
        }

        return HashIsValid(requestFromPost, hmacSignature1);
    }
    private string ComputeHash(string payload)
    {
        string docuSignHMACSecretKey = "KXXXXKXXKXKXKXXXX-FFDocuSignHMACKey"; //LIKE THIS
        byte[] bytes = Encoding.UTF8.GetBytes(docuSignHMACSecretKey);
        System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(bytes);
        bytes = Encoding.UTF8.GetBytes(payload);
        bytes = hmac.ComputeHash(bytes);
        var computedHash = Convert.ToBase64String(bytes);
        return computedHash;
    }
    private bool HashIsValid(string payload, string verify)
    {
        var hashOutput = ComputeHash(payload).Equals(verify);
        return hashOutput;
    }
4

1 回答 1

0

试试这个代码:

using System;
using System.Text;
using System.Security.Cryptography;

public static class HMACValidation
{
    public static string ComputeHash(string secret, string payload)
    {
    byte[] bytes = Encoding.UTF8.GetBytes(secret);
    HMAC hmac = new HMACSHA256(bytes);
    bytes = Encoding.UTF8.GetBytes(payload);

    return Convert.ToBase64String(hmac.ComputeHash(bytes));
    }




    public static bool HashIsValid(string secret, string payload, string verify)
    {

    ReadOnlySpan<byte> hashBytes = Convert.FromBase64String(ComputeHash(secret, payload));
    ReadOnlySpan<byte> verifyBytes = Convert.FromBase64String(verify);

    return CryptographicOperations.FixedTimeEquals(hashBytes, verifyBytes);
    }
}
于 2021-11-11T23:19:14.677 回答