溫馨提示×

C#中怎么使用MD5加密數據

c#
小億
158
2023-08-03 11:32:30
欄目: 編程語言

在C#中使用MD5加密數據,可以使用System.Security.Cryptography命名空間中的MD5類。以下是一個示例代碼:

using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
string input = "Hello World";
string encryptedData = ComputeMD5Hash(input);
Console.WriteLine($"Input: {input}");
Console.WriteLine($"MD5 Hash: {encryptedData}");
}
public static string ComputeMD5Hash(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();
}
}
}

輸出:

Input: Hello World
MD5 Hash: b10a8db164e0754105b7a99be72e3fe5

在上面的示例中,ComputeMD5Hash方法接收一個字符串輸入,并返回其MD5哈希值的字符串表示形式。該方法使用MD5.Create()創建一個MD5實例,然后使用Encoding.UTF8.GetBytes()將輸入轉換為字節數組。接下來,使用md5.ComputeHash()計算輸入的MD5哈希值,并將結果存儲在hashBytes中。最后,通過使用StringBuilder將每個字節轉換為兩位的十六進制字符串,得到最終的MD5哈希值的字符串表示形式。

請注意,MD5算法已經被認為是不安全的,并且不推薦用于加密敏感信息。更安全的替代算法是SHA-256或SHA-512。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女