Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >ASP.NET核中的加密配置

ASP.NET核中的加密配置
EN

Stack Overflow用户
提问于 2016-03-17 05:56:12
回答 5查看 83.7K关注 0票数 71

随着web.config的消失,在使用ASP.NET核心构建的web应用程序的配置中存储敏感信息(密码、令牌)的首选方法是什么?

有没有一种方法可以在appsettings.json中自动获得加密的配置部分?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-03-17 06:48:56

用户秘密看起来是一个很好的解决方案,用于存储密码,通常情况下,应用程序机密,至少在开发期间是这样。

检查一下微软官方文档。您还可以查看其他这样的问题。

这只是在开发过程中“隐藏”您的秘密并避免将它们泄露到源树中的一种方法;秘密管理器工具不加密存储的机密,不应将其视为受信任的存储。

如果您想要将加密的appsettings.json引入生产,可以通过构建一个自定义配置提供程序来实现。

例如:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class CustomConfigProvider : ConfigurationProvider, IConfigurationSource
{
    public CustomConfigProvider()
    {
    }

    public override void Load()
    {
        Data = UnencryptMyConfiguration();
    }

    private IDictionary<string, string> UnencryptMyConfiguration()
    {
        // do whatever you need to do here, for example load the file and unencrypt key by key
        //Like:
       var configValues = new Dictionary<string, string>
       {
            {"key1", "unencryptedValue1"},
            {"key2", "unencryptedValue2"}
       };
       return configValues;
    }

    private IDictionary<string, string> CreateAndSaveDefaultValues(IDictionary<string, string> defaultDictionary)
    {
        var configValues = new Dictionary<string, string>
        {
            {"key1", "encryptedValue1"},
            {"key2", "encryptedValue2"}
        };
        return configValues;                
    }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
       return new CustomConfigProvider();
    }
}

为扩展方法定义一个静态类:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static class CustomConfigProviderExtensions
{              
        public static IConfigurationBuilder AddEncryptedProvider(this IConfigurationBuilder builder)
        {
            return builder.Add(new CustomConfigProvider());
        }
}

然后你可以激活它:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// Set up configuration sources.
var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEncryptedProvider()
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
票数 35
EN

Stack Overflow用户

发布于 2018-06-20 08:14:29

我同意@CoderSteve的观点,写一个全新的提供者是太多的工作了。它也不基于现有的标准JSON体系结构。下面是我在标准JSON体系结构之上提出的一个解决方案,它使用了首选的.Net核心加密库,并且对DI非常友好。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static class IServiceCollectionExtensions
{
    public static IServiceCollection AddProtectedConfiguration(this IServiceCollection services)
    {
        services
            .AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(@"c:\keys"))
            .ProtectKeysWithDpapi();

        return services;
    }

    public static IServiceCollection ConfigureProtected<TOptions>(this IServiceCollection services, IConfigurationSection section) where TOptions: class, new()
    {
        return services.AddSingleton(provider =>
        {
            var dataProtectionProvider = provider.GetRequiredService<IDataProtectionProvider>();
            section = new ProtectedConfigurationSection(dataProtectionProvider, section);

            var options = section.Get<TOptions>();
            return Options.Create(options);
        });
    }

    private class ProtectedConfigurationSection : IConfigurationSection
    {
        private readonly IDataProtectionProvider _dataProtectionProvider;
        private readonly IConfigurationSection _section;
        private readonly Lazy<IDataProtector> _protector;

        public ProtectedConfigurationSection(
            IDataProtectionProvider dataProtectionProvider,
            IConfigurationSection section)
        {
            _dataProtectionProvider = dataProtectionProvider;
            _section = section;

            _protector = new Lazy<IDataProtector>(() => dataProtectionProvider.CreateProtector(section.Path));
        }

        public IConfigurationSection GetSection(string key)
        {
            return new ProtectedConfigurationSection(_dataProtectionProvider, _section.GetSection(key));
        }

        public IEnumerable<IConfigurationSection> GetChildren()
        {
            return _section.GetChildren()
                .Select(x => new ProtectedConfigurationSection(_dataProtectionProvider, x));
        }

        public IChangeToken GetReloadToken()
        {
            return _section.GetReloadToken();
        }

        public string this[string key]
        {
            get => GetProtectedValue(_section[key]);
            set => _section[key] = _protector.Value.Protect(value);
        }

        public string Key => _section.Key;
        public string Path => _section.Path;

        public string Value
        {
            get => GetProtectedValue(_section.Value);
            set => _section.Value = _protector.Value.Protect(value);
        }

        private string GetProtectedValue(string value)
        {
            if (value == null)
                return null;

            return _protector.Value.Unprotect(value);
        }
    }
}

连接受保护的配置部分,如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // Configure normal config settings
    services.Configure<MySettings>(Configuration.GetSection("MySettings"));

    // Configure protected config settings
    services.AddProtectedConfiguration();
    services.ConfigureProtected<MyProtectedSettings>(Configuration.GetSection("MyProtectedSettings"));
}

您可以使用如下控制器轻松地为您的配置文件创建加密值:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[Route("encrypt"), HttpGet, HttpPost]
public string Encrypt(string section, string value)
{
    var protector = _dataProtectionProvider.CreateProtector(section);
    return protector.Protect(value);
}

用法:http://localhost/cryptography/encrypt?section=SectionName:KeyName&value=PlainTextValue

票数 26
EN

Stack Overflow用户

发布于 2016-12-08 11:49:03

我不想写一个自定义的提供者-太多的工作。我只想进入JsonConfigurationProvider,所以我想出了一种适合我的方法,希望它能帮助别人。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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;
    }
}
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36062670

复制
相关文章
TLS协议分析 (三) record协议
record协议做应用数据的对称加密传输,占据一个TLS连接的绝大多数流量,因此,先看看record协议 图片来自网络:
用户8964349
2021/09/06
1.4K0
TLS握手协议详解
握手协议是TLS握手协议的一部分,负载生成共享密钥以及交换证书。其中,生成共享密钥是为了进行密码通信,交换证书是为了通信双方相互进行认证。
用户9407507
2022/02/16
1.3K0
TLS协议学习笔记
说起TLS(Transport Layer Security 传输层安全协议),可能有点陌生,但是说起HTTPS,大家应该都知道,我们现在浏览网页基本上都是HTTPS的。HTTPS就是加密的HTTP,HTTP基于明文传播,直接使用HTTP的话内容很容易被窃取。HTTPS则对内容进行了一层加密,避免了内容被窃取和篡改的可能性,如下图所示。
roper
2018/07/02
2.4K1
TLS协议学习笔记
mqttnet 详解_mqttnet3.0用法
1 ///开源库地址:https://github.com/chkr1011/MQTTnet
全栈程序员站长
2022/09/12
1K0
图解TLS握手连接
SSL:(Secure Socket Layer,安全套接字层),位于可靠的面向连接的网络层协议和应用层协议之间的一种协议层。SSL通过互相认证、使用数字签名确保完整性、使用加密确保私密性,以实现客户端和服务器之间的安全通讯。该协议由两层组成:SSL记录协议和SSL握手协议。
半月弧
2020/03/03
5.4K0
图解TLS握手连接
TLS协议分析 (四) handshake协议概览
TLS 1.3对握手做了大修改,下面先讲TLS 1.2,讲完再介绍一下分析TLS 1.3.
用户8964349
2021/09/07
1.5K0
TLS协议分析 (六) handshake协议扩展
在 ChangeCipherSpec 消息之后,应该立即发送 Finished 消息,来确认密钥交换和认证过程已经成功了。ChangeCipherSpec 必须在其它握手消息和 Finished 消息之间。
用户8964349
2021/09/07
1.3K0
DTLS协议介绍,Udp协议基于TLS
UDP协议是不面向连接的不可靠协议,且没有对传输的报文段进行加密,不能保证通信双方的身份认证、消息传输过程中的按序接收、不丢失和加密传送。
Kunkka Wu
2022/01/13
3.1K0
DTLS协议介绍,Udp协议基于TLS
mqttnet 详解_mqttnet 简记
1.mqttnet开源库,https://github.com/chkr1011/MQTTnet
全栈程序员站长
2022/09/12
3K0
MQTTnet[通俗易懂]
近期学习了一下物联网中应用较广的MQTT协议,同时使用MQTTnet开源类库做了简单实现,因此做下笔记。 环境:.NET Framework 4.6.1 MQTTnet 2.8.2.0 遵循MQTT 3.1.0协议规范 源码 >>> GitHub 注意:在实现订阅者离线再连接时,一直接受不到离线信息,需要做一下配置
全栈程序员站长
2022/09/12
7970
mqttnet 详解_MQTT MQTTnet 实现
│ │ ├── MQTTServer.runtimeconfig.dev.json
全栈程序员站长
2022/09/12
9210
检查网站的TLS版本
有时候需要知道某个网站支持的TLS的版本。现在SSL 2.0和SSL 3.0都已经被淘汰了。其中TLS 1.0,TLS 1.1,TLS 1.2是目前的的主流,相对也是安全的。主要看加密的算法。TLS 1.3是目前最新的协议版本,也是相对最安全的版本了。
宋天伦
2023/10/21
4.4K0
检查网站的TLS版本
轻量通讯协议 --- MQTT
「MQTT(Message Queuing Telemetry Transport)」 是一种轻量级的消息传输协议,通常用于在物联网(IoT)和传感器网络中进行通信。它设计用于在低带宽、不稳定或高延迟的网络环境下传输数据,因此非常适用于连接设备之间的通信,尤其是在资源有限的环境中。
Niuery Diary
2023/10/22
4.1K0
轻量通讯协议 --- MQTT
TLS加密远程连接Docker
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
程序员欣宸
2019/09/18
2.1K0
TLS加密远程连接Docker
如何建立TLS连接?TLS握手失败可能这个原因!
签前面三个案例里的HTTP都没加密,使排查工作省去不少麻烦,抓包文件里直接就看清应用层信息。
JavaEdge
2023/07/25
1.4K0
如何建立TLS连接?TLS握手失败可能这个原因!
mqttnet 详解_MQTTnet 3.0.5学习笔记
段时间在使用MQTTnet,都说这个东西比较好,可是翻了翻网上没有例子给参考一下。
全栈程序员站长
2022/09/12
1.1K0
golang简单tls协议用法完整示例
本文实例讲述了golang简单tls协议用法。分享给大家供大家参考,具体如下: 生成私钥: openssl genrsa -out key.pem 2048 生成证书: openssl req -new -x509 -key key.pem -out cert.pem -days 3650 https: package main import ( "io" "net/http" "log" ) func HelloServer(w http.ResponseWrite
李海彬
2018/03/27
3.8K0
golang简单tls协议用法完整示例
本文实例讲述了golang简单tls协议用法。分享给大家供大家参考,具体如下: 生成私钥: openssl genrsa -out key.pem 2048 生成证书: openssl req -new -x509 -key key.pem -out cert.pem -days 3650 https: package main import ( "io" "net/http" "log" ) func HelloServer(w http.ResponseWriter, req *
李海彬
2018/03/26
3.3K0
SSL / TLS 协议运行机制详解
本文简要介绍SSL/TLS协议的运行机制。文章的重点是设计思想和运行过程,不涉及具体的实现细节。如果想了解这方面的内容,请参阅RFC文档。
Java技术栈
2018/07/30
8130
SSL / TLS 协议运行机制详解
点击加载更多

相似问题

AttributeError:“函数”对象没有属性“as_view”

18

Django "AttributeError:‘函数’对象没有属性'as_view'“

11

AttributeError - CBV‘函数’对象没有属性'as_view‘。

12

AttributeError:输入对象'DirectView‘没有属性'as_view’

10

AttributeError:'function‘对象没有属性'as_view’。怎么了?

22
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文