| 演算法 | 核心類別 |
|---|---|
| MD5 | System.Security.Cryptography.MD5System.Security.Cryptography.MD5CryptoServiceProviderSystem.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5") |
| SHA1 | System.Security.Cryptography.SHA1System.Security.Cryptography.SHA1CryptoServiceProviderSystem.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1") |
public string GetMd5Method1(string source)
{
// 建立 CSP 實例
using (var md5 = new MD5CryptoServiceProvider())
{
// 計算雜湊位元組陣列
byte[] hashBytes = md5.ComputeHash(Encoding.Default.GetBytes(source));
// 取第 9-25 位 (索引 4 起長度 8),轉 16 進位字串
string result = BitConverter.ToString(hashBytes, 4, 8).Replace("-", "");
return result;
}
}
public string GetMd5Method2(string source)
{
using (var md5 = MD5.Create())
{
byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(source));
// 手動轉 16 進位 (大寫)
var sb = new StringBuilder();
foreach (byte b in hashBytes)
sb.Append(b.ToString("X2"));
return sb.ToString();
}
}
public string GetMd5Method3(string source)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");
}
將上述類別替換為 SHA1/SHA1CryptoServiceProvider,或 FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1") 即可。
上述方法皆在伺服端執行,意謂著:
企業級解決方案: