1 //计算字符串MD5
2 public static string GetStringMd5(string txt)
3 {
4 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
5 string result = "";
6 byte[] bytes = Encoding.ASCII.GetBytes(txt);
7 byte[] cryptBytes = md5.ComputeHash(bytes);
8 foreach (byte item in cryptBytes)
9 {
10 result += item.ToString("X2");
11 }
12 return result;
13 }
14
15 //计算文件MD5
16 public static string GetFileMd5(string path)
17 {
18 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
19 string result = "";
20 using (FileStream fs = new FileStream(path, FileMode.Open))
21 {
22 byte[] cryptBytes = md5.ComputeHash(fs);
23 foreach (byte item in cryptBytes)
24 {
25 result += item.ToString("X2");
26 }
27 return result;
28 }
29 }
C#代码依旧简单易懂,不过是调用了一个类库而已,记录在这里留着日后用的时候Copy。其实可以利用这段代码写一个小工具计算MD5。