C # 中的 SHA1散列算法

我想散列给定的 byte[]数组与使用 SHA1算法与使用 SHA1Managed
byte[]散列将来自单元测试。
期望的散列是 0d71ee4472658cd5874c5578410a9d8611fc9aef(区分大小写)。

我怎么才能做到呢?

public string Hash(byte [] temp)
{
using (SHA1Managed sha1 = new SHA1Managed())
{


}
}
177058 次浏览

You can "compute the value for the specified byte array" using ComputeHash:

var hash = sha1.ComputeHash(temp);

If you want to analyse the result in string representation, then you will need to format the bytes using the {0:X2} format specifier.

public string Hash(byte [] temp)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(temp);
return Convert.ToBase64String(hash);
}
}

EDIT:

You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);

or

return System.Text.Encoding.Unicode.GetString(hash);

For those who want a "standard" text formatting of the hash, you can use something like the following:

static string Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);


foreach (byte b in hash)
{
// can be "x2" if you want lowercase
sb.Append(b.ToString("X2"));
}


return sb.ToString();
}
}

This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415.

Or for a code golfed version:

static string Hash(string input)
{
var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
return string.Concat(hash.Select(b => b.ToString("x2")));
}

For .Net 5 and above, the built-in Convert.ToHexString gives a nice solution with no compromises:

static string Hash(string input)
{
using var sha1 = SHA1.Create();
return Convert.ToHexString(sha1.ComputeHash(Encoding.UTF8.GetBytes(input)));
}

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
byte[] data = UTF8Encoding.UTF8.GetBytes (str);
data = data.Sha1Hash ();
return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
using (SHA1Managed sha1 = new SHA1Managed ()) {
return sha1.ComputeHash (data);
}

This is what I went with. For those of you who want to optimize, check out https://stackoverflow.com/a/624379/991863.

    public static string Hash(string stringToHash)
{
using (var sha1 = new SHA1Managed())
{
return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)));
}
}

Fastest way is this :

    public static string GetHash(string input)
{
return string.Join("", (new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("X2")).ToArray());
}

For Small character output use x2 in replace of of X2