Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Hash Functions in .NET


Hash functions are an important security tool in .NET and ASP.NET applications. Over the Web any input is potentially evil and must be carefully checked to be safe. For this reason, you should avoid sending out critical information as clear text. Encryption is one possible answer to this issue. Depending on the context, encryption can be applied to the protocol level (HTTPS) or to individual pieces of data, care of the programmer. Encryption does a good job of protecting data, but requires a key. The burden of protecting the key is placed on you. Once the key is known, the wall built around your data disappears. In addition, encryption does have a relevant computational cost. Yet, in some cases you can't just do without encryption-for example, to authenticate a user and be sure about his or her identity you need encryption (typically, certificates).

There are other situations in which integrity and confidentiality of data can be obtained without encryption. Imagine you have to call a library subject to authentication rules. Instead of sending out credentials as clear text, you can calculate a hash value and send it over the wire. On the server, you can compare the hash against a set of stored hashes, one for each authorized user. If a match is found, you have successfully verified the credentials, have an identity to work with, and can proceed with tasks. If not, the credentials are invalid and you just reject the call.

This pattern is commonly used to verify passwords. On the server, you keep a hashed version of the user's password. From the client, you receive the password as clear text; hash it on the server and verify the obtained value against stored hashes. In this way, at least you avoid storing passwords as clear text, which solves a potential big privacy issue in case your database is hacked. Needless to say, there are other issues related to storing passwords, but they go beyond the scope of this article.

In .NET Framework, hash functions only work with arrays of bytes. If you want to hash a string (for example, a password or the contents of a file), you have to extract the contents as bytes. Here's how to do it:


UnicodeEncoding ue = new UnicodeEncoding();
byte[] bytes = ue.GetBytes(text);
SHA1Managed sha1 = new SHA1Managed();
byte[] hashValue = sha1.ComputeHash(bytes);

First and foremost, you get a byte array out of the input data. This process is known as encoding, that is transforming a set of Unicode characters into a sequence of bytes. In .NET, there are various encoding classes to choose from based on the input character set. They are UTF8, UTF7 and UTF16 or just Unicode.

Once you hold an instance of the correct encoding class, you pass the GetBytes method the text and get its bytes. Next, you get an instance of the hash generator and call its ComputeHash method. To compare two hash values, you simply iterate and compare all of contained bytes.


bool same = true;
int i=0;
while(i<providedHashValue.Length && same)
{
         if (providedHashValue[i] != hashValue[i])
              same = false;
         i++;
}

SHA1 is one of the most popular hash algorithms and is implemented by the SHA1Managed class in the .NET Framework. However, be aware that holes have been found in the algorithm, as well as in other equally popular hash algorithms such as MD5. Today, SHA512 is deemed to be the most reliable and safe hashing algorithm. In .NET Framework, it is implemented by the SHA512Managed class. The key benefit of hash values is that they provide a unique, fixed-length, deterministic representation of a block of data.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.