MD5加密
使用MD5CryptoServiceProvider类
1 public static string Md5(string str) 2 { 3 var buffer = Encoding.UTF8.GetBytes(str); 4 5 MD5 md5 = new MD5CryptoServiceProvider(); 6 byte[] bytes = md5.ComputeHash(buffer); 7 8 var sb = new StringBuilder(); 9 foreach (var t in bytes) 10 { 11 sb.Append(t.ToString("X2")); 12 } 13 return sb.ToString().ToLower(); 14 }
Sha1加密
SHA1,也是在System.Security.Cryptography程序集下提供的算法
1 /// <summary> 2 /// Sha1加密 3 /// </summary> 4 /// <param name="str">要加密的字符串</param> 5 /// <returns>加密后的十六进制的哈希散列(40个字符)</returns> 6 public static string Sha1(string str) 7 { 8 var buffer = Encoding.UTF8.GetBytes(str); 9 10 var sha1 = SHA1.Create(); 11 var bytes = sha1.ComputeHash(buffer); 12 13 var stringBuilder = new StringBuilder(); 14 foreach (var byt in bytes) 15 { 16 stringBuilder.Append(byt.ToString("X2")); 17 } 18 19 return stringBuilder.ToString().ToLower(); 20 }
案例
以上,bytes转string,也可以使用 BitConverter.ToString(bytes)
但是需要额外替换其中的特殊字符“-”,
var encryptionStr = BitConverter.ToString(bytes).Replace("-", "").ToLower();