c#

如何在C#中使用md5加密

小樊
84
2024-07-13 21:58:25
栏目: 编程语言

在C#中使用MD5加密需要使用System.Security.Cryptography命名空间下的MD5类。以下是一个简单的示例代码:

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

class Program
{
    static void Main()
    {
        string input = "Hello World";
        string encrypted = GetMD5Hash(input);

        Console.WriteLine($"Input: {input}");
        Console.WriteLine($"MD5 Encrypted: {encrypted}");
    }

    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();
        }
    }
}

在上面的代码中,我们首先定义了一个GetMD5Hash方法,该方法接收一个字符串作为输入,然后使用MD5算法来对输入进行加密,最后返回加密后的结果。在Main方法中,我们调用GetMD5Hash方法并输出加密结果。

0
看了该问题的人还看了