温馨提示×

c#中md5加密实现的方法是什么

c#
小亿
87
2024-01-25 17:31:34
栏目: 编程语言

在C#中,可以使用System.Security.Cryptography.MD5类来实现MD5加密。以下是一个示例代码:

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

public class Program
{
    public static void Main(string[] args)
    {
        string input = "Hello World!";
        string encrypted = GetMd5Hash(input);
        
        Console.WriteLine("MD5 Encrypted: " + encrypted);
    }
    
    public static string GetMd5Hash(string input)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
            }
            
            return sb.ToString();
        }
    }
}

此示例将字符串"Hello World!"使用MD5加密,并输出MD5加密结果。在GetMd5Hash方法中,首先创建一个MD5实例,然后将输入字符串转换为字节数组。使用md5.ComputeHash方法计算哈希值,并使用StringBuilder将哈希值转换为十六进制字符串。最后返回加密后的字符串。

0