众所周知,web.config可以存储包括数据库链接在内的众多信息,所以为配置文件加密有时候就显得必要了。
1.加密前的配置文件如下:
Web.config
1 2 34 5 87 9 12 1310 11 14 19 2015 16 18 21 2322
2.加密
(1)前端源代码
ConfigurationEncryption.aspx
1
(2)后台代码
1 private const string provider = "RSAProtectedConfigurationProvider"; //Use RSA Provider to encrypt configuration sections 2 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 6 } 7 8 protected void btnEncrypt_Click(object sender, EventArgs e) 9 { 10 if (string.IsNullOrEmpty(this.ddlSection.SelectedValue)) 11 { 12 Response.Write("please select a configuration section"); 13 //选择要加密的配置节点 14 return; 15 } 16 //获取加密的配置节点 17 string sectionString = this.ddlSection.SelectedValue; 18 //使用指定的虚拟路径将 Web 应用程序配置文件作为 System.Configuration.Configuration 对象打开以允许读或写操作。 19 Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); 20 ConfigurationSection section = config.GetSection(sectionString); 21 if (section != null) 22 { //标记配置节点,进行保护 23 section.SectionInformation.ProtectSection(provider); 24 config.Save(); 25 Response.Write("encrypt successed, please check the configuration file."); 26 } 27 } 28 29 protected void btnDecrypt_Click(object sender, EventArgs e) 30 { 31 string sectionString = this.ddlSection.SelectedValue; 32 33 Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); 34 ConfigurationSection section = config.GetSection(sectionString); 35 if (section != null && section.SectionInformation.IsProtected) 36 { 37 // 从关联的配置节中移除受保护的配置加密。 38 section.SectionInformation.UnprotectSection(); 39 config.Save(); 40 Response.Write("decrypt success, please check the configuration file."); 41 } 42 43 }
(3)加密后的效果
Rsa Key im7ZLO/++t/Iu7rVXYj7J0WvUH0cry6YgZXyY9FKE47TLBggiJPrSn+kVKBGPzSygH92ompVIhPWhJtqsTGJhdKuxRlQA5SrASmEvlB7ANo3chLoZOQbTzRyiCNFk3jOF7uoUykyFIqDPDZO9Tw9tW+iJ3LUYEhWyhOuz66GgQs= mCgroKV5diU9GnjPG7vNEB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