Building a Simple C# Hashing Utility

One of the most interesting aspects of Cryptography is the ability to generate unique hash values from strings or files.

Wikipedia Defines Cryptographic as follows:

A cryptographic hash function is a hash function that is suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size and is a one-way function, that is, a function which is practically infeasible to invert

https://en.wikipedia.org/wiki/Cryptographic_hash_function

The most common use of hashes is to store hashed (vs plain text) values of passwords in databases.

Another use case of hashes is to detect changes to files. A few years back we built a script runner that would only run new or changed files from a given scripts folder. The basic algorithm for this was:

1) Read all file names from a folder.

2) Look for for a file same name with a .HASH extension.
    If .HASH file was missing:  
      a) Run the script file
      b) Create a new file with a .HASH extension. 
      c) Hash the script file and store the result in 
         the .HASH file

3) If the .HASH file already existed:
    a) Generate a hash value of the script file 
    b) Compare value the hash value stored in the .HASH file. 
    c) If they were the same we ignore the file. 
    d) If they were different Run the script, 
       re-generate the hash and store the results 
       in the .HASH file. 

The core of these processed is a little nugget of code I built up a few years back .I thought it would be good to share my hashing function with the world. The following code generates a SHA512 has for a given string. The code then takes the generated byte array converts it to a string:

public static string GenerateHash(string stringToHash)
{
  var crypt = new SHA512Managed();
  var hash = new StringBuilder();
  var crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(stringToHash), 0,
    Encoding.UTF8.GetByteCount(stringToHash));

    foreach (var bit in crypto)
    {
      hash.Append(bit.ToString("x2"));
    }

    return hash.ToString();
}

I built a little command line utility that implements this function and can generate a hash for a passed in string or file. You can find this utility on Github:

https://github.com/rjpaddock/HashUtility.git

Description of SHA Hashing: https://en.wikipedia.org/wiki/Secure_Hash_Algorithms

Leave a Reply

Your email address will not be published. Required fields are marked *