.net2.0下web.config敏感数据的加密

using System.Web.Configuration;
...
   
//加密web.Config中的指定节
     private void ProtectSection(string sectionName)
     {
         Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
         ConfigurationSection section = config.GetSection(sectionName);
         if (section != null && !section.SectionInformation.IsProtected)
         {
             section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
             config.Save();
         }
     }

     //解密web.Config中的指定节
     private void UnProtectSection(string sectionName)
     {
         Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
         ConfigurationSection section = config.GetSection(sectionName);
         if (section != null && section.SectionInformation.IsProtected)
         {
             section.SectionInformation.UnprotectSection();
             config.Save();
         }
     }


示例:
//加密连接字符串
protected void btnEncrypt_Click(object sender, EventArgs e)
     {
         ProtectSection("connectionStrings");
     }


变化:
加密前:
<connectionStrings>
   <add name="connStr" connectionString="Data Source=server;Initial Catalog=Lib;User ID=sa;password=3power"
    providerName="System.Data.SqlClient" />
</connectionStrings>

加密后:
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
   <EncryptedData>
    <CipherData>
     <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAYzAtjjJo0km/XdUrGFh3YAQAAAACAAAAAAADZgAAqAAAABAAAAD5H0RB6uSYHCk33lo9x5VHAAAAAASAAACgAAAAEAAAALS6KNeUNySZfZ/0tpmh7YWAAQAA85NFHJHoVx1aW5pTaFfLtTo5J9lWoBR76IYIinLiIjcTeJ4tuAstgCspZlK9NMgzyWmWbbNbb8Z8canVCUpdKF0xmTBTpVih08TtODLszcUpCsJGvEgxuDPi6JtKjG/nT+UvpRp154TNnm04LP/iq1InDxePW2tEViHIiooEXARX8FLY00RFBaUgarrfi5Fppu4usqavdnj7oqwFEbp3MXOaWY6m9qyVzNsf2G1UwBrivsrM4hZUcr1hy/S87co63ioWie8QDVgGuaTEaSyklC9STyvRsLU6A/QxalCHY4VoRjzNS/27vGoin+c3AJ587wMKJyJBiV08DyzoGM7elAlg8yTAeHvVMLOEFcTUwsCG0f2rwhi3fZYUyykczYsfHXLEXdbJ+YRiBxYWP6xzffIdyWzrawxaIfnPq/pw6e2Vrwt6tJthDImu0tzXdwupbJVdy4T5vQvy4Fw3SB9lmbSZQacekaXcViBdX7Tejx7TTpDs36RdAOf8WcVMJH4FFAAAACjQFCaOcSfbD2LXX4YP506vHDXw</CipherValue>
    </CipherData>
   </EncryptedData>
</connectionStrings>

注意:
加密后,仍然可以按以前的操作来读取,不需要额外的解决操作,因为
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
这里已经指定了用何种方式解密,asp.net会自动处理
发布了34 篇原创文章 · 获赞 1 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章