Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're going to want to use the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx" rel="noreferrer"><code>System.Security.Cryptography</code></a> namespace; specifically, the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx" rel="noreferrer"><code>MD5</code> class</a> or the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256.aspx" rel="noreferrer"><code>SHA256</code> class</a>. </p> <p>Drawing a bit from the code on <a href="http://bloggingabout.net/blogs/rick/archive/2005/05/18/4118.aspx" rel="noreferrer">this page</a>, and with the knowledge that both classes have the same base class (<a href="http://msdn.microsoft.com/en-us/library/k50cye1b.aspx" rel="noreferrer"><code>HashAlgorithm</code></a>), you could use a function like this:</p> <pre><code>public string ComputeHash(string input, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); } </code></pre> <p>Then you could call it like this (for MD5):</p> <pre><code>string hPassword = ComputeHash(password, new MD5CryptoServiceProvider()); </code></pre> <p>Or for SHA256:</p> <pre><code>string hPassword = ComputeHash(password, new SHA256CryptoServiceProvider()); </code></pre> <hr> <p><strong>Edit: Adding Salt Support</strong><br> As dtb pointed out in the comments, this code would be stronger if it included the ability to add <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)" rel="noreferrer">salt</a>. If you're not familiar with it, salt is a set of random bits that are included as an input to the hashing function, which goes a long way to thwart dictionary attacks against a hashed password (e.g., using a <a href="http://en.wikipedia.org/wiki/Rainbow_table" rel="noreferrer">rainbow table</a>). Here's a modified version of the <code>ComputeHash</code> function that supports salt:</p> <pre><code>public static string ComputeHash(string input, HashAlgorithm algorithm, Byte[] salt) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); // Combine salt and input bytes Byte[] saltedInput = new Byte[salt.Length + inputBytes.Length]; salt.CopyTo(saltedInput, 0); inputBytes.CopyTo(saltedInput, salt.Length); Byte[] hashedBytes = algorithm.ComputeHash(saltedInput); return BitConverter.ToString(hashedBytes); } </code></pre> <p>Hope this has been helpful!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload