-
-
Save fernandofig/c16b7085415d9cfa9fecf26ac3fdc00f to your computer and use it in GitHub Desktop.
SHA1 Hash for Unicode string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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