MD5对文件进行加密,可以支持大文件
生活随笔
收集整理的這篇文章主要介紹了
MD5对文件进行加密,可以支持大文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/// <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();
}/// <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; // 緩沖區大小,1MBbyte[] 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();
}
轉載于?https://www.cnblogs.com/ahui/archive/2010/12/23/1914586.html
總結
以上是生活随笔為你收集整理的MD5对文件进行加密,可以支持大文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P68是什么意思 IP67和IP68等级
- 下一篇: [框架]高并发中的惊群效应