在 C# 中实现 MD5 加密(严格来说是 MD5 哈希)可以使用 System.Security.Cryptography 命名空间下的 MD5 类。

下面给你一个完整示例:


1. 生成 32 位 MD5 哈希(常用)

using System;using System.Security.Cryptography;using System.Text;class Program{    static void Main()    {        string input = "HelloWorld";        string md5Hash = GetMD5(input);        Console.WriteLine("原文: " + input);        Console.WriteLine("MD5哈希: " + md5Hash);    }    public static string GetMD5(string input)    {        using (MD5 md5 = MD5.Create())        {            // 将字符串转换为字节数组            byte[] inputBytes = Encoding.UTF8.GetBytes(input);            // 计算哈希            byte[] hashBytes = md5.ComputeHash(inputBytes);            // 转换为十六进制字符串(32位)            StringBuilder sb = new StringBuilder();            foreach (byte b in hashBytes)            {                sb.Append(b.ToString("x2")); // 小写,X2 为大写            }            return sb.ToString();        }    }}php824 Bytes© 菜鸟-创作你的创作

2. 输出效果示例

输入 "HelloWorld"可能输出:

原文: HelloWorldMD5哈希: fc5e038d38a57032085441e7fe7010b0php54 Bytes© 菜鸟-创作你的创作

3. 小贴士

  • MD5 不可逆,只能用于校验或签名,不适合存储密码(建议用 SHA256 + 盐)
  • 如果要得到 16 位 MD5,可以取 32 位结果的中间 16 个字符: string md5_16 = md5Hash.Substring(8, 16);

如果你需要,我可以帮你做一个 C# MD5 加密 + SHA256 加密对比 的速查代码,这样你能直接比较两者的安全性和用法。
你要我直接帮你加上这个对比吗?

https://www.52runoob.com/archives/5679