导航

MD5

Posted on 2017-08-21 22:32  清浅ヾ  阅读(145)  评论(0编辑  收藏  举报
 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Security.Cryptography;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace MyEncrypt
10 {
11     /// <summary>
12     /// 不可逆加密
13     /// 1 防止被篡改
14     /// 2 防止明文存储
15     /// 3 防止抵赖,数字签名
16     /// </summary>
17     public class MD5Encrypt
18     {
19         #region MD5
20         /// <summary>
21         /// MD5加密,和动网上的16/32位MD5加密结果相同,
22         /// 使用的UTF8编码
23         /// </summary>
24         /// <param name="source">待加密字串</param>
25         /// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
26         /// <returns>加密后的字串</returns>
27         public static string Encrypt(string source, int length = 32)//默认参数
28         {
29             if (string.IsNullOrEmpty(source)) return string.Empty;
30             HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
31             byte[] bytes = Encoding.UTF8.GetBytes(source);//这里需要区别编码的
32             byte[] hashValue = provider.ComputeHash(bytes);
33             StringBuilder sb = new StringBuilder();
34             switch (length)
35             {
36                 case 16://16位密文是32位密文的9到24位字符
37                     for (int i = 4; i < 12; i++)
38                     {
39                         sb.Append(hashValue[i].ToString("x2"));
40                     }
41                     break;
42                 case 32:
43                     for (int i = 0; i < 16; i++)
44                     {
45                         sb.Append(hashValue[i].ToString("x2"));
46                     }
47                     break;
48                 default:
49                     for (int i = 0; i < hashValue.Length; i++)
50                     {
51                         sb.Append(hashValue[i].ToString("x2"));
52                     }
53                     break;
54             }
55             return sb.ToString();
56         }
57         #endregion MD5
58 
59         #region MD5摘要
60         /// <summary>
61         /// 获取文件的MD5摘要
62         /// </summary>
63         /// <param name="fileName"></param>
64         /// <returns></returns>
65         public static string AbstractFile(string fileName)
66         {
67             FileStream file = new FileStream(fileName, FileMode.Open);
68             MD5 md5 = new MD5CryptoServiceProvider();
69             byte[] retVal = md5.ComputeHash(file);
70             file.Close();
71 
72             StringBuilder sb = new StringBuilder();
73             for (int i = 0; i < retVal.Length; i++)
74             {
75                 sb.Append(retVal[i].ToString("x2"));
76             }
77             return sb.ToString();
78         }
79         #endregion
80     }
81 }