1 #region MD5 2 /// <summary> 3 /// 16位MD5加密 4 /// </summary> 5 /// <param name="password"></param> 6 /// <returns></returns> 7 public static string MD5Encrypt16(string strByMd5) 8 { 9 var md5 = new MD5CryptoServiceProvider(); 10 string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(strByMd5)), 4, 8); 11 t2 = t2.Replace("-", ""); 12 return t2; 13 } 14 15 /// <summary> 16 /// 32位MD5加密 17 /// </summary> 18 /// <param name="password"></param> 19 /// <returns></returns> 20 public static string MD5Encrypt32(string strByMd5) 21 { 22 string cl = strByMd5; 23 string pwd = ""; 24 MD5 md5 = MD5.Create(); //实例化一个md5对像 25 // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 26 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); 27 // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得 28 for (int i = 0; i < s.Length; i++) 29 { 30 // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 31 pwd = pwd + s[i].ToString("X"); 32 } 33 return pwd; 34 } 35 36 public static string MD5Encrypt64(string strByMd5) 37 { 38 string cl = strByMd5; 39 //string pwd = ""; 40 MD5 md5 = MD5.Create(); //实例化一个md5对像 41 // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 42 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); 43 return Convert.ToBase64String(s); 44 } 45 #endregion 46 47 #region 对文件进行MD5处理 48 /// <summary> 49 /// 对文件流进行MD5加密 50 /// </summary> 51 public static string MD5Stream(Stream stream) 52 { 53 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 54 md5.ComputeHash(stream); 55 byte[] b = md5.Hash; 56 md5.Clear(); 57 StringBuilder sb = new StringBuilder(32); 58 for (int i = 0; i < b.Length; i++) 59 { 60 sb.Append(b[i].ToString("X2")); 61 } 62 return sb.ToString(); 63 } 64 65 /// <summary> 66 /// 对文件进行MD5加密 67 /// </summary> 68 public static string MD5Stream(string filePath) 69 { 70 using (FileStream stream = File.Open(filePath, FileMode.Open)) 71 { 72 return MD5Stream(stream); 73 } 74 } 75 76 #endregion 77 78 /// <summary> 79 /// 获取MD5值(对字节数组进行MD5) 80 /// </summary> 81 /// <param name="fileBytes"></param> 82 /// <returns></returns> 83 public static string GetMd5(byte[] fileBytes) 84 { 85 var MD5 = System.Security.Cryptography.MD5.Create().ComputeHash(fileBytes); 86 //将md5byte[]数组转换为字符串 87 var str_md5 = Convert.ToBase64String(MD5); 88 return str_md5; 89 }