MD5相当于文件指纹,比较文件是否被修改很有用.常见的文件升级,病毒检测应该就是用这种技术.
现实代码如下:
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; namespace CodeLib.Security { /// <summary> /// MD5 哈希计算工具类,能从字符串和文件中计算哈希值。 /// 支持MD5和SHA1两种算法,可指定大小写。 /// </summary> public sealed class MD5Utils { public string GetMD5FromString(string value) { return GetMD5FromString(value, false); } public string GetMD5FromString(string value, bool returnlowerCase) { MD5 md5 = MD5.Create(); byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(value)); StringBuilder sbResult = new StringBuilder(); for (int i = 0; i < data.Length; i++) { if (returnlowerCase) { sbResult.AppendFormat("{0:x2}", data[i]); } else { sbResult.AppendFormat("{0:X2}", data[i]); } } return sbResult.ToString(); } public string GetMD5FromFile(string fileName) { return GetMD5FromFile(fileName, false); } public string GetMD5FromFile(string fileName, bool returnlowerCase) { using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { MD5 md5 = MD5.Create(); byte[] data = md5.ComputeHash(fileStream); StringBuilder sbResult = new StringBuilder(); for (int i = 0; i < data.Length; i++) { if (returnlowerCase) { sbResult.AppendFormat("{0:x2}", data[i]); } else { sbResult.AppendFormat("{0:X2}", data[i]); } } return sbResult.ToString(); } } public string GetSHA1FromString(string value) { return GetSHA1FromString(value, false); } public string GetSHA1FromString(string value, bool returnlowerCase) { SHA1 md5 = SHA1.Create(); byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(value)); StringBuilder sbResult = new StringBuilder(); for (int i = 0; i < data.Length; i++) { if (returnlowerCase) { sbResult.AppendFormat("{0:x2}", data[i]); } else { sbResult.AppendFormat("{0:X2}", data[i]); } } return sbResult.ToString(); } public string GetSHA1FromFile(string fileName) { return GetSHA1FromFile(fileName, false); } public string GetSHA1FromFile(string fileName, bool returnlowerCase) { using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { SHA1 md5 = SHA1.Create(); byte[] data = md5.ComputeHash(fileStream); StringBuilder sbResult = new StringBuilder(); for (int i = 0; i < data.Length; i++) { if (returnlowerCase) { sbResult.AppendFormat("{0:x2}", data[i]); } else { sbResult.AppendFormat("{0:X2}", data[i]); } } return sbResult.ToString(); } } } }
测试:
/// <summary> ///A test for GetMD5FromFile ///</summary> [TestMethod()] public void GetMD5FromFileTest() { MD5Utils target = new MD5Utils(); string fileName = @"C:\WINDOWS\NOTEPAD.EXE"; string expected = string.Empty; string actual; actual = target.GetMD5FromFile(fileName); Console.WriteLine(actual); }
输出:CA94F7297B444AB655CD4B7793C02FD3
如果你输出的不是这个值,估计是中病毒了:)