在 ASP.NET 中無需引用外部檔案,直接使用內建類別 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile() 即可實作 MD5 加密。
public string md5(string str, int code)
{
if (code == 16) // 16 位 MD5(取 32 位的第 9~25 字元)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
}
if (code == 32) // 32 位完整加密
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
}
return "00000000000000000000000000000000";
}
此方法簡單易用,適合快速實作密碼雜湊儲存等需求。