2022-11-09 20:48:03 +08:00
|
|
|
using System;
|
2021-05-28 19:09:36 +08:00
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
2021-11-09 15:23:23 +08:00
|
|
|
namespace SKIT.FlurlHttpClient.Wechat.Api.Utilities
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
2024-02-04 22:52:14 +08:00
|
|
|
using SKIT.FlurlHttpClient.Primitives;
|
|
|
|
|
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>
|
2024-02-04 22:52:14 +08:00
|
|
|
/// 计算 HMAC-SHA-256 哈希值。
|
2021-05-28 19:09:36 +08:00
|
|
|
/// </summary>
|
2024-02-04 22:52:14 +08:00
|
|
|
/// <param name="keyBytes">密钥字节数组。</param>
|
|
|
|
/// <param name="msgBytes">要计算哈希值的信息字节数组。</param>
|
|
|
|
/// <returns>哈希值字节数组。</returns>
|
|
|
|
public static byte[] HashWithSHA256(byte[] keyBytes, byte[] msgBytes)
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
2024-02-04 22:52:14 +08:00
|
|
|
if (keyBytes is null) throw new ArgumentNullException(nameof(keyBytes));
|
2024-01-29 23:11:56 +08:00
|
|
|
if (msgBytes is null) throw new ArgumentNullException(nameof(msgBytes));
|
2021-05-28 19:09:36 +08:00
|
|
|
|
2024-02-04 22:52:14 +08:00
|
|
|
#if NET5_0_OR_GREATER
|
|
|
|
return HMACSHA256.HashData(keyBytes, msgBytes);
|
|
|
|
#else
|
|
|
|
using HMAC hmac = new HMACSHA256(keyBytes);
|
2022-03-11 20:07:12 +08:00
|
|
|
return hmac.ComputeHash(msgBytes);
|
2024-02-04 22:52:14 +08:00
|
|
|
#endif
|
2021-05-28 19:09:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2024-02-04 22:52:14 +08:00
|
|
|
/// 计算 HMAC-SHA-256 哈希值。
|
2021-05-28 19:09:36 +08:00
|
|
|
/// </summary>
|
2024-02-04 22:52:14 +08:00
|
|
|
/// <param name="key">密钥。</param>
|
|
|
|
/// <param name="message">要计算哈希值的信息。</param>
|
|
|
|
/// <returns>经过十六进制编码的哈希值。</returns>
|
|
|
|
public static EncodedString HashWithSHA256(string key, string message)
|
2021-05-28 19:09:36 +08:00
|
|
|
{
|
2024-02-04 22:52:14 +08:00
|
|
|
if (key is null) throw new ArgumentNullException(nameof(key));
|
2024-01-29 23:11:56 +08:00
|
|
|
if (message is null) throw new ArgumentNullException(nameof(message));
|
2021-05-28 19:09:36 +08:00
|
|
|
|
2024-02-04 22:52:14 +08:00
|
|
|
byte[] keyBytes = EncodedString.FromLiteralString(key);
|
|
|
|
byte[] msgBytes = EncodedString.FromLiteralString(message);
|
|
|
|
byte[] hashBytes = HashWithSHA256(keyBytes, msgBytes);
|
|
|
|
return EncodedString.ToHexString(hashBytes);
|
2021-05-28 19:09:36 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|