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

45 lines
1.7 KiB
C#
Raw Normal View History

2022-11-09 20:48:03 +08:00
using System;
using System.Security.Cryptography;
using System.Text;
namespace SKIT.FlurlHttpClient.Wechat.Api.Utilities
{
/// <summary>
2022-01-21 16:57:42 +08:00
/// HMAC 算法工具类。
/// </summary>
2022-01-21 16:57:42 +08:00
public static class HMACUtility
{
/// <summary>
2022-01-21 16:57:42 +08:00
/// 获取 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)
{
2024-01-29 23:11:56 +08:00
if (secretBytes is null) throw new ArgumentNullException(nameof(secretBytes));
if (msgBytes is null) throw new ArgumentNullException(nameof(msgBytes));
using HMAC hmac = new HMACSHA256(secretBytes);
2022-03-11 20:07:12 +08:00
return hmac.ComputeHash(msgBytes);
}
/// <summary>
2022-01-21 16:57:42 +08:00
/// 获取 HMAC-SHA-256 消息认证码。
/// </summary>
/// <param name="secret">密钥。</param>
/// <param name="message">文本信息。</param>
2022-03-11 20:07:12 +08:00
/// <returns>消息认证码。</returns>
2022-01-21 16:57:42 +08:00
public static string HashWithSHA256(string secret, string message)
{
2024-01-29 23:11:56 +08:00
if (secret is null) throw new ArgumentNullException(nameof(secret));
if (message is 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);
2022-11-09 20:48:03 +08:00
return BitConverter.ToString(hashBytes).Replace("-", string.Empty);
}
}
}