MD5 文件加密(用于文件唯一性识别)

 1 /// <summary>
 2     /// 客户端MD5码的工具类
 3     /// </summary>
 4     public class MD5Util
 5     {
 6 
 7         /// <summary>  
 8         /// 通过MD5CryptoServiceProvider类中的ComputeHash方法直接传入一个FileStream类实现计算MD5  
 9         /// 操作简单,代码少,调用即可  
10         /// </summary>  
11         /// <param name="path">文件地址</param>  
12         /// <returns>MD5Hash</returns>  
13         public static string GetMD5ByMD5CryptoService(string path)
14         {
15             if (!File.Exists(path))
16                 throw new ArgumentException(string.Format("<{0}>, 不存在", path));
17             FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
18             MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
19             byte[] buffer = md5Provider.ComputeHash(fs);
20             string resule = BitConverter.ToString(buffer);
21             resule = resule.Replace("-", "");
22             md5Provider.Clear();
23             fs.Close();
24             return resule;
25         } 
26     
27         /// <summary>
28         /// 通过HashAlgorithm的TransformBlock方法对流进行叠加运算获得MD5  
29         /// 实现稍微复杂,但可使用与传输文件或接收文件时同步计算MD5值  
30         /// 可自定义缓冲区大小,计算速度较快  
31         /// </summary>
32         /// <param name="file">文件地址</param>
33         /// <param name="bufferSize">自定义缓冲区大小,默认1024 * 16 = 16K</param>
34         /// <returns>MD5Hash</returns>
35         public static string GetMD5ByHashAlgorithm(string path, int bufferSize = 16384)
36         {
37             if (File.Exists(path))
38             {
39                 byte[] buffer = new byte[bufferSize];
40                 Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
41                 HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
42                 int readLength = 0;//每次读取长度  
43                 var output = new byte[bufferSize];
44                 while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)
45                 {
46                     //计算MD5  
47                     hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);
48                 }
49                 //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)  
50                 hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
51                 string md5 = BitConverter.ToString(hashAlgorithm.Hash);
52                 hashAlgorithm.Clear();
53                 inputStream.Close();
54                 md5 = md5.Replace("-", "");
55                 return md5; 
56             }
57             else 
58             {
59                 throw new ClientException(ClientExceptionStatus.FILE_NOT_FOUND, "MD5码生成时找不到文件[" + path + "]");
60             }
61         }
62     }

 

参考地址 : http://blog.csdn.net/qiujuer/article/details/19344527

posted on 2018-01-22 16:43  hi-gdl  阅读(609)  评论(0)    收藏  举报

导航