直接存儲明文密碼極不安全:數據庫被竊取時,所有用戶密碼立即洩露。最佳實踐是只存儲密碼的哈希值。驗證時,對用戶輸入的密碼進行相同哈希運算,比對哈希值是否一致。
位於 System.Web.Security 命名空間,支持 SHA1 與 MD5 兩種哈希算法。調用極簡單:
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(userInputPwd, "SHA1");
// 或 "MD5"
<%@ Page language="c#" Codebehind="loginform.aspx.cs" AutoEventWireup="false" Inherits="konson.log.loginform" %>
<HTML><body MS_POSITIONING="GridLayout">
<form id="loginform" method="post" runat="server">
<table>
<tr><td>登錄名</td><td><asp:TextBox id="userid" runat="server" Width="101px"></asp:TextBox></td></tr>
<tr><td>密碼</td><td><asp:TextBox id="pwd" runat="server" TextMode="Password" Width="101px"></asp:TextBox></td></tr>
<tr><td><asp:Button id="login" runat="server" Text="登 錄"></asp:Button></td>
<td><asp:Button ID="cancel" Runat="server" Text="取 消"></asp:Button></td></tr>
</table></form></body></HTML>
using System; using System.Web.Security; using System.Web.UI.WebControls;
namespace konson.log
{
public class loginform : System.Web.UI.Page
{
protected TextBox userid, pwd; protected Button login, cancel;
private void Page_Load(object sender, EventArgs e) {}
private void login_Click(object sender, System.EventArgs e)
{
string epwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd.Text, "SHA1");
// epwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd.Text, "MD5");
Response.Write(epwd); // 實際應保存至數據庫並比對
}
}
}
Microsoft.AspNetCore.Cryptography.KeyDerivation 或 BCrypt.Net-Next。