Warm tip: This article is reproduced from serverfault.com, please click

c#-如何在ASP.NET Core 2的appsettings.json中加密密码?

(c# - How do you encrypt a password within appsettings.json for ASP.net Core 2?)

发布于 2018-01-08 22:56:38

我想使用我的appsettings.json来存储“主密码”。

然后,将使用此主密码来打开由这个出色的密码存储包生成的私钥(及其后续的密码存储):https : //github.com/neosmart/SecureStore

问题是,我想不出任何方式来加密主密码。我知道在.NET 4.5中,可以执行以下操作:

1)将密码放入web.config文件

2)运行此脚本:aspnet_regiis.exe -pef appSettings“ C:\ myfolder”

3)你的密码最终将被加密-但是你的程序可以安全地读取该密码。

https://www.codeproject.com/Articles/599416/Encrypting-ASP-NET-Application-Settings

我是要以正确的方式这样做还是有更好的做法?

Questioner
Ryan Battistone
Viewed
0
2020-09-19 14:56:34

请记住,不要在网站的主目录appsettings.json存储机密,通常将其存储在源代码管理中。使用文件提供程序将文件定位在服务器上其他位置。

如果有权访问Azure,则可以将机密存储在Azure Key Vault中,而不是appsettings.json

考虑到这一点,如果你想使用JSON文件,则可以使用网桥或代理类来处理值的解密。

首先,你将需要一个类来解密值。为简便起见,在这里我将不涉及解密类的详细信息,而只是假设SettingsDecryptor已编写了一个名为的类,ISettingsDecryptor使用一个解密字符串值的单一方法Decrypt实现了调用的接口

bridge类采用两个构造函数参数。

  • 第一个是IOptions<T>or IOptionsSnapshot<T>,其中T是该部分appsettings.json 通过services.Configure方法(Eg MyAppSettings绑定到的另外,如果你不想绑定到一个类,则可以IConfiguration改用并直接从配置中读取。
  • 第二个是实现的解密类ISettingsDecryptor

在网桥类中,每个需要解密的属性都应使用解密类来解密配置中的加密值。

public class MyAppSettingsBridge : IAppSettings
{
    private readonly IOptions<MyAppSettings> _appSettings;

    private readonly ISettingsDecrypt _decryptor;

    public MyAppSettingsBridge(IOptionsSnapshot<MyAppSettings> appSettings, ISettingsDecrypt decryptor) {
        _appSettings = appSettings ?? throw new ArgumentNullException(nameof(appSettings));
        _decryptor = decryptor ?? throw new ArgumentException(nameof(decryptor));
    }

    public string ApplicationName => _appSettings.Value.ApplicationName;

    public string SqlConnectionSting => _decryptor.Decrypt(_appSettings.Value.Sql);

    public string OracleConnectionSting => _decryptor.Decrypt(_appSettings.Value.Oracle);
}

DI容器应设置如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddOptions();            
    services.Configure<MyAppSettings>(Configuration.GetSection("MyAppSettings"));
    services.AddSingleton(Configuration);        
    services.AddSingleton<ISettingsDecrypt, SettingsDecryptor>();
    services.AddScoped<IAppSettings, MyAppSettingsBridge>();
}

然后,控制器可以具有一个构造函数,该构造函数将桥接器作为IAppSettings来访问解密的设置。

上面的答案是整个解决方案的简短摘要,因为需要大量代码。

可以在我的博客文章“隐藏秘密appsettings.json-在ASP.Net Core配置中使用网桥(第4部分)”看到完整的详细说明,在此我详细描述了使用网桥模式。Github上还有一个完整的示例(包括解密类),位于https://github.com/configureappio/ConfiguarationBridgeCrypto