Csharp 中MD5加密
时间: 2023-09-18 12:14:33 浏览: 36
在 C# 中使用 MD5 进行加密可以通过以下代码实现:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string input = "Hello World";
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
using (MD5 md5 = MD5.Create())
{
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
string hash = sb.ToString();
Console.WriteLine("Input: " + input);
Console.WriteLine("Hash: " + hash);
}
}
}
```
在上面的示例中,我们首先将要加密的字符串转换为字节数组,然后使用 `MD5.Create()` 创建一个 MD5 实例。接下来,我们调用 `ComputeHash()` 方法计算输入字节数组的哈希值。最后,我们将哈希值转换为十六进制字符串并输出。