Skip to content

Instantly share code, notes, and snippets.

@jchandra74
Forked from kristopherjohnson/SHA1Util.cs
Last active April 3, 2019 17:20
Show Gist options
  • Save jchandra74/f96bbf33cb1a68539626 to your computer and use it in GitHub Desktop.
Save jchandra74/f96bbf33cb1a68539626 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
/// </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>
/// Compute hash for Unicode encoded string.
/// This is the exact same Hash that the following SQL Server SHA1 Hash will produce...
/// SET @hash = HASHBYTES('SHA1', @dataJson);
/// SET @hash64str = cast('' as xml).value('xs:hexBinary(sql:variable("@hash"))', 'varchar(max)');
/// just in case you need to recreate the hash in C#
/// </summary>
/// <param name="s">String to be hashed</param>
/// <returns>40-character hex string</returns>
public static string SHA1HashStringForUnicodeString(string s)
{
byte[] bytes = Encoding.Unicode.GetBytes(s);
var sha1 = SHA1.Create();
byte[] hashBytes = sha1.ComputeHash(bytes);
return HexStringFromBytes(hashBytes).ToUpperInvariant();
}
/// <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();
}
}
}
@jchandra74
Copy link
Author

Added a method to create SHA1 Hash from Unicode string. Needed a C# equivalent of SQL Server SHA1 hash on nvarchar field.

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