How to use the MD5 encryption method in C#?
In C#, you can use the MD5 encryption method by implementing the MD5 class in the System.Security.Cryptography namespace. Here is a simple example code:
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main(string[] args)
{
string input = "Hello World";
string encrypted = GetMd5Hash(input);
Console.WriteLine("MD5加密前的字符串: " + input);
Console.WriteLine("MD5加密后的字符串: " + encrypted);
}
public static string GetMd5Hash(string input)
{
using (MD5 md5Hash = MD5.Create())
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
builder.Append(data[i].ToString("x2"));
}
return builder.ToString();
}
}
}
The GetMd5Hash method in the above code takes a string as input, creates an MD5 instance using MD5.Create(), calculates the MD5 hash value of the input string using the ComputeHash method, and then converts the result to a hexadecimal string. Finally, it returns the string representation of the MD5 hash value. Running the above code will output the MD5 encryption results of the input string before and after hashing.