溫馨提示×

如何在C#中使用md5加密

c#
小樊
111
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女