public static class SHA256EncryptUtil
{
/// SHA256加密,并十六进制编码
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string SHA256EncryptString(string data)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
byte[] hash = SHA256Managed.Create().ComputeHash(bytes);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
builder.Append(hash[i].ToString("x2"));
}
return builder.ToString();
}
/// <summary>
/// HMACSHA256加密
/// </summary>
/// <param name="message"></param>
/// <param name="secret"></param>
/// <returns></returns>
public static string HmacSHA256(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashmessage.Length; i++)
{
builder.Append(hashmessage[i].ToString("x2"));
}
return builder.ToString();
}
}
}
C# sha256和HMAC-sha256加密
最新推荐文章于 2024-09-25 11:27:31 发布