.NET String Hashing: The Hidden Knot
Published: 10 Apr 2007
This article explains why string-hash outputs in .NET 1.1 and .NET 2.0 are different and provides a workaround to solve this problem.
by Joseph Chahine
Average Rating: 
Views (Total / Last 10 Days): 26472/ 79


As defined by Wikipedia, "a hash function is a reproducible method of turning some kind of data into a (relatively) small number that may serve as a digital 'fingerprint' of the data. The algorithm 'chops and mixes' (substitutes or transposes) the data to create such fingerprints, called hash values. These are commonly as indices into hash tables or hash files. Cryptographic hash functions are used for various purposes in information security applications."

In short, hashing is a way to protect data. It is simple, fast, and relatively secure.


In .NET 1.1, a sample hashing function can be as follows:

Listing 1

Imports System.Text
Imports System.Security.Cryptography
Function ComputeHashValue(ByVal Data As StringAs String
  Dim HashAlgorithm As SHA1 = SHA1.Create
  Dim HashValue() As Byte =
  Return Encoding.ASCII.GetString(HashValue)
End Function

Lately, I was migrating an application from .NET 1.1 to .NET 2.0. The login passwords were already hashed and stored in a Microsoft SQL 2000 database in ntext format. On user login, the application hashes the provided user password and compares it to the stored password hash in the database. All logins failed in .NET 2.0 and I had to find out what was going wrong. I spent some time working and luckily I came to a solution.


The ComputeHash function's return value is an array of bytes. In .NET 1.1, the most significant bit of each byte is disregarded when the Encoding.ASCII.GetString function is called. But this is not true in .NET 2.0. So, to simulate the behavior of Encoding.ASCII.GetString as it worked in .NET 1.1, I had to get rid of the most significant bit manually in the .NET 2.0 code by ANDing every byte with the binary value of 01111111 (127 in decimal).

The code becomes as follows:

Listing 2

Function ComputeHashValue(ByVal Data As StringAs String
  Dim HashAlgorithm As SHA1 = SHA1.Create
  Dim HashValue() As Byte =
  REM: Looping over the array and ANDing each byte with 0111111
  For i As Integer = 0 To HashValue.Length - 1
    HashValue(i) = HashValue(i) And Convert.ToByte(127)
  Return Encoding.ASCII.GetString(HashValue)
End Function

I do not claim in this article that string-hashing passwords are a good way to protect your data. But for those who faced the same problem that I did, I hope this article helps.

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2020 ASPAlliance.com  |  Page Processed at 2020-06-04 6:50:15 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search