Encryption du web.config

Encrypter des sections du web.config en ASP.NET 4.0
Introduction
ASP.NET 4.0 nous offre un moyen très simple d'encrypter n'importe quelle section du fichier web.config, à l'aide de la méthode ProtectSection() de la classe System.Configuration.SectionInformation.

Cette technique offre l'avantage de ne nécessiter aucune modification du code existant ; la lecture des valeurs stockées dans le fichier web.config continue à se faire à l'aide de la classe ConfigurationManager.

Nous allons donc créer une simple page d'administration nous permettant de crypter/décrypter à volonté notre fichier de configuration.

Code source

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace WebConfigEncryption
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void EncryptSection(string sectionName, string provider)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}
private void DecryptSection(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)
{
EncryptSection("appSettings", "DataProtectionConfigurationProvider");
}
protected void btnDecrypt_Click(object sender, EventArgs e)
{
DecryptSection("appSettings");
}
}
}

Utilisation
La figure 2 ci-dessous montre le résultat de l'encyptage de la section connectionStrings du fichier web.config présenté dans la figure 1 :


Malgré l'encryptage de la section, la lecture d'une chaîne de connection se fait de manière tout à fait standard :

string sValue = ConfigurationManager.ConnectionStrings["MembershipConnectionString"];

Commentaires