在 .NET Core 中使用 SHA-1

Using SHA-1 in .NET Core

在 dotnet core 中散列字符串时得到奇怪的结果 我发现了这个类似的问题: 并找到了如何在 .net core

convert a byte array to string

这是我的代码:

private static string CalculateSha1(string text)
{
    var enc = Encoding.GetEncoding(65001); // utf-8 code page
    byte[] buffer = enc.GetBytes(text);

    var sha1 = System.Security.Cryptography.SHA1.Create();

    var hash = sha1.ComputeHash(buffer);

    return enc.GetString(hash);
}

这是我的测试:

string test = "broodjepoep"; // forgive me

string shouldBe = "b2bc870e4ddf0e15486effd19026def2c8a54753"; // according to http://www.sha1-online.com/

string wouldBe = CalculateSha1(test);

System.Diagnostics.Debug.Assert(shouldBe.Equals(wouldBe));

输出:

���M�Hn�ѐ&��ȥGS

我安装了 nuget 包 System.Security.Cryptography.Algorithms (v 4.3.0)

还尝试使用 GetEncoding(0) 获取系统默认编码。也没有用。

我不确定 'SHA-1 Online' 如何表示您的散列,但由于它是散列,它可以包含无法在 (UTF8) 字符串中表示的字符。我认为你最好使用 Convert.ToBase64String() 来轻松地表示字符串中的字节数组哈希:

var hashString = Convert.ToBase64String(hash);

要将其转换回字节数组,请使用 Convert.FromBase64String():

var bytes =  Convert.FromBase64String(hashString);

另见:Converting a md5 hash byte array to a string。这表明有多种方法可以在字符串中表示散列。例如,hash.ToString("X") 将使用十六进制表示。

感谢 broodjepoep,顺便说一句。 :-)

目前解决的问题:

var enc = Encoding.GetEncoding(0);

byte[] buffer = enc.GetBytes(text);
var sha1 = SHA1.Create();
var hash = BitConverter.ToString(sha1.ComputeHash(buffer)).Replace("-","");
return hash;