一种计算MD5的实现方法

1、在需要用到加密的地方可以使用.net中的md5相关的类生成md5给文件加密。

2、基本思路:

将文件也好,字符串也好,转成字节数组,再利用.net的md5相关类生成md5相关字符串,再将字符串转成16进制。

3、具体的例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Runtime.InteropServices;
 6 using System.Security.Cryptography;
 7 using System.IO;
 8 using System.Diagnostics;
 9 
10 namespace MD5
11 {
12     public class MD5Hash 
13     {
14         public MD5Hash()
15         {
16             this.md5 = MD5.Create();
17         }
18 
19         public string CalculateFile(string filePath)
20         {
21             string reuslt = string.Empty;
22 
23             try
24             {
25              reuslt = Calculate(System.IO.File.ReadAllBytes(filePath));
26             }
27             catch (Exception e)
28             {
29                 reuslt = string.Empty;
30             }
31 
32             return reuslt;
33         }
34         
35         public string Calculate(byte[] buffer)
36         {
37             return Format(md5.ComputeHash(buffer));
38         }
39                 
40         private string Format(byte[] source)
41         {
42             StringBuilder result = new StringBuilder(string.Empty);
43 
44             Array.ForEach(source, (value) => result.Append(value.ToString("X2")));
45 
46             return result.ToString();
47         }
48                 
49         public string Calculate(string message)
50         {
51             return Calculate(message, Encoding.UTF8);
52         }
53 
54         public string Calculate(string message, Encoding encoder)
55         {
56             return Calculate(encoder.GetBytes(message));
57         }
58 
59         private MD5 md5;
60     }
61 }

 

posted on 2014-12-25 19:39  siszqsqx  阅读(403)  评论(0编辑  收藏  举报

导航