DotNetCore.SKIT.FlurlHttpCl.../src/SKIT.FlurlHttpClient.Wechat.TenpayV2/Utilities/HMACUtility.cs

45 lines
1.7 KiB
C#
Raw Normal View History

2022-01-20 23:20:03 +08:00
using System;
using System.Security.Cryptography;
using System.Text;
namespace SKIT.FlurlHttpClient.Wechat.TenpayV2.Utilities
{
/// <summary>
/// HMAC 算法工具类。
/// </summary>
public static class HMACUtility
{
/// <summary>
/// 获取 HMAC-SHA-256 消息认证码。
/// </summary>
/// <param name="secretBytes">密钥字节数组。</param>
2022-03-11 20:07:12 +08:00
/// <param name="msgBytes">信息字节数组。</param>
/// <returns>消息认证码字节数组。</returns>
public static byte[] HashWithSHA256(byte[] secretBytes, byte[] msgBytes)
2022-01-20 23:20:03 +08:00
{
if (secretBytes == null) throw new ArgumentNullException(nameof(secretBytes));
2022-03-11 20:07:12 +08:00
if (msgBytes == null) throw new ArgumentNullException(nameof(msgBytes));
2022-01-20 23:20:03 +08:00
using HMAC hmac = new HMACSHA256(secretBytes);
2022-03-11 20:07:12 +08:00
return hmac.ComputeHash(msgBytes);
2022-01-20 23:20:03 +08:00
}
/// <summary>
/// 获取 HMAC-SHA-256 消息认证码。
/// </summary>
/// <param name="secret">密钥。</param>
/// <param name="message">文本信息。</param>
2022-03-11 20:07:12 +08:00
/// <returns>消息认证码。</returns>
2022-01-20 23:20:03 +08:00
public static string HashWithSHA256(string secret, string message)
{
if (secret == null) throw new ArgumentNullException(nameof(secret));
if (message == null) throw new ArgumentNullException(nameof(message));
byte[] secretBytes = Encoding.UTF8.GetBytes(secret);
2022-03-11 20:07:12 +08:00
byte[] msgBytes = Encoding.UTF8.GetBytes(message);
byte[] hashBytes = HashWithSHA256(secretBytes, msgBytes);
return BitConverter.ToString(hashBytes).Replace("-", "");
2022-01-20 23:20:03 +08:00
}
}
}