.Net Core 常用加密方式收集
在我们对接外部接口时常常为了一个接口对接加密方式查半天文档,现收集我工作中用到的加密方式
Md5 加密
/// <summary>
/// 转换为MD5加密后的字符串(默认加密为32位)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToMD5String(this string str)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.UTF8.GetBytes(str);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
md5.Dispose();
return sb.ToString();
}
HMACSHA1加密
public static string HMACSHA1Text(this string text, string key)
{
//HMACSHA1加密
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(key);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(text);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
var enText = new StringBuilder();
foreach (byte iByte in hashBytes)
{
enText.AppendFormat("{0:x2}", iByte);
}
return enText.ToString();
}