c#

C#怎么实现MD5加密功能

小亿
109
2023-07-27 19:39:48
栏目: 编程语言

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

using System;
using System.Security.Cryptography;
using System.Text;
public class MD5Example
{
public static string CalculateMD5Hash(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();
}
}
public static void Main(string[] args)
{
string input = "Hello World";
string hashedInput = CalculateMD5Hash(input);
Console.WriteLine("Input: " + input);
Console.WriteLine("MD5 Hash: " + hashedInput);
}
}

运行代码后,将输出以下结果:

Input: Hello World
MD5 Hash: ed076287532e86365e841e92bfc50d8c

这里的CalculateMD5Hash方法接受一个字符串参数input,并返回其MD5哈希值。在方法内部,首先创建一个MD5实例,然后使用ComputeHash方法计算输入字符串的MD5哈希值。最后,通过将每个字节转换为两位的十六进制字符串,并连接起来,得到最终的哈希值。

0
看了该问题的人还看了