我尝试使用以下代码加密和解密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 = 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);
答案 0 :(得分:1)
我认为你要做的是加密一个值,然后在cookie中设置该值。显示的代码不会这样做。你需要做的是:
尝试返回原始值时,向后运行相同的过程。
答案 1 :(得分: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);
答案 2 :(得分: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);