在C#中,可以使用System.Security.Cryptography.HMAC类来实现Java中的HmacUtils方法。

首先,需要引入System.Security.Cryptography命名空间。

然后,可以通过以下方式使用HMAC类来计算HMAC值:

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

public class HmacUtils
{
    public static string ComputeHmac(HmacAlgorithm algorithm, string key, string message)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] messageBytes = Encoding.UTF8.GetBytes(message);

        HMAC hmac;

        switch (algorithm)
        {
            case HmacAlgorithm.HmacMD5:
                hmac = new HMACMD5(keyBytes);
                break;
            case HmacAlgorithm.HmacSHA1:
                hmac = new HMACSHA1(keyBytes);
                break;
            case HmacAlgorithm.HmacSHA256:
                hmac = new HMACSHA256(keyBytes);
                break;
            // Add more cases for other HMAC algorithms if needed
            default:
                throw new ArgumentException("Invalid algorithm");
        }

        byte[] hmacBytes = hmac.ComputeHash(messageBytes);

        return Convert.ToBase64String(hmacBytes);
    }
}

public enum HmacAlgorithm
{
    HmacMD5,
    HmacSHA1,
    HmacSHA256
}

public class Program
{
    public static void Main(string[] args)
    {
        string key = "your_key";
        string message = "your_message";
        string hmac = HmacUtils.ComputeHmac(HmacAlgorithm.HmacSHA256, key, message);
        
        Console.WriteLine(hmac);
    }
}

在上述示例中,ComputeHmac方法接受一个HmacAlgorithm参数,该参数用于指定要使用的HMAC算法。然后根据算法初始化相应的HMAC对象,并使用给定的密钥和消息计算HMAC值。最后,将计算得到的HMAC值转换为Base64编码的字符串并返回。

你可以根据需要选择适合的HmacAlgorithm枚举值,例如HmacAlgorithm.HmacMD5HmacAlgorithm.HmacSHA1HmacAlgorithm.HmacSHA256

Java 的 HmacUtilsHmacAlgorithms algorithm String key 方法转C#

原文地址: https://www.cveoy.top/t/topic/hJCF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录