×

浅谈C#中Md5和Sha1两种加密方式

独孤求败 独孤求败 发表于2026-03-08 22:27:33 浏览45 评论0

抢沙发发表评论

介绍

在 C# 开发中,MD5 与 SHA1 是两种常见的哈希算法(常被用于数据摘要与校验场景)。二者均可将任意长度的输入数据转换为固定长度的摘要输出,具备不可逆性与理论上的唯一性(即抗碰撞性)。具体而言,MD5 生成 128 位(16 字节)的哈希值,SHA1 则生成 160 位(20 字节)的哈希值。

使用场景

MD5 与 SHA1 常用于数据完整性校验、数字签名生成、文件指纹比对等非高敏场景。需特别注意:MD5 算法已被证实存在严重安全漏洞,可被高效碰撞攻击破解;SHA1 的安全性亦于近年被攻破,国际标准组织(如 NIST)已明确不推荐在新系统中使用。因此,在涉及用户密码存储、金融支付、身份认证等对安全性要求较高的场景中,应避免采用 MD5 或 SHA1,转而选用 SHA-256、SHA-3 或 Argon2 等更安全的现代算法。

示例说明

以下通过 C# 代码示例,分别演示 MD5 与 SHA1 哈希值的计算过程及十六进制字符串输出方式。

MD5 加密示例

以下代码对指定字符串进行 MD5 哈希计算,并将结果转换为小写十六进制字符串:

using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string text = "This is the message to be hashed.";

        MD5 md5 = MD5.Create();
        byte[] inputBytes = Encoding.ASCII.GetBytes(text);
        byte[] hashBytes = md5.ComputeHash(inputBytes);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }

        Console.WriteLine("The input string is: " + text);
        Console.WriteLine("The MD5 hash of the input is: " + sb.ToString());
    }
}

运行结果:

The input string is: This is the message to be hashed.
The MD5 hash of the input is: 3a08a57b25d5d8e938616aab37d904ce

SHA1 加密示例

以下代码对密码字符串进行 SHA1 哈希处理,并输出十六进制格式结果:

using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string password = "myPassword";

        SHA1 sha1 = SHA1.Create();
        byte[] inputBytes = Encoding.ASCII.GetBytes(password);
        byte[] hashBytes = sha1.ComputeHash(inputBytes);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }

        Console.WriteLine("The input password is: " + password);
        Console.WriteLine("The SHA1 hash of the input password is: " + sb.ToString());
    }
}

运行结果:

The input password is: myPassword
The SHA1 hash of the input password is: 6aaf70b7576e6a817d1f154dcaa908adad5df47e

总结

MD5 与 SHA1 作为早期广泛使用的哈希算法,在数据校验与轻量级签名场景中曾发挥重要作用。二者输出长度分别为 128 位与 160 位,但因已被证实存在可被利用的安全缺陷,已不适用于现代高安全需求系统。在实际开发中,应依据应用场景选择符合当前安全标准的算法,并持续关注密码学领域的演进与规范更新。对于密码存储等敏感操作,建议结合加盐(Salt)、密钥派生函数(如 PBKDF2)及更安全的哈希算法综合设计。


群贤毕至

访客