Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active October 1, 2020 22:18
  • Star 27 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kristopherjohnson/3021045 to your computer and use it in GitHub Desktop.
.NET/C# Generate SHA1 hex string for a string encoded as UTF8
using System.Security.Cryptography;
using System.Text;
namespace Snippets
{
public static class SHA1Util
{
/// <summary>
/// Compute hash for string encoded as UTF8
/// </summary>
/// <param name="s">String to be hashed</param>
/// <returns>40-character hex string</returns>
public static string SHA1HashStringForUTF8String(string s)
{
byte[] bytes = Encoding.UTF8.GetBytes(s);
var sha1 = SHA1.Create();
byte[] hashBytes = sha1.ComputeHash(bytes);
return HexStringFromBytes(hashBytes);
}
/// <summary>
/// Convert an array of bytes to a string of hex digits
/// </summary>
/// <param name="bytes">array of bytes</param>
/// <returns>String of hex digits</returns>
public static string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
}
}
@knocte
Copy link

knocte commented Jan 7, 2014

There's a typo: pubilc->public, but apart from that, thanks for this useful snippet!

@kristopherjohnson
Copy link
Author

Fixed the typo. Thanks!

@stevehansen
Copy link

SHA1 implements IDisposable so you should use an using

            using (var sha1 = SHA1.Create())
            {
                byte[] hashBytes = sha1.ComputeHash(bytes);

                return HexStringFromBytes(hashBytes);
            }

@ivandrofly
Copy link

If it's going to be called multiple times, it would be more efficient if you pull out the string builder to a static readonly field

@logo123
Copy link

logo123 commented Sep 23, 2017

i want that encrypted string in 16 character

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment