C# - MD5验证

前言

本篇主要记录:VS2019 WinFrm桌面应用程序实现字符串和文件的Md5转换功能。后续系统用户登录密码保护,可采用MD5加密保存到后台数据库。

准备工作

搭建WinFrm前台界面

如下图

C# - MD5验证

核心代码构造Md5Helper类

代码如下:

C# - 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 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

效果展示

C# - MD5验证

C# - MD5验证

上一篇:计算一个十进制数字n,它对应的二进制第k位的值


下一篇:WebApi上传文件