C#为配置文件加密的实现方法

2019-12-26 12:21:30王冬梅

System.Configuration.DPAPIProtectedConfigurationProvider:在System.Configuration.dll中,使用Windows DPAPI(Data Protection API)来进行加密,密钥存在Windows Local Security Authority(LSA)中。

注意:当使用DPAPIProtectedConfigurationProvider时,加密文件所使用的帐号需要与运行web application的帐号相同,否则web application无法解密加密的内容。
System.Configuration.RSAProtectedConfigurationProvider:在System.Configuration.dll中,使用RSA算法来进行加密(RSA算法是非对称加密,具体可参见前面一篇文章C#对称加密与非对称加密),公钥存放在config文件当中,只有加密的计算机有密钥。RSAProtectedConfigurationProvider通常是默认的缺省provider。

二、加密文件的命令

加密web.config文件可以使用:

 

复制代码 aspnet_regiis -pef section web-app-physical-dir

 

Encrypt the configuration section. Optional arguments:

[-prov provider] Use this provider to encrypt.

 

比如运行下面的命令就会分别对connectionStrings和appSettings中的信息进行加密:

 

复制代码 aspnet_regiis.exe -pef "connectionStrings" "C:mywebHelloService"

 

aspnet_regiis.exe -pef "appSettings" "C:mywebHelloService"

 

C#为配置文件加密的实现方法

加密后的web.config文件变成:

 

复制代码 <?xml version="1.0"?>
<configuration>
    <system.web>
      <compilation targetFramework="4.0" />
    </system.web>
    <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
        <EncryptedData Type="http://www.easck.com/2001/04/xmlenc#Element"