Asp.NET Core 中如何加密 Configuration ?

咨询区

  • Ovi

web.config 已进入历史垃圾堆,请问现在的 asp.net core 如何更好的做到将敏感信息(password,token) 存储到 configuration 中?

换句话说:是否可以自动化解密 appsettings.json 中的 configuration p 节中加密的内容。

回答区

  • CoderSteve

要想保护隐私,最好的方式就是将密文放置在 appsettings.json 中,那如何让程序自动化解密在 appsetting.json 中的密文呢?通常有两种做法。

  1. 继承并实现 ConfigurationProvider, IConfigurationSource

这种方式太麻烦,我就不演示了。

  1. 重写 JsonConfigurationProvider 方法

这种方式相对简单,重写它的 Load 方法并实现解密逻辑,参考如下代码。


public class JsonConfigurationProvider2 : JsonConfigurationProvider
{
    public JsonConfigurationProvider2(JsonConfigurationSource2 source) : base(source)
    {
    }

    public override void Load(Stream stream)
    {
        // Let the base class do the heavy lifting.
        base.Load(stream);

        // Do decryption here, you can tap into the Data property like so:

         Data["abc:password"] = MyEncryptionLibrary.Decrypt(Data["abc:password"]);

        // But you have to make your own MyEncryptionLibrary, not included here
    }
}

public class JsonConfigurationSource2 : JsonConfigurationSource
{
    public override IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        EnsureDefaults(builder);
        return new JsonConfigurationProvider2(this);
    }
}

public static class JsonConfigurationExtensions2
{
    public static IConfigurationBuilder AddJsonFile2(this IConfigurationBuilder builder, string path, bool optional,
        bool reloadOnChange)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }
        if (string.IsNullOrEmpty(path))
        {
            throw new ArgumentException("File path must be a non-empty string.");
        }

        var source = new JsonConfigurationSource2
        {
            FileProvider = null,
            Path = path,
            Optional = optional,
            ReloadOnChange = reloadOnChange
        };

        source.ResolveFileProvider();
        builder.Add(source);
        return builder;
    }
}

有了它,然后就可以在 CreateHostBuilder 时进行配置。


        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(config =>
            {
                config.AddJsonFile2("xxx.appsettings", true, true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

点评区

其实在很早的时候我一直不理解这种做法,既然要放在配置文件中为啥还要加密起来,在平时开发的时候给自己带来了诸多不便,为此我还写了一篇文章 配置文件中的数据库连接串加密了,你以为我就挖不出来吗? 来聊这个问题,我可以直接用 windbg 到进程里拿明文字符串,毕竟最后的 SqlCommand 需要明文去连接数据库哈,只能说这种防君子不防小人。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值