C#實現MD5


什么是MD5?

  MD5即Message-Digest Algorithm 5(信息-摘要算法5),用於確保信息傳輸完整一致。是計算機廣泛使用的雜湊算法之一,主流編程語言普遍已有MD5實現。

MD5的特點:

  • 壓縮性:任意長度的數據,算出的MD5值長度都是固定的。
  • 容易計算:從原數據計算出MD5值很容易。
  • 抗修改性:對原數據進行任何改動,哪怕只修改1個字節,所得到的MD5值都有很大區別。
  • 強抗碰撞:已知原數據和其MD5值,想找到一個具有相同MD5值的數據(即偽造數據)是非常困難的。
 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 ConsoleApplication1
10 {
11     public class MD5Helper
12     {
13         /// <summary>
14         /// 計算字節數組的 MD5 值
15         /// </summary>
16         /// <param name="buffer"></param>
17         /// <returns></returns>
18         public static string CalcMD5(byte[] buffer)
19         {
20             using (MD5 md5 = MD5.Create())
21             {
22                 byte[] md5Bytes = md5.ComputeHash(buffer);
23                 return BytesToString(md5Bytes);
24             }
25         }
26 
27         /// <summary>
28         /// 將得到的 MD5 字節數組轉成 字符串
29         /// </summary>
30         /// <param name="md5Bytes"></param>
31         /// <returns></returns>
32         private static string BytesToString(byte[] md5Bytes)
33         {
34             StringBuilder sb = new StringBuilder();
35             for (int i = 0; i < md5Bytes.Length; i++)
36             {
37                 sb.Append(md5Bytes[i].ToString("X2"));
38             }
39             return sb.ToString();
40         }
41 
42         /// <summary>
43         /// 計算字符串的 MD5 值
44         /// </summary>
45         /// <param name="str"></param>
46         /// <returns></returns>
47         public static string CalcMD5(string str)
48         {
49             byte[] buffer = Encoding.UTF8.GetBytes(str);
50             return CalcMD5(buffer);
51         }
52 
53         /// <summary>
54         /// 計算流的 MD5 值
55         /// </summary>
56         /// <param name="stream"></param>
57         /// <returns></returns>
58         public static string CalcMD5(Stream stream)
59         {
60             using (MD5 md5 = MD5.Create())
61             {
62                 byte[] buffer = md5.ComputeHash(stream);
63                 return BytesToString(buffer);
64             }
65         }
66     }
67 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM