【发布时间】:2021-10-07 04:27:24
【问题描述】:
我正在使用下面的类来处理 cookie 并使用它们在我的 ASP.NET MVC 应用程序中存储/读取值(例如购物车项目等)
1.我想知道是否在浏览器中存储的值没有任何安全性并且任何人都可以查看其内容(使用以下实现)?我检查了值是否存储为一些十六进制值,但我怀疑此实现中是否存在任何特定的加密/安全性。
2.如何修改该类以将cookie值存储为加密信息?
using System;
using System.Web;
namespace My.Application.Sample
{
public class CookieStore
{
public static void SetCookie(string key, string value)
{
SetCookie(key, value, TimeSpan.FromDays(14));
}
public static void SetCookie(string key, string value, TimeSpan expires)
{
string encodedValue = HttpUtility.UrlEncode(value);
HttpCookie encodedCookie = new HttpCookie(key, encodedValue);
if (HttpContext.Current.Request.Cookies[key] != null)
{
var cookieOld = HttpContext.Current.Request.Cookies[key];
cookieOld.Expires = DateTime.Now.Add(expires);
cookieOld.Value = encodedCookie.Value;
HttpContext.Current.Response.Cookies.Add(cookieOld);
}
else
{
encodedCookie.Expires = DateTime.Now.Add(expires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
}
/// <summary>
/// Return value stored in a cookie by defined key, if not found returns empty string
/// </summary>
/// <param name="key"></param>
/// <returns> never returns null! :) </returns>
public static string GetCookie(string key)
{
string value = string.Empty;
try
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
//if (cookie != null)
//{
// // For security purpose, we need to encrypt the value.
// HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
// value = decodedCookie.Value;
//}
if (cookie != null)
{
string encodedValue = cookie.Value;
value = HttpUtility.UrlDecode(encodedValue);
}
}
catch (Exception)
{
}
return value;
}
}
}
【问题讨论】:
标签: c# asp.net-mvc security httpcookie