c# 使用Md5加密字符串

在 C# 中使用 MD5 加密字符串,可以通过 System.Security.Cryptography 命名空间下的 MD5 类实现。以下是完整代码示例及详细说明:

MD5类的实例在使用后需要正确释放资源,因为实现了IDisposable接口。所以应该使用using语句来确保资源被释放,避免内存泄漏。

现在,编写代码的大致步骤是:

1. 创建MD5实例。

2. 将输入字符串转换为字节数组(使用UTF8编码)。

3. 计算哈希值。

4. 将哈希字节数组转换为十六进制字符串。

5. 处理资源释放。


1. 基础代码实现

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

public class Md5Helper
{
    /// 
    /// 计算字符串的 MD5 哈希值(32位小写)
    /// 
    public static string MD5Encrypt(string input)
    {
        if (input == null)
        {
            throw new ArgumentNullException(nameof(input));
        }

        // 创建 MD5 实例
        using (MD5 md5 = MD5.Create())
        {
            // 将输入字符串转为字节数组(UTF-8编码)
            byte[] inputBytes = Encoding.UTF8.GetBytes(input)

你可能感兴趣的:(c#,哈希算法,MD5加密)