ASP.NET Core - 将加密密钥存储到 Redis

3

我对数据保护机制不是很熟悉,特别是在.NET Core/Redis上,因此我无法从官方文档中了解加密密钥是如何被存储在Redis中的。

var conn = $"{host}:{port}";
var redis = ConnectionMultiplexer.Connect(conn);

services.AddStackExchangeRedisCache(options =>
        {
            options.Configuration = conn;
        });
//here            
services.AddDataProtection()
        .PersistKeysToRedis(Redis, "DataProtection-Keys"); //where is the VALUE for the KEY? Should it be saved to Redis manually before call this?

我想知道我能用哪种密钥(我没有任何密钥,如何创建?),在哪里存储,并在配置文件中指定从哪里获取。

运行应用程序时,会将键为“DataProtection-Keys”的记录添加到Redis中,但我不知道其值是什么以及是否起作用。

所以另一个问题是,如何验证加密是否有效?

请帮助我理解基础知识,非常感谢任何示例。

1个回答

4

数据保护系统可以帮助您创建和管理密钥,您无需自己手动创建/保存到Redis中。

此外,在 .PersistKeysToRedis(Redis, "DataProtection-Keys") 方法中的 "DataProtection-Keys" 是一个 RedisKey,它是数据块的唯一名称,加密需要的密钥会以值(RedisValue)的形式存储。

如何验证加密是否有效?

您可以参考下面的代码片段来注入 IDataProtectionProvider 并使用它来创建 IDataProtector 实例,然后加密和解密数据。

IDataProtector _protector;

public HomeController(IDataProtectionProvider provider)
{
    _protector = provider.CreateProtector(" WebDataProtection.Controllers.HomeController.v1");
}

public IActionResult Index()
{
    var input = "hello world";

    // protect the payload
    string protectedPayload = _protector.Protect(input);
    ViewBag.ProtectedPayload = $"Protect returned: {protectedPayload}";

    // unprotect the payload
    string unprotectedPayload = _protector.Unprotect(protectedPayload);
    ViewBag.UnprotectedPayload = $"Unprotect returned: {unprotectedPayload}";

    return View();
}

测试结果

在这里输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接