MD5编码
1 x2方式和x 方式的区别是 比如 比特为 0 x2显示的是 07 x显示的是 7 我们如果是要固定位32位MD5编码的话就使用x2方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static string GetMD5(string str) { StringBuilder sb = new StringBuilder(); foreach (byte b in System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(str))) { sb.Append(b.ToString("x2")); } return sb.ToString(); }
2 对文件流进行MD5加密
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 对文件流进行MD5加密 /// </summary> /// <param name="filePath"></param> /// <returns></returns> /// <example></example> public static string MD5Stream(string filePath) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.ComputeHash(fs); fs.Close(); byte[] b = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < b.Length; i++) { sb.Append(b[i].ToString("X2")); } Console.WriteLine(sb.ToString()); Console.ReadLine(); return sb.ToString(); }
3 对文件进行MD5加密
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 对文件进行MD5加密 /// </summary> /// <param name="filePath"></param> public static void MD5File(string filePath) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // 缓冲区大小,1MB byte[] buff = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区 if (offset + readSize < fs.Length) // 不是最后一块 { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // 最后一块 { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } Console.WriteLine(sb.ToString()); Console.ReadLine(); }
4 返回指定文件的MD5值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 返回指定文件的MD5值 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string Check(string path) { if (!File.Exists(path)) throw new ArgumentException(string.Format("<{0}>, 不存在", path)); using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider(); byte[] buffer = md5Provider.ComputeHash(fs); string resule = BitConverter.ToString(buffer); resule = resule.Replace("-", ""); return resule; } }