SHA1 hash in c#

Hi, let’s try to get the SHA1 hash from a string in .NET c#.

SHA1 hash is often used to “encrypt” passwords, but notice it’s not the way you’re going to be totally secured, there are many other ways to store way more secure passwords, for any reason you’re trying to calculate a string’s sha1 hash, this is the right place, let’s do it the easy way.

I’m actually using Microsoft Visual Studio 2010 Ultimate with .NET Framework V 4.0 but I guess it will work in any other version.

First you need to create a “Windows Forms Application” project  (File > New > Project > Windows Forms Application). Give it the name you want and hit ok.



Now we’re ready to start, drag a “Button” and a “TextBox” from the left side and drop them into the “Form” like this:



Set the TextBox’s name property to “txtString” or whatever you want.




Now set the button’s text to something like: “Hash”. Then double click the Button, you will see some code like:

       private void Button1_Click(object sender, EventArgs e)
              {


              }

There we will place our “really hard” code inside those curly braces. Meanwhile, go to the top and place a new “Using” directive:

       using System.Security.Cryptography;

That will allow us to achieve the sha1 hash and some others. Now going back to our “Click” event, let’s get the text that has been typed into the TextBox and store it inside “myString” variable (remember you can name it what you want):

      string myString = txtPass.Text;
      //save our text
      byte[] otherString = Encoding.Unicode.GetBytes(myString);
      SHA1 string2 = SHA1.Create();
      //instantiate sha1
      otherString = cadena2.ComputeHash(otherString);
      //get the hash
      string base64 = Convert.ToBase64String(otherString);
      //convert it to “base64”
      txtString.Text = base64;

Then we’ve set the “txtString” text to the hash so we can see it when it’s done. Now press “F5” and see the “magic”.



That’s all, thank you for reading.

Post a Comment