c#

C#如何将字符串转为md5

小樊
134
2024-07-13 22:04:23
栏目: 编程语言

在C#中,可以使用System.Security.Cryptography命名空间中的MD5类来将字符串转换为MD5哈希值。下面是一个简单的示例代码:

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

class Program
{
    static void Main()
    {
        string input = "Hello, World!";
        
        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"));
            }
            
            string md5Hash = sb.ToString();
            Console.WriteLine("MD5 Hash of '{0}': {1}", input, md5Hash);
        }
    }
}

在上面的示例中,我们首先创建一个MD5对象,然后将字符串转换为字节数组,再使用ComputeHash方法计算MD5哈希值。最后,我们将哈希值转换为十六进制字符串并输出结果。

0
看了该问题的人还看了