How to create a SHA1 hash in C#

This is a brief piece of C# code that generates a SHA1 hash. Converting a string to a byte array and back again is the only challenging part.

I therefore need two methods:

  • the first takes the byte array directly and returns a byte array,
  • the second converts the string to byte array and back again.

Remember to include the necessary using:

  using System.Security.Cryptography;

And here is the code to create the SHA1 in C#:

        public static string GetSha1(string text)
        {
            if (text == null)
            {
                return string.Empty;
            }

            byte[] message = System.Text.Encoding.ASCII.GetBytes(text);
            byte[] hashValue = GetSha1(message);

            string hashString = string.Empty;
            foreach (byte x in hashValue)
            {
                hashString += string.Format("{0:x2}", x);
            }

            return hashString;

        }

        private static byte[] GetSha1(byte[] message)
        {
            SHA1Managed hashString = new SHA1Managed();
            return hashString.ComputeHash(message);
        }

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.