asp.net利用加密的cookie实现记住用户名和密码

本文转载:http://blog.sina.com.cn/s/blog_67aaf4440100qju5.html

 我们知道,在登录的时候,有一个记住密码,那么它的原理就是利用cookies来记录登录信息。

 

    那么在我们的电脑上哪里可以看到cookies?

 

    以xp系统为例,C:\Documents and Settings\Administrator\Cookies可以看到很多cookies,这些文件就记录这我们登录的信息。那么这就带来一个问题:如果我们cookie不加密的话,可以被轻易看到很多信息,包括密码。

 

    下面这个完整的例子就是对cookie进行操作的:

 

Login.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class Admin_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Title = ConfigurationManager.AppSettings["WebName"].ToString() + " - 管理登陆";

        if (!IsPostBack)
        {
            Cookie = Request.Cookies["UserInfo"];
            if (Cookie != null)
            {
                Name.Text = Cookie.Values["userName"];
                //asp.net中的TextBox如果TextMode为Password的时候不支持直接赋值,
              //在此处以添加属性的方式把读取的密码赋值给密码框
                Pwd.Attributes.Add("value", BLL.CookieHelper.DecryptQueryString

              (Cookie.Values["Pwd"].ToString()));
            }
        }

    }

    protected void Sub_Click(object sender, EventArgs e)
    {
        Model.Admin User = new Model.Admin();
        User.AdminName = Name.Text;
        User.AdminPwd = BLL.Message.ToSHA512(Pwd.Text.ToString());
        BLL.Business Pn163 = new BLL.Business();
        DataTable Dt = Pn163.DtRead(User);
        if (!String.IsNullOrEmpty(User.AdminName) && !String.IsNullOrEmpty(User.AdminPwd))
        {
            if (Session["Code"].ToString() == ChkCode.Text)
            {
                if (Dt.Rows.Count > 0)
                {
                    Session["Admin"] = User.AdminName;
                    Session["Pwd"] = User.AdminPwd;
                    Session["Comp"] = Dt.Rows[0]["Comp"].ToString();

                    // 如果选择"下次记住我"
                    if (this.chboxRemeber.Checked)
                    {
                        this.SaveCookie(Name.Text, BLL.CookieHelper.EncryptQueryString

                     (Server.UrlEncode(Pwd.Text)));
                    }
                    Response.Redirect("./Admin.aspx");
                }
                else BLL.Message.Show("用户名或密码错误!");
            }
            else BLL.Message.Show("验证码错误!");
        }
        else BLL.Message.Show("请输入用户名和密码!");
    }

   

    private HttpCookie Cookie = null;
   
    /// <summary>
    /// 记住用户名和密码
    /// </summary>
    private void SaveCookie(string userName, string Pwd)
    {
        Cookie = Request.Cookies["UserInfo"];

        if (Cookie == null || !Cookie.Values["userName"].Equals(userName))
        {
            Cookie = new HttpCookie("UserInfo");
            Cookie.Values.Add("userName", userName);
            Cookie.Values.Add("Pwd", Pwd);
            Cookie.Expires = DateTime.Now.AddDays(365);
            Response.Cookies.Add(Cookie);
        }
    }
}

 

 

CookieHelper.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace BLL
{

    // 这个类是实现了DES的加密和解密
    public class CookieHelper
    {
        //URL传输参数加密Key这个key可以自己设置支持8位这个东西很重要的,密钥
        static string _QueryStringKey = "e2345678";

        /// <summary>
        /// 加密算法
        /// </summary>
        public static string EncryptQueryString(string QueryString)
        {
            return Encrypt(QueryString, _QueryStringKey);
        }


        /// <summary>
        /// 解密算法
        /// </summary>
        public static string DecryptQueryString(string QueryString)
        {
            return Decrypt(QueryString, _QueryStringKey);
        }


        public static string Encrypt(string originalString, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            // 把字符串放到byte数组中
            byte[] inputByteArray = Encoding.Default.GetBytes(originalString);

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);  //原文使用ASCIIEncoding.ASCII方法的

                                                            GetBytes方法
            MemoryStream ms = new MemoryStream();         //使得输入密码必须输入英文文本
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();

            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        public static string Decrypt(string originalString, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[originalString.Length / 2];
            for (int x = 0; x < originalString.Length / 2; x++)
            {
                int i = (Convert.ToInt32(originalString.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            //建立加密对象的密钥和偏移量,此值重要,不能修改

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);           

            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }

    }
}

asp.net利用加密的cookie实现记住用户名和密码,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。