在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。