譯:在ASP.NET中如何對cookies進行加密和解密

譯文地址:http://www.codeproject.com/Tips/872826/Encrypt-Decrypt-Cookies-in-ASP-NETweb

源代碼:http://files.cnblogs.com/files/yplong/ShanuBasicCSharpOOPConceptV1.4.zip瀏覽器

簡介:安全

在這個話題中,我將說明如何加密和解密cookies的值。cookies是一個在瀏覽器端存儲值的text文件。做爲cookies存儲在一個簡單的text文件中,很容易被讀取和修改cookies內容。cookie

然而你能夠對cookies進行加密和解密來達到必定的安全性。本文中咱們將使用"MachineKey.Protect」 和 「MachineKey.Unprotect」兩個方法來加密和解密。加密

MachineKey.Protect() MachineKey.Unprotect() 是應用在ASP.NET4.5中。這兩個方法須要2個參數,第一個參數就是要進行加密和解密的內容文件的字節形式,第二個參數就是目的。目的就像一個鍵(key),能夠是字符串類型的值。咱們須要經過相同的目的值來對值進行加保護和解保護。spa

源碼設計:設計

 

 1 <div>
 2     <asp:TextBox ID="txtvalue" runat="server" 
 3     placeholder="Enter Some Text" Width="250">
 4     </asp:TextBox><br />
 5     <asp:Label runat="server" ID="lblmsg" ForeColor="Green" 
 6     Font-Bold="true"></asp:Label><br />
 7     <asp:Button ID="btnEncrypt"
 8                 runat="server" Text="Encrypt" 
 9                 OnClick="btnEncrypt_Click" />  
10     <asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" 
11     OnClick="btnDecrypt_Click" Style="height: 26px" />
12 </div>

 

代碼的實際操做:
使用命名空間:code

 

 1 //using System.Text;
 2 //using System.Web.Security;
 3 
 4 protected void btnEncrypt_Click(object sender, EventArgs e)
 5     {
 6         var cookieText = Encoding.UTF8.GetBytes(txtvalue.Text);
 7         var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "ProtectCookie"));
 8 
 9         //--- Create cookie object and pass name of the cookie and value to be stored.
10         HttpCookie cookieObject = new HttpCookie("NameOfCookie", encryptedValue);
11 
12         //---- Set expiry time of cookie.
13         cookieObject.Expires.AddDays(5);
14 
15         //---- Add cookie to cookie collection.
16         Response.Cookies.Add(cookieObject);
17         lblmsg.Text = encryptedValue;
18     }
19     protected void btnDecrypt_Click(object sender, EventArgs e)
20     {
21         var bytes = Convert.FromBase64String(Request.Cookies["NameOfCookie"].Value);
22         var output = MachineKey.Unprotect(bytes, "ProtectCookie");
23         string result = Encoding.UTF8.GetString(output);
24         lblmsg.Text = result;
25     }

 ASP.NET 4.0中:

加密:orm

1 var plaintextBytes = Encoding.UTF8.GetBytes("Jitendra Gangwar");
2 var encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
3 Response.Write(encryptedValue.ToString());

解密:server

1 var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All);
2 var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
3 Response.Write(decryptedValue);

輸出:

相關文章
相關標籤/搜索