编辑代码

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

public class HmacExample
{
    public static void Main()
    {
        var now = DateTime.UtcNow;
        // 定义密钥和消息
        string key = "secret";
        string message = "Hello, world!";

        // 使用 HMAC-SHA256 算法生成 HMAC 值
        byte[] hmac = GenerateHmac(key, message);

        // 将 HMAC 值附加到消息中
        string signedMessage = message + hmac;

        // 接收方接收到消息后,可以使用相同的密钥验证数据完整性
        byte[] receivedHmac = signedMessage.Substring(message.Length).ToByteArray();
        bool isVerified = VerifyHmac(key, message, receivedHmac);

        // 打印验证结果
        Console.WriteLine("验证结果:{0}", isVerified);
    }

    private static byte[] GenerateHmac(string key, string message)
    {
        // 创建一个 HMAC 对象
        HMACSHA256 hmac = new HMACSHA256();

        // 设置密钥
        hmac.Key = Convert.FromBase64String(key);

        // 计算 HMAC 值
        hmac.ComputeHash(Encoding.UTF8.GetBytes(message));

        return hmac.Hash;
    }

    private static bool VerifyHmac(string key, string message, byte[] hmac)
    {
        // 创建一个 HMAC 对象
        HMACSHA256 hmacVerifier = new HMACSHA256();

        // 设置密钥
        hmacVerifier.Key = Convert.FromBase64String(key);

        // 验证 HMAC 值
        return hmacVerifier.VerifyHash(Encoding.UTF8.GetBytes(message), hmac);
    }
}