2022-11-09 20:48:03 +08:00
|
|
|
using System;
|
2021-05-28 19:09:36 +08:00
|
|
|
using System.Security.Cryptography;
|
|
|
|
using System.Text;
|
|
|
|
|
2021-11-09 15:23:23 +08:00
|
|
|
namespace SKIT.FlurlHttpClient.Wechat.Api.Utilities
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
|
|
|
/// <summary>
|
2022-01-21 16:57:42 +08:00
|
|
|
/// HMAC 算法工具类。
|
2021-05-28 19:09:36 +08:00
|
|
|
/// </summary>
|
2022-01-21 16:57:42 +08:00
|
|
|
public static class HMACUtility
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
|
|
|
/// <summary>
|
2022-01-21 16:57:42 +08:00
|
|
|
/// 获取 HMAC-SHA-256 消息认证码。
|
2021-05-28 19:09:36 +08:00
|
|
|
/// </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)
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
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));
|
2021-05-28 19:09:36 +08:00
|
|
|
|
|
|
|
using HMAC hmac = new HMACSHA256(secretBytes);
|
2022-03-11 20:07:12 +08:00
|
|
|
return hmac.ComputeHash(msgBytes);
|
2021-05-28 19:09:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2022-01-21 16:57:42 +08:00
|
|
|
/// 获取 HMAC-SHA-256 消息认证码。
|
2021-05-28 19:09:36 +08:00
|
|
|
/// </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)
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
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));
|
2021-05-28 19:09:36 +08:00
|
|
|
|
|
|
|
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);
|
2021-05-28 19:09:36 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|