Вот несколько методов C# для генерации хеша MD5 из строки:
-
Использование пространства имен
System.Security.Cryptography
:using System.Security.Cryptography; using System.Text; public string GetMD5Hash(string input) { using (MD5 md5 = MD5.Create()) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { builder.Append(hashBytes[i].ToString("x2")); } return builder.ToString(); } }
-
Использование метода расширения:
using System.Security.Cryptography; using System.Text; public static class StringExtensions { public static string ToMD5(this string input) { using (MD5 md5 = MD5.Create()) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { builder.Append(hashBytes[i].ToString("x2")); } return builder.ToString(); } } }
-
Использование вспомогательного класса:
using System.Security.Cryptography; using System.Text; public static class MD5Helper { public static string GetMD5Hash(string input) { using (MD5 md5 = MD5.Create()) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { builder.Append(hashBytes[i].ToString("x2")); } return builder.ToString(); } } }