0

我尝试使用以下代码加密和解密 cookie。我能够加密但解密功能接受字节输入。如何将 cookie 转换为字节以进行解密?错误是

无法将类型“System.Web.HttpCookie”隐式转换为“byte[]

错误行是“byte[] encrypted = myCookie;” 如何在解密之前将“cookie”转换为 byte[]? Enryption:

HttpCookie myCookie = new HttpCookie("co");
myCookie.Values.Add("customerId", dr["customerId"].ToString());

using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
{
    byte[] encrypted = AesEncryption.EncryptStringToBytes_Aes(myCookie.ToString(),    myAes.Key, myAes.IV);
}
Response.Cookies.Add(myCookie);

Decription:

HttpCookie myCookie = Request.Cookies["co"];
byte[] encrypted = myCookie;

using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
{
   string decripted = AesEncryption.DecryptStringFromBytes_Aes(myCookie.ToString(), myAes.Key, myAes.IV);
}
4

3 回答 3

1

我认为您正在尝试做的是加密一个值,然后在 cookie 中设置该值。显示的代码没有这样做。您需要做的是:

  1. 加密值
  2. 将加密的字节转换为可打印的字符串(因为 cookie 是纯文本),base64 编码是一个常见的选项。
  3. 在 cookie 中设置该值。
  4. 在响应中设置 cookie。

当试图恢复到原始值时,向后运行相同的过程。

于 2013-08-03T12:31:56.303 回答
1
byte[] b1 = System.Text.Encoding.ASCII.GetBytes(myCookie.ToString());
string str1 = Convert.ToBase64String(b1);

byte[] b2 = Convert.FromBase64String(str1);
string str2 = System.Text.Encoding.ASCII.GetString(b2);
于 2013-08-03T12:56:57.413 回答
0
HttpCookie myCookie = new HttpCookie("co");

using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
{
    byte[] encrypted = AesEncryption.EncryptStringToBytes_Aes(dr["customerId"].ToString(), myAes.Key, myAes.IV);
myCookie.Values.Add("customerId", Convert.ToBase64String(encrypted));
}
Response.Cookies.Add(myCookie);

并在解密前做相反的事情

HttpCookie myCookie = Request.Cookies["co"];
byte[] encrypted = Convert.FromBase64String(myCookie.Value);
于 2013-08-03T12:48:49.723 回答