Skip to content

Instantly share code, notes, and snippets.

@fernandofig
Forked from jchandra74/SHA1Util.cs
Last active April 3, 2019 17:42
Show Gist options
  • Save fernandofig/c16b7085415d9cfa9fecf26ac3fdc00f to your computer and use it in GitHub Desktop.
Save fernandofig/c16b7085415d9cfa9fecf26ac3fdc00f to your computer and use it in GitHub Desktop.
SHA1 Hash for Unicode string
//Forked from kristopherjohnson/SHA1Util.cs gist
using System.Security.Cryptography;
using System.Text;
namespace Snippets
{
public static class SHA1Util
{
/// <summary>
/// Compute hash for string encoded as UTF8, return as base64 encoded string
/// </summary>
/// <param name="s">String to be hashed</param>
/// <returns>Base64 encoded string</returns>
public static string HashAsBase64(string s)
{
byte[] hashBytes = GetSHA1HashBytes(s);
return System.Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Compute hash for string encoded as UTF8, return as hexadecimal string sequence
/// </summary>
/// <param name="s">String to be hashed</param>
/// <returns>40-character hex string</returns>
public static string HashAsHex(string s)
{
byte[] hashBytes = GetSHA1HashBytes(s);
var sb = new StringBuilder();
foreach (byte b in hashBytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
private static byte[] GetSHA1HashBytes(string s) {
return GetSHA1HashBytes(s, Encoding.UTF8);
}
private static byte[] GetSHA1HashBytes(string s, Encoding e)
{
byte[] bytes = e.GetBytes(s);
var sha1 = SHA1.Create();
return sha1.ComputeHash(bytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment