在做一個前台的登陸和背景資訊審核管理功能時,需要用到記住密碼的模組:
雖然.net內建了登陸控制項,有記住密碼的功能,但還是想自己實踐一下,以下代碼主要應用了COOKIE,包括安全加密的過程等。
複製代碼 代碼如下://設定,刪除Cookie
//provider jb51.net
protected void set_cookie()
{
HttpCookie UserNameCookie = Request.Cookies["UserNameCookie"];
HttpCookie UserPasswordCookie = Request.Cookies["UserPasswordCookie"];
if (this.CheSave.Checked)
{
lblcookie.Text = "1";
//儲存使用者名稱和密碼到cookie
if (UserNameCookie == null)
{
UserNameCookie = new HttpCookie("UserNameCookie");
UserNameCookie.Values.Add("UserName", TxtUserName.Text);
UserNameCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(UserNameCookie);
}
//修改COOKIE
else if (UserNameCookie.Values["UserName"] != TxtUserName.Text)
{
SetToCookie(UserNameCookie, "UserName", TxtUserName.Text);
}
if (UserPasswordCookie == null)
{
UserPasswordCookie = new HttpCookie("UserPasswordCookie");
string password1 = FormsAuthentication.HashPasswordForStoringInConfigFile(TxtUserPassword.Text, "MD5"); //如果重新指定使用者密碼,則重新加密密碼
UserPasswordCookie.Values.Add("UserPassword", password1);
UserPasswordCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(UserPasswordCookie);
}
else if (UserPasswordCookie.Values["UserPassword"] != FormsAuthentication.HashPasswordForStoringInConfigFile(TxtUserPassword.Text, "MD5") && TxtUserPassword.Text != "1234567890")
//“1234567890”是程現在密碼框中的十個字元。
{
SetToCookie(UserPasswordCookie, "UserPassword", FormsAuthentication.HashPasswordForStoringInConfigFile(TxtUserPassword.Text, "MD5"));
}
}
else
{
lblcookie.Text = "0";
//從cookie刪除使用者名稱和密碼
if (Response.Cookies["UserNameCookie"] != null)
{
HttpCookie myCookie = new HttpCookie("UserNameCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
if (Response.Cookies["UserPasswordCookie"] != null)
{
HttpCookie myCookie = new HttpCookie("UserPasswordCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
}
}
//檢查是否存在COOKie情況
public void check_cookie()
{
HttpCookie UserNameCookie = Request.Cookies["UserNameCookie"];
HttpCookie UserPasswordCookie = Request.Cookies["UserPasswordCookie"];
if (UserNameCookie != null)
{
this.CheSave.Checked = true;
TxtUserName.Text = UserNameCookie.Values["UserName"];
}
if (UserPasswordCookie != null)
{
TxtUserPassword.Attributes.Add("value", "1234567890");//設定密碼框初始值
}
}
public string getpassword()
{
HttpCookie UserPasswordCookie = Request.Cookies["UserPasswordCookie"];
string strpwd = ""; //擷取此密碼字串與資料庫存中的密布相比。
if (lblcookie.Text == "1")
{
strpwd = UserPasswordCookie.Values["UserPassWord"];//直接擷取COOKIE中的密碼值
}
else
{
strpwd= FormsAuthentication.HashPasswordForStoringInConfigFile(TxtUserPassword.Text, "MD5"); //對密碼進行加密
}
return strpwd; //返回密碼欄位
}
//修改COOKIE這段的方法
public void SetToCookie(HttpCookie httpcookie, string cookiename, string cookievalue)
{
httpcookie.Values[cookiename] = cookievalue;
httpcookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(httpcookie);
}
}