UsersBLL bll = new UsersBLL(); private void AutoLogin() { if (Request.Cookies["loginId"] != null && Request.Cookies["pwd"] != null && Request.Cookies["id"] != null) { int cookId = Convert.ToInt32(Request.Cookies["id"].Value); string cookLoginId = Request.Cookies["loginId"].Value; string cookPwd = Request.Cookies["pwd"].Value; UserInfo model = bll.GetUserById(cookId); if (model != null) { string sysPwd = WebComm.MD5Str(model.LoginPwd, cookPwd.Substring(0, 2)); if (model.LoginId == cookLoginId && sysPwd == cookPwd) { GoPage(model); } } } } protected void btLogin_Click(object sender, EventArgs e) { UserInfo model = bll.GetUser(txtUserLogin.Text.Trim(), WebComm.MD5Str(txtPwd.Text.Trim())); if (model == null) { JScript.Alert(this, "用户名或者密码错误!"); return; } //用户勾选记住密码后执行 if (checkPwd.Checked) { string dbcookPwd = WebComm.MD5Str(model.LoginPwd, null); HttpCookie cookId = new HttpCookie("id", model.Id.ToString()); HttpCookie cookLoginId = new HttpCookie("loginId", model.LoginId); HttpCookie cookPwd = new HttpCookie("pwd", dbcookPwd); cookId.Expires = DateTime.Now.AddMonths(1); cookLoginId.Expires = DateTime.Now.AddMonths(1); cookPwd.Expires = DateTime.Now.AddMonths(1); Response.Cookies.Add(cookLoginId); Response.Cookies.Add(cookPwd); Response.Cookies.Add(cookId); } GoPage(model); } private void GoPage(UserInfo model) { Session["id"] = model.Id; Session["loginId"] = model.LoginId; Session["name"] = model.Name; string url = "~/Default.aspx"; if (Request.QueryString["return"] != null) { url = Request.QueryString["return"]; } Response.Redirect(url); }
应用到的方法
#region MD5 加密字符串 +string MD5Str(string str) /// <summary> /// MD5 加密字符串 /// </summary> /// <param name="rawPass">源字符串</param> /// <returns>加密后字符串</returns> public static string MD5Str(string str) { // 创建MD5类的默认实例:MD5CryptoServiceProvider MD5 md5 = MD5.Create(); byte[] bs = Encoding.UTF8.GetBytes(str); byte[] hs = md5.ComputeHash(bs); StringBuilder sb = new StringBuilder(); foreach (byte b in hs) { // 以十六进制格式格式化 sb.Append(b.ToString("x2")); } return sb.ToString(); } #endregion #region 返回 对字符串MD5之后 加上随机生成的盐值之后 再MD5 的字符串 +string MD5Str(string str, string salt) /// <summary> /// 返回 对字符串MD5之后 加上随机生成的盐值之后 再MD5 的字符串 /// </summary> /// <param name="str"></param> /// <param name="salt">如果为null,则为字符串进行两次MD5加密算法</param> /// <returns></returns> public static string MD5Str(string str, string salt) { if (salt == null) { Random r = new Random(); salt = ((char)r.Next(65, 91)).ToString() + ((char)r.Next(65, 91)).ToString(); } return salt + MD5Str(salt + MD5Str(str)); } #endregion
版权声明:本文为博主原创文章,未经博主允许不得转载。