Message Digest Algorithm MD5为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。该算法的文件号为RFC 1321(R.Rivest,MIT Laboratory for Computer Science and RSA Data Security Inc. April 1992)。
MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一,主流编程语言普遍已有MD5实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理。
public static string getMD5ByHashAlgorithm(string path)
{if (!File.Exists(path))
throw new ArgumentException(string.Format("<{0}>, 不存在", path));
var bufferSize = 1024 * 16;//自定义缓冲区大小16K
byte[] buffer = new byte[bufferSize];
Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
var readLength = 0;//每次读取长度
var output = new byte[bufferSize];
while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
//计算MD5
hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);
}
//完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)
hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
var md5 = BitConverter.ToString(hashAlgorithm.Hash);
hashAlgorithm.Clear();
inputStream.Close();
md5 = md5.Replace("-", "");
return md5;
}
转自http://www.cnblogs.com/anjou/archive/2008/08/05/1261290.html