首页 > 解决方案 > Asp.Net Core Data Protection API 用于保护数据库中的数据

问题描述

我想加密一些机密信息并将其保存到数据库中,然后再解密。

我已经让所有这些工作正常,并且我正在保护和保留 Aws S3 和 KMS 上的密钥。

这会让我无限期地解密数据还是我必须考虑什么?

ConfigureServices 的代码片段 - startup.cs

services.AddSingleton<IAmazonS3>(new AmazonS3Client(RegionEndpoint.EUWest2));
services.AddSingleton<IAmazonKeyManagementService>(new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest2));

services.AddDataProtection()
        .ProtectKeysWithAwsKms(Configuration.GetSection("KmsProtection"))
        .PersistKeysToAwsS3(Configuration.GetSection("S3Persistence"));

var cipherOptions = Configuration.GetSection("CipherOptions");
services.Configure<CipherOptions>(cipherOptions);

services.AddScoped(typeof(ICipherService), typeof(CipherService)); 

密码服务.cs

public class CipherService : ICipherService
{
    private readonly IDataProtectionProvider dataProtectionProvider;
    private readonly string purpose;

    public CipherService(IDataProtectionProvider dataProtectionProvider, IOptions<CipherOptions> options)
    {
        this.dataProtectionProvider = dataProtectionProvider;
        this.purpose = options.Value.Purpose;
    }

    public string Encrypt(string input)
    {
        var protector = dataProtectionProvider.CreateProtector(purpose);
        return protector.Protect(input);
    }

    public string Decrypt(string cipherText)
    {
        var protector = dataProtectionProvider.CreateProtector(purpose);
        return protector.Unprotect(cipherText);
    }
}

标签: securityencryptionasp.net-core

解决方案


听起来您几乎是在问加密数据是否有某种时间限制(?)。如果是这样:不,没有。

只要您可以访问加密数据以及解密它的密钥,那么您应该能够随时随地解密并阅读它。是的,无限期。

作为旁注,您是否将加密数据及其密钥存储在同一个地方并不完全清楚。如果是这样,那可能是个坏主意。如果加密数据的目的是保证其安全,那么将密钥放在它旁边就没有意义了;那么您不妨将其存储为纯文本。

简而言之,只要您的加密足够好,您就可以将数据存储在您喜欢的任何地方;最重要的是您可以在需要时自己访问它。

至于您的密钥,您可能应该将其存储在至少两个不同的地方(冗余以防万一您丢失了一个 - 否则,您的数据将永远丢失!),并确保两者都像其他人一样安全且无法访问可能的。


推荐阅读