c# - 在不使用 IDataProtector 的情况下,在 ASP.NET Core 中加密 cookie 的简单/体面的方法是什么?

标签 c# encryption asp.net-core

我想了解如何在 ASP.NET Core 2.1 中加密 cookie 的内容。

如果我使用 IDataProtector Protect 方法来加密 cookie 的内容,我已经了解到如果网站移动到不同的服务器,Unprotect 方法将无法解密,在服务器场、Azure 等中运行 如果这是真的,并且我不想使用 Redis(或四处移动 key ),并且能够使用一种简单的方法来加密内容,我将如何处理这个问题?

这是我当前的代码(使用 IDataProtector):

    public static void SetEncryptedCookie()
    {
        var cookieData = new Dictionary<string, string>()
        {
            { "a", "123" },
            { "b", "xyz" },
            { "c", DateTime.Now.ToString() },
            { "UserID", "unique-number-789" }
        };

        CookieOptions options = new CookieOptions
        {
            Expires = DateTime.Now.AddDays(90)
            ,HttpOnly = true
            ,Secure = true
            ,IsEssential = true // GDPR
            ,Domain = ".example.org"
        };

        // _dataProtector = provider.CreateProtector("somepurpose");
        string protectedCookie = _dataProtector.Protect(cookieData);

        // IHttpContextAccessor _accessor
        // write cookie to http response 
        _accessor.HttpContext.Response.Cookies.Append("mycookie", protectedCookie, options);

        // retrieve encrypted cookie contents.
        // ##### this will fail in server farms.
        var cookieEnc = _accessor.HttpContext.Request.Cookies["mycookie"];
        var cookieDec =  _dataProtector.Unprotect(cookieEnc);
    }

最佳答案

public void ConfigureServices(IServiceCollection services)

DirectoryInfo SharedKeysDataProtectionDirectory = new DirectoryInfo("shared/KeysDataProtection/Directory");
services.AddDataProtection()
        .SetApplicationName("WebFarmSharedAppName")
        .PersistKeysToFileSystem(SharedKeysDataProtectionDirectory);

关于c# - 在不使用 IDataProtector 的情况下,在 ASP.NET Core 中加密 cookie 的简单/体面的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395650/

相关文章:

c# - MSTest:CS0117 'Assert' 不包含 'ThrowsException' 的定义

iphone - 我的应用程序是 "contain encryption"吗?

php - PHP中的加解密算法

c# - .NET Core 项目引用问题 - "Cannot find project info for ' XXX.csproj'”

Docker dotnet watch 运行错误 : Unable to bind to https://localhost:5000 on the IPv6 loopback interface

c# - 正确使用 BeginReceive/EndReceive?

c# - 如何使用环回 IP 检索身份验证 token

c# - 编码文本文件以显示在 IBM 大型机上

security - 加盐和散列可以防止对单个帐户的攻击吗?

c# - 在 ASP.NET Core(以前的 ASP.NET 5)中嵌套路由的便捷方式是什么?