一、生成 string 对应的 MD5 码
/// <summary>/// 生成 string 对应的 MD5 码/// </summary>/// <param name="str">需要转换的字符串 string:用于登录认证时,str = username + 线下传递的key + DateTime.Now.Ticks.ToString() </param>/// <returns>转换后的 MD5 码</returns>public static string GetMD5FromString(string str){byte[] data = System.Security.Cryptography.MD5.HashData(System.Text.Encoding.UTF8.GetBytes(str));System.Text.StringBuilder sBuilder = new();for (int i = 0; i < data.Length; i++){sBuilder.Append(data[i].ToString("x2"));}return sBuilder.ToString().ToUpper();}
二、 生成 string 对应的 Pbkdf2 码
/// <summary>/// derive a 256-bit subkey (use HMACSHA256 with 100 iterations)/// </summary>/// <param name="str">需要转换的字符串 string:用于登录认证时,通常为 username</param>/// <param name="password">线下传递的key</param>/// <param name="Ticks">用于登录认证时,通常为 DateTime.Now.Ticks.ToString(),用于检测登录认证是否超时</param>/// <returns>转换后的 Pbkdf2 码</returns>public static string GetPbkdf2FromString(string str, string password, string Ticks){string hashed = Convert.ToBase64String(Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivation.Pbkdf2(password: password,salt: System.Text.Encoding.UTF8.GetBytes(str + Ticks),prf: Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivationPrf.HMACSHA256,iterationCount: 100,numBytesRequested: 256 / 8));return hashed;}