有時設計客戶端程序,需要發佈給其他人使用,如app.config文件中存在一些敏感數據,存在一定的安全隱患,解決辦法之一就是加密這些配置文件中的敏感數據,可以在用戶安裝程序時自動加密配置文件內容。
方法之一 就是使用.net 的兩個提供程序,好處就是使用配置文件中配置時,.net 自動解密,代碼不需要調整,如同未使用加密配置。
DPAPIProtectedConfigurationProvider 使用 Windows 數據保護 API (DPAPI)對數據進行加密和解密。 加密後的文件只能在加密的機器上解密,拷貝到其他機器上不能解密
RsaProtectedConfigurationProvider 使用 RSA 加密算法對數據進行加密和解密。可以實現加密後的文件拷貝的其他機器上進行解密
可以根據需求選擇其一進行加密,針對DPAPIProtectedConfigurationProvider 的使用,過程如下:
1 新建windows 應用程序 demoapp
2 添加配置文件app.config,內容如下:
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="constr" connectionString="Data Source=100.223.22.21;Initial Catalog=testdb;Persist Security Info=True;User ID=sa;Password=xyzpdd54655" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
加密內容是connectionstrings配置節
3.添加安裝類(installer)文件,demoapp_installer.cs 內容如下:
[RunInstaller(true)]
public partial class demoapp_installer: System.Configuration.Install.Installer
{
public guang_caiji_installer()
{
InitializeComponent();
}
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
ProtectSection("connectionStrings", Context.Parameters["assemblypath"]);
}
private void ProtectSection(string connectionStrings, string exeFilePath)
{
Configuration configuration = null;
// Open the configuration file and retrieve the connectionStrings section.
configuration = ConfigurationManager.OpenExeConfiguration(exeFilePath);
ConnectionStringsSection configSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
if ((!(configSection.ElementInformation.IsLocked)) && (!(configSection.SectionInformation.IsLocked)))
{
if (!configSection.SectionInformation.IsProtected)
{
//this line will encrypt the file
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
//re-save the configuration file section
configSection.SectionInformation.ForceSave = true;
// Save the current configuration
configuration.Save();
//configFile.FilePath
}
}
4.添加安裝項目 setup project demoapp_setup
View—File System—Application Folder —Add— Project output,選擇primary output
5.添加自定義動作 custome action
install 裏面添加
6.編譯發佈安裝包,安裝後可以看到配置文件connectionstrings節已經加密