using System.Web.Configuration;
public void EncryptSection(string sectionName, string provider)
{
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
if (cfg == null)
return;
ConfigurationSection section = cfg.GetSection(sectionName);
if (section == null)
if (!section.SectionInformation.IsProtected)
section.SectionInformation.ProtectSection(provider);
cfg.Save();
}
public void DecryptSection(string sectionName)
if (section.SectionInformation.IsProtected)
section.SectionInformation.UnprotectSection();
EncryptSection("connectionStrings","RSAProtectedConfigurationProvider");
DecryptSection("connectionStrings");
EncryptSection("connectionStrings","DataProtectionConfigurationProvider");
DecryptSection("connectionStrings"); To be positive that our configuration file is indeed protected, here is a code that reads the web.config file from website root using server's FileSystem IO and displays it in the TextBox component on ASP.NET page: (we must use the IO commands to read the web.config file to see if its encrypted, because if we would just read the settings directly from our web application they would be decrypted on the fly and we would receive the real values). When using FileSystem IO functions to read the web.config file we receive its true encrypted contents:
using System.IO;
public void ShowWebConfigFile()
StreamReader sr = File.OpenText(Path.Combine(Request.PhysicalApplicationPath,"Web.Config"));
string contents = sr.ReadToEnd();
sr.Close();
webconfig.Text = contents;
TextBox1.Text = WebConfigurationManager.ConnectionStrings["local"].ConnectionString;
} and here is how our connectionStrings section should look when read this way: <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider"> <EncryptedData> <CipherData> <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAevxuCHpsWkK7mJZZB5u9DQQAAAACAAAAAAADZgAAqAAAABAAAADTY4+ 89xTx8n6fgJu3M4AEAAAAAASAAACgAAAAEAAAAJj77evc30ixlYD7sXdZyUbIAAAATK3ZOyiXebQMhT7KOT1TpRDqPxd/zeD2uwg0 4LeC7CHmMquRKcXGI5Xb7LJnNKysbfXycu7ZmUgd4i7mp3ly/unc/FVWG9PAk6b5LG8BTsdNzTQeZYT7u8Iap2BDFKPgiZqLA4SvM ti1MyjAK6P+lQCp0irWiE2yqWpMiQ82+k1SZj6AdYjNvYLmoAPFzqX1++ybMdcHueXsv4dvd5Fw2fFTh6iiBdR2xQtvgMrtP9OHmm CTM1IJ6G8Jv0oxqG7J1b3JWQSIs9MUAAAA4/q1tlT5sNGslF4/yogmvKEz4MY=</CipherValue> </CipherData> </EncryptedData> </connectionStrings>
Show Comments (0)
Loading Comments. Please Wait...