如何在不更改所有页面代码的情况下对现有项目中的cookie进行加密和解密

时间:2018-09-26 04:14:57

标签: asp.net .net vb.net encryption httpcookie

我正在一个项目中,其中有数千个页面使用cookie。现在出现了一个安全问题,因此我计划对cookie进行加密,并在页面级别使用它时进行解密。

我在创建我的cookie的登录页面中使用的示例代码如下:

Response.Cookies.Clear()
Response.Cookies("userinfo")("username") = "Pravin Kumar"
Response.Redirect("Home.aspx")

现在,我想在 HOME.aspx 页面中访问该Cookie。代码如下。

Response.Write(Request.Cookies("userinfo")("username"))

这是我的项目页面到目前为止的工作方式,这使用户可以在浏览器窗口中查看cookie,如下所示: Browser Cookie

现在,我的意图是我想在LOGIN.aspx页中进行一些加密,并在如此集中的位置进行解密,这样我就无需更改所有页。

PS:我已经尝试使用

处理GLOBAL.asax页面
Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)

End Sub

但是它没有帮助。请建议我是否找到最简单的方法。

1 个答案:

答案 0 :(得分:0)

您将不得不使用HttpModule来覆盖cookie读/写的行为。

这是示例代码:

首先,在您的HttpModule

public class CookieEncryptModule : IHttpModule
{
    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.PreSendRequestContent += Context_PreSendRequestContent;
        context.BeginRequest += Context_BeginRequest;
    }

    private void Context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication httpApplication = sender as HttpApplication;
        for (int i = 0; i < httpApplication.Request.Cookies.Count; i++)
        {
            var cookie = httpApplication.Request.Cookies[i];
            cookie.Value = dencryptCookieValue(cookie.Value);
        }
    }



    private void Context_PreSendRequestContent(object sender, EventArgs e)
    {
        HttpApplication httpApplication = sender as HttpApplication;
        for (int i = 0; i < httpApplication.Response.Cookies.Count; i++)
        {
            var cookie = httpApplication.Response.Cookies[i];
            cookie.Value = encryptCookieValue(cookie.Value);
        }
    }


    private string encryptCookieValue(string value)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
    }

    private string dencryptCookieValue(string value)
    {
        try
        {
            return Encoding.UTF8.GetString(Convert.FromBase64String(value));
        }
        catch
        {
            //in case some system generated cookies like session id will not be encrypted by our code
            return value;
        }

    }

}

然后在您的web.config中

  <system.webServer>
<modules>
  <add name="encryptCookie" type="[your_namespace].CookieEncryptModule, [your_assemably_name]"/>
</modules></system.webServer>

完成上述操作后, 您的Cookie现在将以base64存储在客户端中,

但是对于您来说服务器端代码是透明的,您无需更改任何内容

[notice]:这将使所有JS无法读取Cookie值

相关问题