指南ASP.NET 中的请求签名

本文介绍了在 ASP.NET 中实现 请求签名 的示例。

# 依赖项

此示例使用来自 ASP.NET 的 System 依赖项。

# 示例

以下简单示例实现了 请求签名 指南中描述的算法。最重要的是使用 System.Security.Cryptography 中的 HMACSHA256,并将参数按正确的顺序传递:methodurltimestampbody

method 参数应为大写,path 应仅包含 URL 中的相对路径和查询参数,不包含完整的 URL 地址。完整的 URL 地址应转换为例如 /webhook?a=1

如果算法正常工作,它应该生成与下面给出的签名相同的签名:56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762,适用于以下参数

  • apiSecret=SECRET

  • method=POST

  • uri=http://demo.example.com/webhook?a=1

  • timestamp=1563276169752

  • body={a:1}

using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Security.Cryptography;

public class Program
{
    public static void Main()
    {
        string signature = GenerateSignature(
            "SECRET",
            "POST",
            "http://demo.example.com/webhook?a=1",
            1563276169752,
            new { a = 1 }
        );

        Console.WriteLine(
            signature == "56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762"
        );
    }

    public static string GenerateSignature(
        string apiSecret,
        string method,
        string uri,
        long timestampMilliseconds,
        object body = null
    )
    {
        string upperMethod = method.ToUpper();
        Uri url = new Uri(uri);
        string path = url.AbsolutePath + url.Query;
        string message = upperMethod + path + timestampMilliseconds;

        if (body != null && (upperMethod == "POST" || upperMethod == "PUT"))
        {
            string bodyString = JsonSerializer.Serialize(body);
            message += bodyString;
        }

        return HmacSha256Digest(message, apiSecret);
    }

    public static string HmacSha256Digest(string message, string secret)
    {
        UTF8Encoding utf8Encoder = new UTF8Encoding();
        byte[] encodedSecret = utf8Encoder.GetBytes(secret);
        byte[] encodedMessage = utf8Encoder.GetBytes(message);

        HMACSHA256 hmac256 = new HMACSHA256(encodedSecret);
        byte[] messageHash = hmac256.ComputeHash(encodedMessage);

        return BitConverter.ToString(messageHash).Replace("-", "").ToLower();
    }
}