前言
本篇主要記錄:VS2019 WinFrm桌面應用程式實作字元串和檔案的Md5轉換功能。後續系統使用者登入密碼保護,可采用MD5加密儲存到背景資料庫。
準備工作
搭建WinFrm前台界面
如下圖
核心代碼構造Md5Helper類
代碼如下:

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 MD5Demo
10 {
11 class Md5Helper
12 {
13 /// <summary>
14 /// 擷取Md5碼
15 /// </summary>
16 /// <param name="value">需要轉換成Md5碼的原碼</param>
17 /// <returns></returns>
18 public static string Md5(string value)
19 {
20 var result = string.Empty;
21 if (string.IsNullOrEmpty(value)) return result;
22 using (var md5 = MD5.Create())
23 {
24 result = GetMd5Hash(md5, value);
25 }
26 return result;
27 }
28 static string GetMd5Hash(MD5 md5Hash, string input)
29 {
30
31 byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
32 var sBuilder = new StringBuilder();
33 foreach (byte t in data)
34 {
35 sBuilder.Append(t.ToString("x2"));
36 }
37 return sBuilder.ToString();
38 }
39 static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
40 {
41 var hashOfInput = GetMd5Hash(md5Hash, input);
42 var comparer = StringComparer.OrdinalIgnoreCase;
43 return 0 == comparer.Compare(hashOfInput, hash);
44 }
45
46 /// <summary>
47 /// 擷取檔案的Md5碼
48 /// </summary>
49 /// <param name="fileName">檔案所在的路徑</param>
50 /// <returns></returns>
51 public static string GetMD5HashFromFile(string fileName)
52 {
53 try
54 {
55 FileStream file = new FileStream(fileName, FileMode.Open);
56 System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
57 byte[] retVal = md5.ComputeHash(file);
58 file.Close();
59
60 StringBuilder sb = new StringBuilder();
61 for (int i = 0; i < retVal.Length; i++)
62 {
63 sb.Append(retVal[i].ToString("x2"));
64 }
65 return sb.ToString();
66 }
67 catch (Exception ex)
68 {
69 throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
70 }
71 }
72
73 }
74 }
View Code
效果展示
作者:Jeremy.Wu
出處:https://www.cnblogs.com/jeremywucnblog/
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。