using System.Security.Cryptography; using System.Text; namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { string username = "boot"; string password = "#Ba~rk4ekf2,UdCW"; string u3 = string.Format("{0}:{1}", username, password); //a8a5159edab2acadd2272b9a08e6d3b0 //a8a5159edab2acadd2272b9a8e6d3b0 //a8a5159edab2acadd2272b9a08e6d3b0 //a8a5159edab2acadd2272b9a08e6d3b0 //0001993c04ee2584d558e5004dd7ff2d //a8a5159edab2acadd2272b9a08e6d3b0 string HHH = GetMD5(u3); string hash = GetMD5Hash1(u3).ToLower(); Console.WriteLine("Hello, World!"); } static string GetMD5Hash(string input) { using (HashAlgorithm algorithm = MD5.Create()) // 更现代的写法,自动处理资源释放 { byte[] inputBytes = Encoding.UTF8.GetBytes(input); // 将字符串转换为字节数组 byte[] hashBytes = algorithm.ComputeHash(inputBytes); // 计算哈希值 return Convert.ToHexString(hashBytes); // 将字节数组转换为十六进制字符串(C# 8及以上版本) } } static string GetMD5Hash1(string input) { StringBuilder sb = new StringBuilder(32); // 预分配32字符空间 using (HashAlgorithm algorithm = MD5.Create()) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); byte[] hashBytes = algorithm.ComputeHash(inputBytes); foreach (byte b in hashBytes) { sb.Append(b.ToString("x2")); // 使用"x2"确保总是两位十六进制 } } return sb.ToString(); } public static string GetMD5(string str) { //创建MD5对象 MD5 mD5 = MD5.Create(); byte[] buffer = Encoding.Default.GetBytes(str); var MD5Buffer = mD5.ComputeHash(buffer); //将字节数组转换为字符串 //法一:将字节数组中每个元素按照指定的编码格式解析成字符串 //return Encoding.Default.GetString(MD5Buffer);(会造成乱码) //法二:直接将数组tostring //法三:直接将数组中的每个元素ToString() string s = ""; for (int i = 0; i < MD5Buffer.Length; i++) { s += MD5Buffer[i].ToString("x");//tostring中的参数x是将10进制转化为16进制 } return s; } } }