c#加密
转自:https://blog.csdn.net/u011127019/article/details/51384246
一、SHA加密
/// <summary> /// SHA1 加密,返回大写字符串 /// </summary> /// <param name="content">需要加密字符串</param> /// <returns>返回40位UTF8 大写</returns> public static string SHA1(string content) { return SHA1(content, Encoding.UTF8); } /// <summary> /// SHA1 加密,返回大写字符串 /// </summary> /// <param name="content">需要加密字符串</param> /// <param name="encode">指定加密编码</param> /// <returns>返回40位大写字符串</returns> public static string SHA1(string content, Encoding encode) { try { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_in = encode.GetBytes(content); byte[] bytes_out = sha1.ComputeHash(bytes_in); sha1.Dispose(); string result = BitConverter.ToString(bytes_out); result = result.Replace("-", ""); return result; } catch (Exception ex) { throw new Exception("SHA1加密出错:" + ex.Message); } }
二、md5加密
2.使用标准MD5CryptoServiceProvider 方法1
//方法1 //默认小写 32位加密 public static string GetMd532(string str) { MD5CryptoServiceProvider crypto = new MD5CryptoServiceProvider(); byte[] bytes = Encoding.UTF8.GetBytes(str); bytes = crypto.ComputeHash(bytes); StringBuilder builder = new StringBuilder(); foreach (var item in bytes) { builder.AppendFormat("{0:x2}", item); } return builder.ToString(); } //默认小写 16位加密 public static string GetMd516(string str) { return GetMd532(str).Substring(8, 16); }
3.使用标准MD5CryptoServiceProvider 方法2(推荐)
//方法2 //默认大写 32位加密 public static string GetMd5_32(string str) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] bytes = Encoding.UTF8.GetBytes(str); string result = BitConverter.ToString(md5.ComputeHash(bytes)); return result.Replace("-", ""); } //默认大写 16位加密 public static string GetMd5_16(string str) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] bytes = Encoding.UTF8.GetBytes(str); string result = BitConverter.ToString(md5.ComputeHash(bytes),4,8); return result.Replace("-", ""); }
4.测试
string str = "张三"; Console.WriteLine("FormsAuthentication:" + Md5Operate.HashMD5_String(str)); Console.WriteLine(); Console.WriteLine("md532:" + Md5Operate.GetMd532(str)); Console.WriteLine(); Console.WriteLine("md516:" + Md5Operate.GetMd516(str)); Console.WriteLine(); Console.WriteLine("md5_32:" + Md5Operate.GetMd5_32(str)); Console.WriteLine(); Console.WriteLine("md5_16:" + Md5Operate.GetMd5_16(str));