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

ASP.NET Core - Storing encryption key to Redis

我对数据保护机制不是很有经验,尤其是在 .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 时,但我不知道该值是什么以及它是否正常工作。

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

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

数据保护系统会帮助创建和管理密钥,您无需自己手动create/save到Redis。

另外,.PersistKeysToRedis(Redis, "DataProtection-Keys")方法中的"DataProtection-Keys"是一个RedisKey,是一条数据的唯一名称,加密的key requires 将存储为值 (RedisValue)。

how to verify if the encryption works?

您可以参考以下代码片段注入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();
}

测试结果