1.简介
1.什么是cookie:cookie是一种能够让网站服务器把少量数据(4kb左右)存储到客户端的硬盘或内存。并且读可以取出来的一种技术。
2.当你浏览某网站时,由web服务器放置于你硬盘上的一个非常小的文本文件,它可以记录你的用户id、浏览过的网页或者停留的时间等网站想要你保存的信息。当你再次通过浏览器访问该网站时,浏览器会自动将属于该网站的cookie发送到服务器去,服务器通过读取cookie,得知你的相关信息,就可以做出相应的动作。比如,显示欢迎你的小标题,不用填写帐号密码直接登录等。。
3.不同的浏览器存储的cookie位置是也不一样的。cookie文件的信息是不安全的,所以cookie里面的数据最好加密。
4.浏览器保存cookie数据有2中形式:浏览器的内存中,浏览器所在的电脑硬盘中。
class="p0">从本质上讲,它可以看作是你的身份证。但Cookies不能作为代码执行,也不会传送病毒,且为你所专有,并只能由提供它的服务器来读取。保存的信息片断以“名/值”对(name-value pairs)的形式储存,一个“名/值”对仅仅是一条命名的数据。一个网站只能取得它放在你的电脑中的信息,它无法从其它的Cookies文件中取得信息,也无法得到你的电脑上的其它任何东西。(摘自网络)
并非所有浏览器都支持。数据信息是以文本的形式保存在客户端计算机。
2.Cookie的基本用法
(1) 将Cookie写入浏览器:
1 HttpCookie makeCookie = new HttpCookie("myCookie");//括号里面写的是Cookie的名称 2 3 makeCookie.Value = this.TextBox1.Text;//这个是Cookie的值 4 5 Response.Cookies.Add(makeCookie);//添加cookie变量
(2)读取Cookie的值
1 HttpCookie readCookie = Request.Cookies["myCookie"];//读取的是使用Request返回的值 2 TextBox2.Text = readCookie.Value;
(3)设置cookie的有效期
1 HttpCookie cookie = new HttpCookie("name","Elaine"); //创建cookie的实例。 2 cookie.Expires = DateTime.Now.AddDays(5);//设置cookie的过期时间,5天后过期,自动清除文件 3 Response.Cookies.Add(cookie);//将创建的cookie文件输入到浏览器端 4 Response.Write(Request.Cookies["name"].Value); //读取cookie文件中存储的值
(4)删除Cookie,没有特定的方法,只需要让它的有效期失效就行了
1 cookie.Expires = DateTime.Now.AddMonths(-1); //cookie的销毁
(5)Cookie的其他属性
HttpCookie makecookie = new HttpCookie("myCookie"); 指定Cookie的名称:makecookie.Name; 指定Cookie的值: makecookie.Value; 指定Cookie的路径:makecookie.Path;
(6)Cookie加密
Response.Cookies["strPWD"].Value = FormsAuthentication.HashPasswordForStoringInConfigFile(加密字符串, "md5");
3.cookie读写原理
Cookies集合是附属于Response对象及Request对象的数据集合,使用时需要在前面加上Response或Request。
用于给客户机发送Cookies的语法通常为:
当给不存在的Cookies集合设置时,就会在客户机创建,如果该Cookies己存在,则会被代替。由于Cookies是作为HTTP传输的头信息的一部分发给客户机的,所以向客户机发送Cookies的代码一般放在发送给浏览器的HTML文件的标记之前。
如果用户要读取Cookies,则必须使用Request对象的Cookies集合,其使用方法是:
需要注意的是,只有在服务器未被下载任何数据给浏览器前,浏览器才能与Server进行Cookies集合的数据交换,一旦浏览器开始接收Server所下载的数据,Cookies的数据交换则停止,为了避免错误,要在程序和前面加上response.Buffer=True。
4.怎么查看Cookie的位置
打开IE》Internet选项》常规》
5.代码示例
案例一:
下面来完成一个登陆实例:
总共有两个页面,一个登陆页面,一个主页;
页面效果:
提示:
首先在登陆页前台的HTML代码里面的head标记里面的Title添加ID=”pageTitle
还有需要在web.config中把<appSettings/>改为以下结果:
<appSettings> <!-- 新添加的内容! --> <add key="WebTitle" value="Elaine00登陆实例"/> <add key="MsgTitle" value="Elaine00登陆测试"/> </appSettings>
具体代码:
登陆页:
前台:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookieLogin.aspx.cs" Inherits="Cookie" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml" > 6 <head runat="server"> 7 <title id="PageTitle">登陆页</title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div> 12 <table style="width: 367px"> 13 <tr> 14 <td colspan="3" style="height: 17px"> 15 用户登录</td> 16 </tr> 17 <tr> 18 <td colspan="2" style="width: 116px; height: 18px"> 19 登录名称:</td> 20 <td style="height: 18px"> 21 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> 22 </tr> 23 <tr> 24 <td colspan="2" style="width: 116px"> 25 密码:</td> 26 <td> 27 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td> 28 </tr> 29 <tr> 30 <td colspan="2" style="width: 116px"> 31 </td> 32 <td> 33 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="登录" /> 34 <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="重置" /></td> 35 </tr> 36 </table> 37 38 </div> 39 </form> 40 </body> 41 </html>
后台:
1 using System; 2 using System.Web; 3 4 public partial class Cookie : System.Web.UI.Page 5 { 6 protected void Page_Load(object sender, EventArgs e) 7 { 8 PageTitle.Text = System.Configuration.ConfigurationSettings.AppSettings["WebTitle"]; 9 } 10 protected void Button1_Click(object sender, EventArgs e) 11 { 12 if (TextBox1.Text.Trim() != "" && TextBox2.Text.Trim() != "") 13 { 14 HttpCookie cookieAdminCode = new HttpCookie("CookAdminCode"); 15 cookieAdminCode["AdminCode"] = TextBox1.Text; 16 cookieAdminCode["PWD"] = TextBox2.Text; 17 cookieAdminCode.Expires.AddDays(1); 18 19 Response.Cookies.Add(cookieAdminCode); 20 Response.Redirect("Main.aspx"); 21 } 22 else 23 { 24 MessageBox("对不起,请输入用户名或者密码!"); 25 } 26 } 27 #region MessageBox(string Message) 28 private void MessageBox(string Message) 29 { 30 string msgTitle = System.Configuration.ConfigurationSettings.AppSettings["MsgTitle"].Trim(); 31 Response.Write("<script language=javascript>alert('" + msgTitle + "\\n\\n" + Message + "')</script>");//"\\n"一个斜线表示转义字符,一个表示于n在一起表示换行符号 32 } 33 #endregion 34 protected void Button2_Click(object sender, EventArgs e) 35 { 36 TextBox1.Text = TextBox2.Text = ""; 37 } 38 }
主页:
前台:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Main" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml" > 6 <head runat="server"> 7 <title>主页</title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div> 12 13 </div> 14 </form> 15 </body> 16 </html>
后台:
1 using System; 2 using System.Web; 3 4 public partial class Main : System.Web.UI.Page 5 { 6 protected void Page_Load(object sender, EventArgs e) 7 { 8 HttpCookie cookieAdminCode = Request.Cookies["CookAdminCode"]; 9 string Adminname = cookieAdminCode.Values["AdminCode"].Trim(); 10 string pwd = cookieAdminCode.Values["PWD"].Trim(); 11 if (Adminname== "Elaine00" && pwd== "1") 12 { 13 MessageBox("登录成功!"); 14 Response.Write("欢迎" + Adminname + "登录本系统!您的密码是:" + pwd); 15 } 16 else 17 { 18 MessageBox("对不起!身份验证失败请重试!"); 19 Response.Write("<script language=javascript>window.location.href='CookieLogin.aspx'</script>"); 20 } 21 } 22 private void MessageBox(string Message) 23 { 24 // string msgTitle = System.Configuration.ConfigurationSettings.AppSettings["MsgTitle"].ToString().Trim(); 25 string msgTitle = System.Configuration.ConfigurationManager.AppSettings["MsgTitle"].Trim(); 26 Response.Write("<script language=javascript>alert('"+msgTitle+"\\n\\n"+Message+"')</script>"); 27 } 28 }
案例二:
图示:
下面实现的是使用两个加密类来加密Cookie
首先定义一个EncryptString类;代码如下:
1 using System; 2 using System.IO; 3 using System.Security.Cryptography; 4 5 namespace Test 6 { 7 public class EncryptString 8 { 9 private static byte[] Key64 = { 42, 16, 93, 156, 78, 4, 218, 32 }; 10 private static byte[] IV64 = { 55, 103, 246, 79, 36, 99, 167, 3 }; 11 private static byte[] Key192 = {42, 16, 93, 156, 78, 4, 218, 32,15, 167, 12 44,80, 26, 250, 155, 112,2, 94, 11, 204, 119, 35, 184, 197}; 13 private static byte[] IV192 = {55, 103, 246, 79, 36, 99, 167, 3,42, 14 5, 62,83, 184, 7, 209, 13,145, 23, 200, 58, 173, 10, 121, 222}; 15 public static String Encrypt(String valueString) 16 { 17 if (valueString != "") 18 { //定义DES的Provider 19 DESCryptoServiceProvider desprovider = 20 new DESCryptoServiceProvider(); 21 //定义内存流 22 MemoryStream memoryStream = new MemoryStream(); 23 //定义加密流 24 CryptoStream cryptoStream = new CryptoStream(memoryStream, 25 desprovider.CreateEncryptor(Key64, IV64), 26 CryptoStreamMode.Write); 27 //定义写IO流 28 StreamWriter writerStream = new StreamWriter(cryptoStream); 29 //写入加密后的字符流 30 writerStream.Write(valueString); 31 writerStream.Flush(); 32 cryptoStream.FlushFinalBlock(); 33 memoryStream.Flush(); 34 //返回加密后的字符串 35 return (Convert.ToBase64String(memoryStream.GetBuffer(), 0, 36 (int)memoryStream.Length)); 37 } 38 return (null); 39 } 40 public static String Decrypt(String valueString) 41 { 42 if (valueString != "") 43 { //定义DES的Provider 44 DESCryptoServiceProvider desprovider = 45 new DESCryptoServiceProvider(); 46 //转换解密的字符串为二进制 47 byte[] buffer = Convert.FromBase64String(valueString); 48 //定义内存流 49 MemoryStream memoryStream = new MemoryStream(); 50 //定义加密流 51 CryptoStream cryptoStream = new CryptoStream(memoryStream, 52 desprovider.CreateEncryptor(Key64, IV64), 53 CryptoStreamMode.Read); 54 //定义读IO流 55 StreamReader readerStream = new StreamReader(cryptoStream); 56 //返回解密后的字符串 57 return (readerStream.ReadToEnd()); 58 } 59 return (null); 60 } 61 public static String EncryptTripleDES(String valueString) 62 { 63 if (valueString != "") 64 { //定义TripleDES的Provider 65 TripleDESCryptoServiceProvider triprovider = 66 new TripleDESCryptoServiceProvider(); 67 //定义内存流 68 MemoryStream memoryStream = new MemoryStream(); 69 //定义加密流 70 CryptoStream cryptoStream = new CryptoStream(memoryStream, 71 triprovider.CreateEncryptor(Key192, IV192), 72 CryptoStreamMode.Write); 73 //定义写IO流 74 StreamWriter writerStream = new StreamWriter(cryptoStream); 75 //写入加密后的字符流 76 writerStream.Write(valueString); 77 writerStream.Flush(); 78 cryptoStream.FlushFinalBlock(); 79 memoryStream.Flush(); 80 //返回加密后的字符串 81 return (Convert.ToBase64String(memoryStream.GetBuffer(), 0, 82 (int)memoryStream.Length)); 83 } 84 return (null); 85 } 86 public static String DecryptTripleDES(String valueString) 87 { 88 if (valueString != "") 89 { //定义TripleDES的Provider 90 TripleDESCryptoServiceProvider triprovider = 91 new TripleDESCryptoServiceProvider(); 92 //转换解密的字符串为二进制 93 byte[] buffer = Convert.FromBase64String(valueString); 94 //定义内存流 95 MemoryStream memoryStream = new MemoryStream(); 96 //定义加密流 97 98 CryptoStream cryptoStream = new CryptoStream(memoryStream, 99 triprovider.CreateEncryptor(Key64, IV64), 100 CryptoStreamMode.Read); 101 //定义读IO流 102 StreamReader readerStream = new StreamReader(cryptoStream); 103 //返回解密后的字符串 104 return (readerStream.ReadToEnd()); 105 } 106 return (null); 107 } 108 } 109 }
再定义一个CookieEncrypt的加密类;代码如下:
1 using System; 2 using System.Web; 3 4 namespace Test 5 { 6 public class CookieEncrypt 7 { 8 public static void SetCookie(HttpCookie cookie) 9 { //设置Cookie 10 HttpContext.Current.Response.Cookies.Set(cookie); 11 } 12 public static void SetCookie(String key, String valueString) 13 { //设置加密后的Cookie 14 key = HttpContext.Current.Server.UrlEncode(key); 15 valueString = HttpContext.Current.Server.UrlEncode(valueString); 16 HttpCookie cookie = new HttpCookie(key, valueString); 17 SetCookie(cookie); 18 } 19 public static void SetCookie(String key, String valueString, 20 DateTime expires) 21 { //设置加密后的Cookie,并设置Cookie的有效时间 22 key = HttpContext.Current.Server.UrlEncode(key); 23 valueString = HttpContext.Current.Server.UrlEncode(valueString); 24 HttpCookie cookie = new HttpCookie(key, valueString); 25 cookie.Expires = expires; 26 SetCookie(cookie); 27 } 28 public static void SetTripleDESEncryptedCookie(String key, 29 String valueString) 30 { //设置使用TripleDES加密后的Cookie 31 key = EncryptString.EncryptTripleDES(key); 32 valueString = EncryptString.EncryptTripleDES(valueString); 33 SetCookie(key, valueString); 34 } 35 public static void SetTripleDESEncryptedCookie(String key, 36 String valueString, DateTime expires) 37 { //设置使用TripleDES加密后的Cookie,并设置Cookie的有效时间 38 key = EncryptString.EncryptTripleDES(key); 39 valueString = EncryptString.EncryptTripleDES(valueString); 40 SetCookie(key, valueString, expires); 41 } 42 43 public static void SetEncryptedCookie(String key, String valueString) 44 { //设置使用DES加密后的Cookie 45 key = EncryptString.Encrypt(key); 46 valueString = EncryptString.Encrypt(valueString); 47 SetCookie(key, valueString); 48 } 49 public static void SetEncryptedCookie(String key, 50 String valueString, DateTime expires) 51 { //设置使用DES加密后的Cookie,并设置Cookie的有效时间 52 key = EncryptString.Encrypt(key); 53 valueString = EncryptString.Encrypt(valueString); 54 SetCookie(key, valueString, expires); 55 } 56 public static String GetTripleDESEncryptedCookieValue(String key) 57 { //获取使用TripleDES解密后的Cookie 58 key = EncryptString.EncryptTripleDES(key); 59 String valueString = GetCookieValue(key); 60 valueString = EncryptString.DecryptTripleDES(valueString); 61 return (valueString); 62 } 63 public static String GetEncryptedCookieValue(String key) 64 { //获取使用DES解密后的Cookie 65 key = EncryptString.Encrypt(key); 66 String valueString = GetCookieValue(key); 67 valueString = EncryptString.Decrypt(valueString); 68 return (valueString); 69 } 70 public static HttpCookie GetCookie(String key) 71 { //通过关键字获取Cookie 72 key = HttpContext.Current.Server.UrlEncode(key); 73 return (HttpContext.Current.Request.Cookies.Get(key)); 74 } 75 public static String GetCookieValue(String key) 76 { //通过关键字获取Cookie的value 77 String valueString = GetCookie(key).Value; 78 valueString = HttpContext.Current.Server.UrlDecode(valueString); 79 return (valueString); 80 } 81 } 82 83 }
接着定义Test.aspx页面;代码如下:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test.Test" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <title></title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div> 12 加密前的Cookie值:<asp:Label ID="myCookie" Runat="server"></asp:Label> 13 <br /> 14 使用DES加密后的Cookie值:<asp:Label ID="EncryptCookie" Runat="server"></asp:Label> 15 <br /> 16 使用TripleDES加密后的Cookie值:<asp:Label ID="TripleDESCookie" Runat="server"></asp:Label> 17 </div> 18 </form> 19 </body> 20 </html>
接着定义Test.aspx.cs代码:
1 using System; 2 using System.Web; 3 4 namespace Test 5 { 6 public partial class Test : System.Web.UI.Page 7 { 8 protected void Page_Load(object sender, EventArgs e) 9 { 10 //调用函数EncryptMyCookies()获取Cookie的原始值和加密后的值 11 if (!Page.IsPostBack) { EncryptMyCookies(); } 12 } 13 //获取cookie的值加密前和加密后的值,并获取 14 private void EncryptMyCookies() 15 { 16 var myNameCookie = new HttpCookie("myName", "Elaine"); 17 Response.Cookies.Add(myNameCookie); 18 //获取Cookie的原始值 19 var httpCookie = HttpContext.Current.Response.Cookies["myName"]; 20 if (httpCookie != null) 21 myCookie.Text = httpCookie.Value; //获取使用DES加密后Cookie的值 22 EncryptCookie.Text = EncryptString.Encrypt(myCookie.Text); //获取使用TripleDES加密后Cookie的值 23 TripleDESCookie.Text = EncryptString.EncryptTripleDES(myCookie.Text); 24 } 25 } 26 }
小结:使用Cookie很方便,但是记得加密是重点~~