C#でMD5暗号化を実現する方法は何ですか?
C#でMD5暗号化を実装するためにSystem.Security.Cryptography.MD5クラスを使用できます。以下はサンプルコードです:
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 Encrypted: " + encrypted);
}
public static string GetMd5Hash(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();
}
}
}
この例では、「Hello World!」という文字列をMD5で暗号化し、その結果を出力します。GetMd5Hashメソッドでは、まずMD5のインスタンスを作成し、入力文字列をバイト配列に変換します。md5.ComputeHashメソッドを使用してハッシュ値を計算し、StringBuilderを使用してハッシュ値を16進数の文字列に変換します。最後に、暗号化された文字列を返します。