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

45 lines
1.6 KiB
C#
Raw Normal View History

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>
/// <param name="bytes">信息字节数组。</param>
/// <returns>信息摘要。</returns>
2022-01-21 16:57:42 +08:00
public static string HashWithSHA256(byte[] secretBytes, byte[] bytes)
{
if (secretBytes == null) throw new ArgumentNullException(nameof(secretBytes));
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
using HMAC hmac = new HMACSHA256(secretBytes);
byte[] hashBytes = hmac.ComputeHash(bytes);
return BitConverter.ToString(hashBytes).Replace("-", "");
}
/// <summary>
2022-01-21 16:57:42 +08:00
/// 获取 HMAC-SHA-256 消息认证码。
/// </summary>
/// <param name="secret">密钥。</param>
/// <param name="message">文本信息。</param>
/// <returns>信息摘要。</returns>
2022-01-21 16:57:42 +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);
byte[] bytes = Encoding.UTF8.GetBytes(message);
2022-01-21 16:57:42 +08:00
return HashWithSHA256(secretBytes, bytes);
}
}
}