<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.: microcode.es :. &#187; app.config</title>
	<atom:link href="http://www.microcode.es/tag/app-config/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.microcode.es</link>
	<description>Un blog sobre programación en .NET y otras locuras más...</description>
	<lastBuildDate>Mon, 30 Aug 2010 21:29:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>C# Encriptar y desencriptar ficheros de configuración</title>
		<link>http://www.microcode.es/2008/09/13/c-encriptar-y-desencriptar-ficheros-de-configuracion/</link>
		<comments>http://www.microcode.es/2008/09/13/c-encriptar-y-desencriptar-ficheros-de-configuracion/#comments</comments>
		<pubDate>Sat, 13 Sep 2008 18:21:21 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[app.config]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[desencriptar]]></category>
		<category><![CDATA[encriptar]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://www.microcode.es/?p=93</guid>
		<description><![CDATA[Usar ficheros de configuración es algo muy común en el desarrollo de aplicaciones, tanto web como windows. En .net tenemos el fichero app.config (web.config) para
poder guardar información que puede cambiar en cualquier momento. Es muy típico almacenar en estos ficheros las cadenas de conexión que usará nuestra aplicación,
pero ¿qué pasa si en esta cadena de [...]]]></description>
			<content:encoded><![CDATA[<p>Usar ficheros de configuración es algo muy común en el desarrollo de aplicaciones, tanto web como windows. En .net tenemos el fichero app.config (web.config) para<br />
poder guardar información que puede cambiar en cualquier momento. Es muy típico almacenar en estos ficheros las cadenas de conexión que usará nuestra aplicación,<br />
pero ¿qué pasa si en esta cadena de conexión va el nombre de usuario / contraseña, y no queremos que el usuario de la aplicación la conozca, abriendo este fichero?.<br />
La solución es bastante simple, sólo tenemos que encriptar / desencriptar nuestro fichero de configuración. Este proceso puede parece muy complicado pero con .NET<br />
es realmente fácil.</p>
<p>El framework de .NET pone a nuestra disposición el ProtectionProvider, con las implementaciones DataProtectionConfigurationProvider y RSAProtectedConfigurationProvider.</p>
<p>Encriptar un sección de nuestro fichero de configuración y guardarla es tan fácil como</p>
<pre>[sourcecode language='csharp']

private void buttonEncrypt_Click(object sender, EventArgs e)
 {
 string provider = "DataProtectionConfigurationProvider";
 //string provider = "RSAProtectedConfigurationProvider";

Configuration configuration = null;
 ConnectionStringsSection section = null;

try
 {
 configuration = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

if (configuration != null)
 {
 bool changed = false;
 section = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
 if (section != null)
 {
 if ((!(section.ElementInformation.IsLocked)) &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; (!(section.SectionInformation.IsLocked)))
 {
 if (!(section.SectionInformation.IsProtected))
 {
 changed = true;

// Encrypt the section.
 section.SectionInformation.ProtectSection(provider);
 }
 }

if (changed)
 {
 // Indicates whether the associated configuration section will be saved even if it has not been modified.
 section.SectionInformation.ForceSave = true;

// Save the current configuration.
 configuration.Save();
 }
 }
 }
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.Message);
 }
 }

[/sourcecode]</pre>
<p>Para desencriptarla tan sólo debemos hacer</p>
<pre>[sourcecode language='csharp']

private void buttonDecrypt_Click(object sender, EventArgs e)
 {
 Configuration configuration = null;
 ConnectionStringsSection section = null;

try
 {
 configuration = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

if (configuration != null)
 {
 bool changed = false;
 section = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
 if (section != null)
 {
 if ((!(section.ElementInformation.IsLocked)) &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; (!(section.SectionInformation.IsLocked)))
 {
 if (section.SectionInformation.IsProtected)
 {
 changed = true;

// Encrypt the section.
 section.SectionInformation.UnprotectSection();
 }
 }

if (changed)
 {
 // Indicates whether the associated configuration section will be saved even if it has not been modified.
 section.SectionInformation.ForceSave = true;

// Save the current configuration.
 configuration.Save();
 }
 }
 }
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.Message);
 }
 }

[/sourcecode]</pre>
<p>Y la seccion &lt;connectrionStrings&gt; de nuestro fichero de configuración que originalmente era</p>
<pre>[sourcecode language='xml']

<connectionStrings>
 <add name="default" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=pubs;Persist Security Info=True;Integrated Security=SSPI;" />
 </connectionStrings>

[/sourcecode]</pre>
<p>pasará a</p>
<pre>[sourcecode language='xml']

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
 <encryptedData>
 <cipherData>;
 <cipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAXiiF4BJLPEqfjkx9sW5uUQQAAAACAAAAAAADZgAAqAAAABAAAADL7FyjP7ANaOQ1ecYsWnhBAAAAAASAAACgAAAAEAAAACEqOzhpnuUlwZ0o9CYqPduYAQAAFy/9mBUvK7zFTsqcIedI6Ay1O6Y5prCtuKmYMr5ObHD/9TMM+y6gO3wpq83qOQYpHiAs386svfRKr9nvdeHYUycJTeZq5V/c+iZvg47sW5rouqXO12Z+cUpYcxpuDaiN25xYbyNzZkwKjypEYEF3aqgS8wt0nhfepnVEoaGur7yxrXIc77xU/KTs7cSfjkSFMI4xvRzBr9sgKQikpeoFsohBuP5fqOLKSYNMxlszuy50KblfzqE9Jj2a6PhLpVWOGdLwvofnTAYpNMNhxyhfNKv/oLg2+IWahuOwaStnVE32cEFlaxKdQ18VwZv2A/UWoKJw1XRHGsPmVPG7ToOZZC9/+Al2amJfXYp8GFQIOgNF8T1crkQvm5TC9lO7JloDxXqjKIROs140CmuYPQXTcBFoghAgXzkNEK3BNGOGSe0twjdkt511zeOkYf2a3/NpA/hTed25ffaVBvxtCNWwHw64oNwhDOcA3JtCL7QFCqLqUPFndoCEYHAAEsxc3LaVZrfD2ymTvPitceZxceKH0mtf0SgECrTHFAAAAONP+7+I5+McJmln/tAYJoiVKsv2</cipherValue>
 </cipherData>
 <encryptedData>
 </connectionString>

[/sourcecode]</pre>
<p>Hay que tener en cuenta que hay determinadas secciones que no se pueden encriptar como son</p>
<p>- &lt;processModel&gt;<br />
- &lt;runtime&gt;<br />
- &lt;mscorlib&gt;<br />
- &lt;startup&gt;<br />
- &lt;system.runtime.remoting&gt;<br />
- &lt;configProtectedData&gt;<br />
- &lt;satelliteassemblies&gt;<br />
- &lt;cryptographySettings&gt;<br />
- &lt;cryptoNameMapping&gt;<br />
- &lt;cryptoClasses&gt;</p>
<p>También hay que recordar que el proceso de encriptar y desencriptar el fichero de configuración puede afectar al rendimiento de nuestra aplicación.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2008/09/13/c-encriptar-y-desencriptar-ficheros-de-configuracion/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

