Custom Search
Logiclabz
  • Home
  • C#
  • Function to Encrypt String in C# .Net using SHA1 Algorithm

Function to Encrypt String in C# .Net using SHA1 Algorithm

SHA stands for Secure Hash Algorithm. This hash algorithm are applied to encrpt the string and store in un-readable format. SHA-1 is the best established of the existing SHA hash functions, and is employed in several widely used security applications and protocols. SHA-1 is implemented in .Net using System.Security.Cryptography.SHA1 Namespace.

First the given string is converted to byte array using ASCIIEncoding class in System.Text Namespace. GetBytes method on ASCIIEncoding class converts given string to byte[]

ComputeHash method in SHA1 class create a hash with SHA-1 Algorithm. Resultant Hashed byte[] is convert to string using Convert.ToBase64String Method

Hashed on encrpted string cannot be decryted (for security reasons). Raw string can be compared with hashed string only by hashing the raw string using the same hash function.

public static string HashCode(string str)
{
    string rethash = "";
    try
    {

	      System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
	       System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
	       byte[] combined = encoder.GetBytes(str);
	       hash.ComputeHash(combined);
	       rethash = Convert.ToBase64String(hash.Hash);
    }
    catch (Exception ex)
    {
	       string strerr = "Error in HashCode : " + ex.Message;
    }
    return rethash;
}


Comments

  • Valentino Vranken says:
    Oct 02, 09

    I needed to calculate a hash from an incoming field in my SSIS package (SQL Server Integration Services) and this is exactly what I needed, thanks! It works great in a Script Component transformation, and the corresponding data type to store the byte array in a field the data flow is DT_BYTES. Thought I'd mention it in case someone ens up here with the same purpose as I did :-)

  • qwerty says:
    Feb 05, 10

    SHA1 is a hash, not an encryption, you cannot encrypt a string using SHA1, only hash it encryptions store the data they protect, and that data can be accessed through a decryption algorithm SHA1 and other hashes do not store the original text, and therefore cannot be decrypted

  • David says:
    Mar 04, 10

    you may want to look at this online sha1 encrypter pretty cool to check how a sha1 message looks like David


Leave a reply


Do you like this post?