<?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>Martijn's C# Programming Blog &#187; md5</title>
	<atom:link href="http://www.dijksterhuis.org/tag/md5/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Encrypting and Decrypting a C# string</title>
		<link>http://www.dijksterhuis.org/encrypting-decrypting-string/</link>
		<comments>http://www.dijksterhuis.org/encrypting-decrypting-string/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 06:31:27 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[decryption]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=453</guid>
		<description><![CDATA[The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with a little help from the MD5 hash sum generator.<br />
</em></p>
<p>The complete source code is listed below, but lets have a little look at how it works first.</p>
<p><span id="more-453"></span></p>
<p><strong>The problem</strong></p>
<p>I want to take a string, and then encrypt it using a password. The result should be a Base64 encoded string that I can store somewhere relatively safe.</p>
<pre class="brush: c#">
            // The message to encrypt.
            string Msg = &quot;This world is round, not flat, don&#039;t believe them!&quot;;
            string Password = &quot;secret&quot;;

            string EncryptedString = EncryptString(Msg, Password);
            string DecryptedString = DecryptString(EncryptedString, Password);

            Console.WriteLine(&quot;Message: {0}&quot;,Msg);
            Console.WriteLine(&quot;Password: {0}&quot;,Password);
            Console.WriteLine(&quot;Encrypted string: {0}&quot;,EncryptedString);
            Console.WriteLine(&quot;Decrypted string: {0}&quot;,DecryptedString);
</pre>
<p>In the EncryptString function we apply the TripleDES algorithm with a 128 bit key. But first we need to turn the above passphrase (&#8217;secret&#8217;) into a 128 bit key.  One useful coincidence is that the MD5 hash algorithm accepts a set of bytes of any length and turns them into a 128 bit hash. So by running the password through the MD5 hashing algorithm we create our key.</p>
<pre class="brush: c#">
            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
</pre>
<p>The TripleDES algorithm itself turns a byte array into an encrypted  byte array. So we first need to convert our C# message string (which is Unicode encoded) into a byte array  through the System.Text.UTF8Encoding encoder.</p>
<p>The key is used to initialize the TripleDES algorithm. In addition we need to specify that we will only encode something once (CipherMode.ECB) and because its unlikely that our source string fits into a single TripleDES block we need to specify how we want to pad any remaining bytes (PaddingMode.PKCS7).</p>
<pre class="brush: c#">
            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
</pre>
<p>The encrypted byte array is finally converted into a Base64 encoded string for easy storage. The <em>DecryptString</em> function is very similar to the encryption function, except that it turns the Base64 encoded encrypted message back into the original UTF8 string.</p>
<p><strong>Drawbacks to the above method</strong></p>
<p>To keep the code above straightforward we made use of the fact that an MD5 hash is exactly 128 bits in length. The C# TripleDES code accepts three possible key lengths: 64 bit, 128 bit and 192 bit. Only 192 bit keys are truly TripleDES, the 128 bit key length we obtain from the MD5 hash is only sufficient for Double DES. According to Wikipedia, that would make its real key strength only equivalent to 80 bits.</p>
<p><strong>The Source code</strong></p>
<pre class="brush: c#">
using System;
using System.Text;
using System.Security.Cryptography;

namespace EncryptStringSample
{
    class MainClass
    {

        public static string EncryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            // Step 5. Attempt to encrypt the string
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return Convert.ToBase64String(Results);
        }

        public static string DecryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return UTF8.GetString( Results );
        }

        public static void Main(string[] args)
        {
            // The message to encrypt.
            string Msg = &quot;This world is round, not flat, don&#039;t believe them!&quot;;
            string Password = &quot;secret&quot;;

            string EncryptedString = EncryptString(Msg, Password);
            string DecryptedString = DecryptString(EncryptedString, Password);

            Console.WriteLine(&quot;Message: {0}&quot;,Msg);
            Console.WriteLine(&quot;Password: {0}&quot;,Password);
            Console.WriteLine(&quot;Encrypted string: {0}&quot;,EncryptedString);
            Console.WriteLine(&quot;Decrypted string: {0}&quot;,DecryptedString);
        }
    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/encrypting-decrypting-string/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating salted hash passwords in C#</title>
		<link>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/</link>
		<comments>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 04:59:11 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[crc]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[salted]]></category>
		<category><![CDATA[sha-1]]></category>
		<category><![CDATA[sha-256]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=336</guid>
		<description><![CDATA[
Hash values have many uses in computing: for storing password tokens, securing that a file hasn&#8217;t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set &#8212; such as a string &#8212; and turns it into a numeric value of a certain length. [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/12/salt.jpg" alt="" title="Salted Hash Passwords in C#" width="500" height="288" class="alignnone size-full wp-image-340" /><br />
<em>Hash values have many uses in computing: for storing password tokens, securing that a file hasn&#8217;t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set &#8212; such as a string &#8212; and turns it into a numeric value of a certain length.  </p>
<p>This article will go into how to create a hash of your passwords and how salting them makes them more secure.</em></p>
<p><span id="more-336"></span></p>
<p><strong>What is a hash?</strong></p>
<p>A hash function turns &#8220;Hello World&#8221; into &#8220;3964322768&#8243;. And it does that every time you run that same string through the hash function. How it does that depends on the hash algorithm, and so does the &#8220;3964322768&#8243; result. </p>
<p>Different hash function return different results, but given the same data the same function always returns the same result. </p>
<p>Now imagine transferring a block of 2Kb of data across the Internet &#8212; at the end of it you include an extra hash. The receiver can check if the data received was all transferred correctly, if a bit had fallen over the data block would have generated a different hash. </p>
<p><strong>On collisions</strong></p>
<p>In the &#8220;old days&#8221; CRC16 was used to ensure that data was being transmitted correctly over telephone and serial lines. As modems became faster and the data send increased collisions became more frequent, leading to corrupted transfers. The CRC-16 was a 16-bit value, so it could only generate 2^16 = 65535 unique values.  </p>
<p>By making the hash longer the chance that two sets of data share the same hash value (a collision) decreases. It is important to realize that this chance will never reach zero! It is entirely (though often unlikely) possible that your program will have two strings that generate the same hash.</p>
<p><strong>Using hashes to store passwords</strong></p>
<p>Hashes are useful as a one-way method to store passwords. In a typical scenario a user types his password and the system generates the hash and compares this with a hash stored on file. </p>
<p>It is not possible to reverse the password from a hash. Thus if someone gets hold of the password file they cannot reverse the original passwords. </p>
<p><strong>Salting the hash</strong></p>
<p>Hashes however are still open to one of the oldest attacks: the dictionary attack. Your system will likely lock out a users after several failed password attempts. If however through a security breach an attacker obtains your hashed password file (or part thereof) it is possible to apply one of many standard dictionaries against the found hashes:</p>
<ol>
<li>Obtain hashed passwords (through online snooping, hacking)</li>
<li>Use dictionary software which contains pre-computed hash values for common passwords</li>
<li>See if the result matches , if so : password found</li>
<li>The hacker can now login and impersonate the user</li>
</ol>
<p>The dictionary attack can be blunted. By adding a unique salt to each hash the attacker needs to re-calculate the dictionary for each users password, greatly increasing the attack time.</p>
<p><em>A salt is a random set of bytes which are added to the data set before calculating the hash. </em></p>
<ol>
<li>User enters password for the first time
<li>The system adds a salt to the password (for example 4 bytes of random data)
<li>The system generates and stores the hash together with the salt
</ol>
<p>When the user returns for another login the system does the following:</p>
<ol>
<li>The users enters the password
<li>The system looks up the stored hash + salt
<li>The system tries if a new hash of the given password + salt matches the stored hash
<li>If they match the user can login
</ol>
<p><strong>A Salted Hash implementation in C#</strong></p>
<p>The following implementation demonstrates how you can implement a Salted Hash in C#. The class defaults to using SHA256Managed hash algorithm, and a salt size of 32 bits. You can however call the class with any other <em>HashAlgorithm</em> derived class (such as for example: <em>SHA1Managed</em>,<em>SHA256Managed</em>, <em>SHA384Managed</em>, <em>SHA512Managed</em> and <em>MD5CryptoServiceProvider</em>) and specify a salt size of any length.</p>
<p>The <em>SaltedHash</em> class provides two routines that do all the leg work:</p>
<p><em>void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)</em></p>
<p>This routine generates the hash and a random salt for a given set of bytes.</p>
<p><em>bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)</em></p>
<p>This routine checks if the data passed, together with the stored salt will generate the same hash as we had earlier calculated.</p>
<p>For convenience two more functions allow us to work with strings directly instead of byte arrays:</p>
<p><em>public void GetHashAndSaltString(string Data, out string Hash, out string Salt)</em></p>
<p>This routine takes a C# hash string and returns both the Hash and Salt as Base-64 encoded string. </p>
<p><em>public bool VerifyHashString(string Data, string Hash, string Salt)</em></p>
<p>The counterpart to the GetHashAndSaltString function, this routine allows us to use verify whether a string returns the same hash with the given salt. </p>
<pre class="brush: c#">
using System;
using System.Security.Cryptography;
using System.Text;

namespace SaltedHash
{
    class SaltedHash
    {
        HashAlgorithm HashProvider;
        int SalthLength;

        /// &lt;summary&gt;
        /// The constructor takes a HashAlgorithm as a parameter.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;HashAlgorithm&quot;&gt;
        /// A &lt;see cref=&quot;HashAlgorithm&quot;/&gt; HashAlgorihm which is derived from HashAlgorithm. C# provides
        /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider
        /// &lt;/param&gt;

        public SaltedHash(HashAlgorithm HashAlgorithm, int theSaltLength)
        {
            HashProvider = HashAlgorithm;
            SalthLength = theSaltLength;
        }

        /// &lt;summary&gt;
        /// Default constructor which initialises the SaltedHash with the SHA256Managed algorithm
        /// and a Salt of 4 bytes ( or 4*8 = 32 bits)
        /// &lt;/summary&gt;

        public SaltedHash() : this(new SHA256Managed(), 4)
        {
        }

        /// &lt;summary&gt;
        /// The actual hash calculation is shared by both GetHashAndSalt and the VerifyHash functions
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A byte array of the Data to Hash&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;A byte array of the Salt to add to the Hash&lt;/param&gt;
        /// &lt;returns&gt;A byte array with the calculated hash&lt;/returns&gt;

        private byte[] ComputeHash(byte[] Data, byte[] Salt)
        {
            // Allocate memory to store both the Data and Salt together
            byte[] DataAndSalt = new byte[Data.Length + SalthLength];

            // Copy both the data and salt into the new array
            Array.Copy(Data, DataAndSalt, Data.Length);
            Array.Copy(Salt, 0, DataAndSalt, Data.Length, SalthLength);

            // Calculate the hash
            // Compute hash value of our plain text with appended salt.
            return HashProvider.ComputeHash(DataAndSalt);
        }

        /// &lt;summary&gt;
        /// Given a data block this routine returns both a Hash and a Salt
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array containing the data from which to derive the salt
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array which will contain the hash calculated
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array which will contain the salt generated
        /// &lt;/param&gt;

        public void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)
        {
            // Allocate memory for the salt
            Salt = new byte[SalthLength];

            // Strong runtime pseudo-random number generator, on Windows uses CryptAPI
            // on Unix /dev/urandom
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

            // Create a random salt
            random.GetNonZeroBytes(Salt);

            // Compute hash value of our data with the salt.
            Hash = ComputeHash(Data, Salt);
        }

        /// &lt;summary&gt;
        /// The routine provides a wrapper around the GetHashAndSalt function providing conversion
        /// from the required byte arrays to strings. Both the Hash and Salt are returned as Base-64 encoded strings.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; string containing the data to hash
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; base64 encoded string containing the generated hash
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; base64 encoded string containing the generated salt
        /// &lt;/param&gt;

        public void GetHashAndSaltString(string Data, out string Hash, out string Salt)
        {
            byte[] HashOut;
            byte[] SaltOut;

            // Obtain the Hash and Salt for the given string
            GetHashAndSalt(Encoding.UTF8.GetBytes(Data), out HashOut, out SaltOut);

            // Transform the byte[] to Base-64 encoded strings
            Hash = Convert.ToBase64String(HashOut);
            Salt = Convert.ToBase64String(SaltOut);
        }

        /// &lt;summary&gt;
        /// This routine verifies whether the data generates the same hash as we had stored previously
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;The data to verify &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;The hash we had stored previously&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;The salt we had stored previously&lt;/param&gt;
        /// &lt;returns&gt;True on a succesfull match&lt;/returns&gt;

        public bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)
        {
            byte[] NewHash = ComputeHash(Data, Salt);

            //  No easy array comparison in C# -- we do the legwork
            if (NewHash.Length != Hash.Length) return false;

            for (int Lp = 0; Lp &lt; Hash.Length; Lp++ )
                if (!Hash[Lp].Equals(NewHash[Lp]))
                    return false;

            return true;
        }

        /// &lt;summary&gt;
        /// This routine provides a wrapper around VerifyHash converting the strings containing the
        /// data, hash and salt into byte arrays before calling VerifyHash.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A UTF-8 encoded string containing the data to verify&lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;A base-64 encoded string containing the previously stored hash&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;A base-64 encoded string containing the previously stored salt&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        public bool VerifyHashString(string Data, string Hash, string Salt)
        {
            byte[] HashToVerify = Convert.FromBase64String(Hash);
            byte[] SaltToVerify = Convert.FromBase64String(Salt);
            byte[] DataToVerify = Encoding.UTF8.GetBytes(Data);
            return VerifyHash(DataToVerify, HashToVerify, SaltToVerify);
        }

    }

    /// &lt;summary&gt;
    /// This little demo code shows how to encode a users password.
    /// &lt;/summary&gt;

    class SaltedHashDemo
    {
        public static void Main(string[] args)
        {
            // We use the default SHA-256 &amp; 4 byte length
            SaltedHash demo = new SaltedHash();

            // We have a password, which will generate a Hash and Salt
            string Password = &quot;MyGlook234&quot;;
            string Hash;
            string Salt;

            demo.GetHashAndSaltString(Password, out Hash, out Salt);
            Console.WriteLine(&quot;Password = {0} , Hash = {1} , Salt = {2}&quot;, Password, Hash, Salt);

            // Password validation
            //
            // We need to pass both the earlier calculated Hash and Salt (we need to store this somewhere safe between sessions)

            // First check if a wrong password passes
            string WrongPassword = &quot;OopsOops&quot;;
            Console.WriteLine(&quot;Verifying {0} = {1}&quot;, WrongPassword, demo.VerifyHashString(WrongPassword, Hash, Salt));

            // Check if the correct password passes
            Console.WriteLine(&quot;Verifying {0} = {1}&quot;, Password, demo.VerifyHashString(Password, Hash, Salt));

        }
    }

}
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/fernando/">Looking Glass</a></small></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
