温馨提示×

C#实现MD5加密

c#
小亿
87
2024-01-05 19:35:33
栏目: 编程语言

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

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

class Program
{
    static void Main()
    {
        string originalText = "Hello, World!";

        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(originalText);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2")); // x2表示以16进制形式输出
            }

            string encryptedText = sb.ToString();
            Console.WriteLine("Original Text: {0}", originalText);
            Console.WriteLine("Encrypted Text: {0}", encryptedText);
        }
    }
}

输出结果:

Original Text: Hello, World!
Encrypted Text: ed076287532e86365e841e92bfc50d8c

在上述代码中,首先创建一个MD5实例,然后将要加密的原始文本转换为字节数组,并使用ComputeHash方法计算MD5哈希值。最后,将哈希值转换为十六进制字符串并输出。

0