How to create your own C# Hashing Class Library

String Operations, Windows Forms

In this article I’m going to show you how to create your very own class library – also know as a dll file. We’ll be building a class containing a static text hashing method, which we’ll then call from a separate application. After reading this article you will know exactly how to create a dll file with your own methods and how to use it within other projects, and that is extremely important for any developer to know.

Creating the Class Library

First of all we must start off by creating a Class Library project from within Visual Studio – in this case we shall name it HashLibrary. Now the namespace for our dll will automatically be set to HashLibrary as well.

Next create a class and call it Hasher. We have the option of either creating a normal class or a static class. A static class is one which does not need to be instantiated. Therefore whoever consumes the class can do so by calling its methods directly, without having to create an instance of it. This is ideal for our situation because we do not need to store any data within the Hasher class – all we’ll have is a method which returns a hash value.

So make the class static by adding the static keyword before the class name as shown below:

using System;
using System.Text;

namespace HashLibrary
{
    public static class Hasher
    {
    }
}

Since the class is static, we don’t even need a constructor, as can be seen in the code. All we have is an empty class which does absolutely nothing at the moment.

So let’s make it do something. Let’s add a string hashing method as shown below.

using System;
using System.Text;
using System.Security.Cryptography;

namespace HashLibrary
{
    public static class Hasher
    {
        /// <summary>
        /// This method hashes the given text with 
        /// the SHA1CryptoServiceProvider.
        /// </summary>
        /// <param name="text">Text to hash</param>
        /// <returns>Hashed Value</returns>
        public static string HashString(string text)
        {
            // Create an instance of the SHA1 provider
            SHA1 sha = new SHA1CryptoServiceProvider();
            
            // Compute the hash 
            byte[] hashedData = sha.ComputeHash(Encoding.Unicode.GetBytes(text));

            StringBuilder stringBuilder = new StringBuilder();

            foreach (byte b in hashedData)
            {
                // Convert each byte to Hex
                stringBuilder.Append(String.Format("{0,2:X2}", b));
            }
            
            // Return the hashed value
            return stringBuilder.ToString();
        }
    }
}

Our new method HashString accepts a string parameter which is the text to be hashed. We also had to add the namespace System.Security.Cryptography because of the SHA1 and SHA1CryptoServiceProvider classes. These are the classes which actually compute the hash.

The hash is returned as a byte array so we are iterating each byte and appending it to the StringBuilder as a hex value. Finally we are returning the hashed value which is a hex representation of the binary hash.

Now if we compile the code, we end up with a file called HashLibrary.dll.

You have just created your own dll which can be used within any .NET project over and over again. And thats the beauty of a dll – it can be re-used without duplicating code, and more importantly, it can be shared between different applications.

Now let me show you how to call the HashString method in our dll.

Consuming a DLL

Create a new Windows Forms Application project and add a reference to the HashLibrary.dll we just created. Also add a button and two textboxes to the form. The first text box (txtToHash) will be for adding the text to hash, and the second textbox (txtHashed) will display the hashed text. The button will be used to call our dll and get the hashed text. Also remember to add the HashLibrary namespace to the project since we will need it to access the HashString method in our dll.

The following code shows how to access the HashString method in the dll:

private void btnHash_Click(object sender, EventArgs e)
{
    txtHashed.Text = Hasher.HashString(txtToHash.Text.Trim());
}

If you run the application you should end up with something similar to this:

And that’s it. You now know how to create your own dll and how to consume it. You can improve your dll further by adding more different static hashing methods and maybe file hashing methods as well.

I hope you enjoyed this article. Stay tuned for more soon.

Dave

8 comments… add one
  • Steve Link Reply

    Nice simple example showing how to create a dll and use it, fantastic thanks!

  • Hue Link Reply

    Dave,
    Thank you for this tutorial code. I am using Visual Studio Express 2015 and came across couple issue. I created the database and added 2 users. Point the ‘web.config’ to the correct database.:
    1) When compile, I have error on line 6 on the ‘web.config’ file. 6:

    2. If I take it out it works fine but it seems like it is not reading from the database with the following error.
    Your login attempt was not successful. Please try again.

    Can you point me in the right direction?

    thanks
    Hue

  • Hue Link Reply

    Sorry I meant to post on this other tutorial link page.
    http://www.daveoncsharp.com/2009/08/creating-an-asp-net-login-screen/

  • Kurt J Link Reply

    Hi!
    I had great expectations, but as a rookie, I always gets problem when trying codes from different tutorials, also this one. I am using Visual Studio 13.
    The very first code I got differs from your example –
    a) have #pragma once on the line after // HashLibrary.h
    b) have public ref class Hasher, and when deleting ref and inserting static instead, VS says error – IntelliSense expect an identifier.
    Next part of code:
    VS does not accept using System.Text nor System.Security.Cryptography.
    Looking forward to hear advices from you.
    Kurt J

    • I think you might be trying to add C# code to a C++ project, which won’t work since they’re different languages.

  • Kurt J Link Reply

    Adding the source code below (copied and pasted from tutorial). Public in public static class Hasher is underlined and shows error: Expected a declaration.
    Code:
    // Hasher lib dll
    #pragma once
    namespace HashLibrary
    {
    public static class Hasher
    {
    ///
    /// This method hashes the given text with
    /// the SHA1CryptoServiceProvider.
    ///
    /// Text to hash
    /// Hashed Value
    public static string HashString(string text)
    {
    // Create an instance of the SHA1 provider
    SHA1 sha = new SHA1CryptoServiceProvider();

    // Compute the hash
    byte[] hashedData = sha.ComputeHash(Encoding.Unicode.GetBytes(text));

    StringBuilder stringBuilder = new StringBuilder();

    foreach(byte b in hashedData)
    {
    // Convert each byte to Hex
    stringBuilder.Append(String.Format(“{0,2:X2}”, b));
    }

    // Return the hashed value
    return stringBuilder.ToString();
    }
    }
    }

Leave a Comment