public static string SHA256Encrypt(string strIN)
{
//string strIN = getstrIN(strIN);
byte[] tmpByte;
SHA256 sha256 = new SHA256Managed();
tmpByte = sha256.ComputeHash(GetKeyByteArray(strIN));
StringBuilder rst = new StringBuilder();
for(int i = 0; i<tmpByte.Length; i++)
{
rst.Append(tmpByte[i].ToString("x2"));
}
sha256.Clear();
return rst.ToString();
//return GetStringValue(tmpByte);
}
private static string GetStringValue(byte[] Byte)
{
string tmpString = "";
UTF8Encoding Asc = new UTF8Encoding();
tmpString = Asc.GetString(Byte);
return tmpString;
}
private static byte[] GetKeyByteArray(string strKey)
{
UTF8Encoding Asc = new UTF8Encoding();
int tmpStrLen = strKey.Length;
byte[] tmpByte = new byte[tmpStrLen - 1];
tmpByte = Asc.GetBytes(strKey);
return tmpByte;
}
private 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);
return Convert.ToBase64String(hashmessage);
}
}
private static string Base64(string message)
{
System.Text.Encoding encode = System.Text.Encoding.UTF8;
byte[] bytedata = encode.GetBytes(message);
string strPath = Convert.ToBase64String(bytedata, 0, bytedata.Length);
return strPath;
}
C#加密算法HmacSHA256,SHA256
最新推荐文章于 2025-11-12 23:40:20 发布
本文介绍了一种使用SHA256算法进行字符串加密的方法,包括SHA256的直接应用、HMAC-SHA256签名算法及Base64编码的实现。通过具体的代码示例展示了如何将原始字符串转换为安全的密文形式。
927

被折叠的 条评论
为什么被折叠?



