译文地址:http://www.codeproject.com/Tips/872826/Encrypt-Decrypt-Cookies-in-ASP-NET
源代码:http://files.cnblogs.com/files/yplong/ShanuBasicCSharpOOPConceptV1.4.zip
简介:
在这个话题中,我将说明如何加密和解密cookies的值。cookies是一个在浏览器端存储值的text文件。作为cookies存储在一个简单的text文件中,很容易被读取和修改cookies内容。
然而你可以对cookies进行加密和解密来达到一定的安全性。本文中我们将使用"MachineKey.Protect
” 和 “MachineKey.Unprotect
”两个方法来加密和解密。
MachineKey.Protect()
和 MachineKey.Unprotect()
是应用在ASP.NET4.5中。这两个方法需要2个参数,第一个参数就是要进行加密和解密的内容文件的字节形式,第二个参数就是目的。目的就像一个键(key),可以是字符串类型的值。我们需要通过相同的目的值来对值进行加保护和解保护。
源码设计:
<div>
<asp:TextBox ID="txtvalue" runat="server"
placeholder="Enter Some Text" Width="">
</asp:TextBox><br />
<asp:Label runat="server" ID="lblmsg" ForeColor="Green"
Font-Bold="true"></asp:Label><br />
<asp:Button ID="btnEncrypt"
runat="server" Text="Encrypt"
OnClick="btnEncrypt_Click" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt"
OnClick="btnDecrypt_Click" Style="height: 26px" />
</div>
代码的实际操作:
使用命名空间:
//using System.Text;
//using System.Web.Security; protected void btnEncrypt_Click(object sender, EventArgs e)
{
var cookieText = Encoding.UTF8.GetBytes(txtvalue.Text);
var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "ProtectCookie")); //--- Create cookie object and pass name of the cookie and value to be stored.
HttpCookie cookieObject = new HttpCookie("NameOfCookie", encryptedValue); //---- Set expiry time of cookie.
cookieObject.Expires.AddDays(); //---- Add cookie to cookie collection.
Response.Cookies.Add(cookieObject);
lblmsg.Text = encryptedValue;
}
protected void btnDecrypt_Click(object sender, EventArgs e)
{
var bytes = Convert.FromBase64String(Request.Cookies["NameOfCookie"].Value);
var output = MachineKey.Unprotect(bytes, "ProtectCookie");
string result = Encoding.UTF8.GetString(output);
lblmsg.Text = result;
}
ASP.NET 4.0中:
加密:
var plaintextBytes = Encoding.UTF8.GetBytes("Jitendra Gangwar");
var encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
Response.Write(encryptedValue.ToString());
解密:
var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All);
var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
Response.Write(decryptedValue);
输出: