前言
本篇主要记录: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/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。