How to create a SHA1 hash in C#

Here is short code snippet to create a SHA1 hash in C#. The only difficult is to convert from string to byte array and back again. So i have to method, one accept the byte array direct and returns a byte array, the second method handles the convert from string to byte array and back again. Don’t forget to add the required 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.