DataProtectionConfigurationProvider加密web.config文件

web.config 文件中经常会包含一些敏感信息,最常见的就是数据库连接字符串了,为了防止该信息泄漏,最好是将相关内容加密。

Aspnet_regiis.exe命令已经提供了加密配置文件的方法,系统默认提供两种加密方式:

DataProtectionConfigurationProvider
RSAProtectedConfigurationProvider
当然,如果有兴趣也可以编写自己的加密提供程序。

本文主要讲解如何利用DataProtectionConfigurationProvider来完成web.config的加解密

一 建立虚拟目录 http://localhost/EncryptWebConfig,并添加web.config,其中包含数据库连接字符串:

<connectionStrings>
<add name="Conn" connectionString="Data Source=liuwu;User ID=liuwu;Password=liuwu;"/>
</connectionStrings>

二 运行 aspnet_regiis -pe "connectionStrings" -app "/EncryptWebConfig" -prov "DataProtectionConfigurationProvider"

aspnet_regiis 位于%WinDir%Microsoft.NETFramework<versionNumber>目录下。
-pe 指定要加密的配置节,这里是 connectionStrings 。
-app 指定该配置文件所在的虚拟目录,这里是EncryptWebConfig。
-prov 指定要使用的提供程序,这里使用的是DataProtectionConfigurationProvider。
三 加密后连接字符串已经不可见了,可以看到如下形式的配置节

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAw=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

四 如果要解密,则运行以下命令 aspnet_regiis -pd "connectionStrings" -app "/EncryptWebConfig"

-pd 指定要解密的配置节
-app 指定虚拟目录
五 如果不想建立虚拟目录,也可以指定配置文件的物理路径:aspnet_regiis.exe -pef "connectionStrings" d:EncryptWebConfig -prov "DataProtectionConfigurationProvider"

-pef 指定要加密的配置节及配置文件的物理路径
六 解密使用 aspnet_regiis -pdf "connectionStrings" d:EncryptWebConfig

-pdf 指定要解密的配置节及配置文件的物理路径

http://www.veryhuo.com/a/view/9885.html

原文地址:https://www.cnblogs.com/chen110xi/p/4963079.html