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!";
byte[] hmac = GenerateHmac(key, message);
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)
{
HMACSHA256 hmac = new HMACSHA256();
hmac.Key = Convert.FromBase64String(key);
hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
return hmac.Hash;
}
private static bool VerifyHmac(string key, string message, byte[] hmac)
{
HMACSHA256 hmacVerifier = new HMACSHA256();
hmacVerifier.Key = Convert.FromBase64String(key);
return hmacVerifier.VerifyHash(Encoding.UTF8.GetBytes(message), hmac);
}
}