<?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>SharpDeveloper &#187; Deconstructing Subtext</title>
	<atom:link href="http://www.sharpdeveloper.net/content/archive/category/deconstructing-subtext/feed" rel="self" type="application/rss+xml" />
	<link>http://www.sharpdeveloper.net/content</link>
	<description>C# articles and tutorials on SharpDeveloper.NET</description>
	<lastBuildDate>Thu, 12 Aug 2010 15:17:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Encryption and Decryption for Dummies in .NET</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/06/27/encryption-for-dummies-in-net.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/06/27/encryption-for-dummies-in-net.aspx#comments</comments>
		<pubDate>Wed, 27 Jun 2007 18:21:56 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[.NET articles]]></category>
		<category><![CDATA[Deconstructing Subtext]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=131</guid>
		<description><![CDATA[Here is some code that demonstrates a very easy way to Encrypt and Decrypt using Rinjdael's (AES) algorithm.  Also explains how to use a symmetric key, how to generate a Key and IV value, and real source code you can use in your application.]]></description>
			<content:encoded><![CDATA[<p>I was trying to figure out the easiest way that I could encrypt some text for the application I was working on. I&nbsp;struggled for a bit to figure out what was the best way to perform encryption in .NET.&nbsp; Having a piece of open source software that you can look at is very helpful, and I highly recommend it.&nbsp; You will frequently run into problems that have been solved by others time and time again, and instead of trying to re-invent the wheel, it would be in your best interests to have this toolbelt of code that you are familiar with, and that you can look up.</p>
<p>The software that this site runs on is called Subtext.&nbsp; You can download the <a href="http://downloads.sourceforge.net/subtext/SubText-1.9.5-source.zip?modtime=1178844138&amp;big_mirror=0">source code</a> or the <a href="http://downloads.sourceforge.net/subtext/SubText-1.9.5-INSTALL.zip?modtime=1178788468&amp;big_mirror=0">compiled version</a> and take a look inside at the source code to get some ideas and learn from the experience of those <a href="http://www.haacked.com/archive/2007/06/25/understanding-productivity-differences-between-developers.aspx">more experienced</a> than you and I.</p>
<p>Encryption is a massive topic and I am not even going to scratch the surface of it, but the code that follows is a simple example of how you can use it.</p>
<p>
This code demonstrates a very easy way to Encrypt and Decrypt using <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">Rinjdael&#8217;s (AES) algorithm</a>.</p>
<p>It first creates an instance of the algorithm, followed by a method that uses our instance to Encrypt, and another that uses our instance to Decrypt.&nbsp; </p>
<pre class="brush: c#">
        static SymmetricAlgorithm encryptionAlgorithm = InitializeEncryptionAlgorithm();

        static SymmetricAlgorithm InitializeEncryptionAlgorithm()
        {
            SymmetricAlgorithm rijaendel = RijndaelManaged.Create();
            rijaendel.GenerateKey();
            rijaendel.GenerateIV();
            return rijaendel;
        }

        /// &lt;summary&gt;
        /// Encrypts the string and returns a base64 encoded encrypted string.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;clearText&quot;&gt;The clear text.&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static string EncryptString(string clearText)
        {
            byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);
            byte[] encrypted = encryptionAlgorithm.CreateEncryptor().TransformFinalBlock(clearTextBytes, 0, clearTextBytes.Length);
            return Convert.ToBase64String(encrypted);
        }

        /// &lt;summary&gt;
        /// Decrypts the base64 encrypted string and returns the cleartext.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;encryptedEncodedText&quot;&gt;The clear text.&lt;/param&gt;
        /// &lt;exception type=&quot;System.Security.Cryptography.CryptographicException&quot;&gt;Thrown the string to be decrypted
        /// was encrypted using a different encryptor (for example, if we recompile and
        /// receive an old string).&lt;/exception&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static string DecryptString(string encryptedEncodedText)
        {
            try
            {
                byte[] encryptedBytes = Convert.FromBase64String(encryptedEncodedText);
                byte[] decryptedBytes = encryptionAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
                return Encoding.UTF8.GetString(decryptedBytes);
            }
            catch (FormatException fe)
            {
                //throw new CaptchaExpiredException(&quot;Encrypted encoded text &#039;&quot; + encryptedEncodedText + &quot;&#039; was not valid.&quot;, fe);
            }
            catch (CryptographicException e)
            {
                //throw new CaptchaExpiredException(&quot;Captcha image expired, probably due to recompile making the key out of synch.&quot;, e);
            }
        }
</pre>
<p>As you can see, all you need is a few methods like this, and you have .NET encryption.&nbsp; To encrypt data, simply call EncryptString(&quot;your string&quot;), and to decrypt data, simply call DecryptString(encryptedString).&nbsp; I commented out the exceptions, you will need to re-implement them as you like.&nbsp; Or you can just leave it crashing <img src='http://www.sharpdeveloper.net/content/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Source from <font face="Arial"><strong><a href="http://subtext.svn.sourceforge.net/viewvc/subtext/trunk/SubtextSolution/Subtext.Web.Controls/Captcha/CaptchaBase.cs?view=markup&amp;pathrev=2716">SubText-1.9.5-source\Subtext.Web.Controls\Captcha\CaptchaBase.cs</a></strong></font></p>
<p>This code is licensed with the new <a href="http://www.opensource.org/licenses/bsd-license.php">BSD template</a>&nbsp;- Open Source baby!</p>
<p>Update (July 10, 2007)<br />
This method will create a random key every time the application restarts, which may not be what you want.&nbsp; If this is the case, you can hardcode the key and IV values so that it will always be the same:</p>
<pre class="brush: c#">
        rijaendel.Key = Convert.FromBase64String(&quot;HUfIj72qL4OnPu1OlMBKqoufdLSw/nOsIrJiSr+lRgg=&quot;);
        rijaendel.IV = Convert.FromBase64String(&quot;p1D5hkd4xa5kyX6O7ZXR2A==&quot;);
</pre>
<p>How did I get these values?&nbsp; You don&#8217;t want to use these, but you can generate these values using the built in method above (<font face="Arial">InitializeEncryptionAlgorithm)</font>, and then store it as a string by running Convert.ToBase64String(keyValue)</p>
<p>Read &quot;<a href="http://haacked.com/archive/2006/10/02/Better_CAPTCHA_Through_Encryption.aspx">Better Captcha Through Encryption</a>&quot; for more details on how this code was implemented.</p>
<p>Another option is to set your <a href="http://www.codinghorror.com/blog/archives/000132.html">machineKey value</a> in your web.config</p>
<p>Update:  Here is another slightly more optimized way to <b>hardcore</b> your Key and IV.  Keep in mind this is not the most secure way, anyone can easily use Reflector on your DLL and get the Key and IV.</p>
<pre class="brush: c#">
            rijaendel.IV = new Byte[] { 56, 151, 249, 160, 183, 47, 5, 42, 90, 5, 207, 241, 11, 166, 166, 173 };
            rijaendel.Key = new Byte[] { 214, 145, 104, 41, 148, 129, 139, 16, 224, 38, 40, 15, 5, 254, 217, 193, 146, 43, 187, 174, 132, 181, 220, 211, 228, 181, 153, 173, 239, 194, 45, 253 };
</pre>
<p>You shouldn&#8217;t use those exact values, but run the debugger and grab new values from GenerateKey() and GenerateIV().  This is more optimized because the values don&#8217;t have to be converted back into bytes.</p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/06/27/encryption-for-dummies-in-net.aspx/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
