学海无涯

导航

统计

.Net Core Md5 加密整理

一、.Net Core中Md5使用说明

.Net Core中自带Md5加密处理,使用方法和 .Net Framework中相同

所在命名空间:

1
using System.Security.Cryptography;

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
namespace Stock.Infrastructure;
/// <summary>
/// MD5 加密
/// </summary>
public class MD5Helper
{
  /// <summary>
  /// 16位 MD5 加密
  /// </summary>
  /// <param name="password"></param>
  /// <returns></returns>
  public static string MD5Encrypt16(string password)
  {
    var md5 =  MD5.Create();
    string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
    t2 = t2.Replace("-", string.Empty);
    return t2;
  }
  /// <summary>
  /// 32位 MD5 加密
  /// </summary>
  /// <param name="password"></param>
  /// <returns></returns>
  public static string MD5Encrypt32(string password = "")
  {
    string pwd = string.Empty;
    try
    {
      if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
      {
        MD5 md5 = MD5.Create();//实例化一个 md5 对象
        //加密后是一个字节类型的数组,这里要注意编码 UTF8/Unicode 的选择
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
        //通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化后所得
        foreach (var item in s)
        {
          //将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X),则格式后的字符是大写字符
          pwd = string.Concat(pwd, item.ToString("X2"));
        }
      }
    }
    catch
    {
      throw new Exception($"错误的 password 字符串:{password}");
    }
    return pwd;
  }
  /// <summary>
  /// 64位 MD5 加密
  /// </summary>
  /// <param name="password"></param>
  /// <returns></returns>
  public static string MD5Encrypt64(string password)
  {
    var md5 = MD5.Create();
    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
    return Convert.ToBase64String(s);
  }
}

  

posted on   宁静致远.  阅读(1495)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
点击右上角即可分享
微信分享提示