登入頁提供「記住我」功能:勾選後將帳號、密碼加密寫入 Cookie,下次造訪自動填入;未勾選則清除 Cookie。
public static class UIHelper
{
// 簡易 AES 加密示範,實務請用 DataProtectionProvider 或 ASP.NET Core Data Protection
private static readonly byte[] Key = Encoding.UTF8.GetBytes("Your32CharLongSecretKey1234567890!!");
private static readonly byte[] IV = Encoding.UTF8.GetBytes("16CharInitVector");
public static string Encrypt(string plain)
{
using (Aes aes = Aes.Create())
{
aes.Key = Key; aes.IV = IV;
var encryptor = aes.CreateEncryptor();
byte[] plainBytes = Encoding.UTF8.GetBytes(plain);
byte[] cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
return Convert.ToBase64String(cipher);
}
}
public static string Decrypt(string cipher)
{
using (Aes aes = Aes.Create())
{
aes.Key = Key; aes.IV = IV;
var decryptor = aes.CreateDecryptor();
byte[] cipherBytes = Convert.FromBase64String(cipher);
byte[] plain = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return Encoding.UTF8.GetString(plain);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var cookie = Request.Cookies["loginInfo"];
if (cookie != null)
{
cbRemember.Checked = true;
txtUser.Text = UIHelper.Decrypt(cookie["loginName"]);
txtPwd.Attributes["value"] = UIHelper.Decrypt(cookie["pwd"]); // 顯示在 value 中
}
else
{
txtPwd.Attributes["value"] = "******";
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
// 驗證碼、帳號狀態檢查略...
if (UserService.Login(txtUser.Text.Trim(), SecurityHelper.HashPwd(txtPwd.Text.Trim())))
{
var cookie = Request.Cookies["loginInfo"];
if (cbRemember.Checked)
{
if (cookie == null) cookie = new HttpCookie("loginInfo");
SetCookie(cookie, 7); // 7 天有效
}
else
{
ExpireCookie(cookie); // 立即過期
}
Response.Redirect("/");
}
else
{
ShowAlert("帳號或密碼錯誤");
}
}
private void SetCookie(HttpCookie cookie, int days)
{
cookie.Values["loginName"] = UIHelper.Encrypt(txtUser.Text.Trim());
cookie.Values["pwd"] = UIHelper.Encrypt(txtPwd.Text.Trim());
cookie.Expires = DateTime.Now.AddDays(days);
Response.AppendCookie(cookie);
}
private void ExpireCookie(HttpCookie cookie)
{
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
Response.AppendCookie(cookie);
}
}