在.NET Core中使用SHA-1

JP *_*ons 1 c# cryptography sha1 .net-core asp.net-core

我在dotnet核心中散列字符串时得到奇怪的结果我发现了类似的问题:用ASP.NET Core计算SHA1 并找到了如何在.net核心中将字节数组转换为字符串

这是我的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

这是我的考验:

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));
Run Code Online (Sandbox Code Playgroud)

输出:

MHnѐ&ȥGS

在此输入图像描述

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

还试图GetEncoding(0)获得sys默认编码.也没工作.

小智 7

到目前为止问题的解决方案:

var enc = Encoding.GetEncoding(0);

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


Hen*_*ema 6

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

var hashString = Convert.ToBase64String(hash);
Run Code Online (Sandbox Code Playgroud)

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

var bytes =  Convert.FromBase64String(hashString);
Run Code Online (Sandbox Code Playgroud)

另请参阅:将md5散列字节数组转换为字符串.这表明有多种方法可以表示字符串中的哈希值.例如,hash.ToString("X")将使用十六进制表示.

broodjepoep顺便说一句,感谢荣誉.:-)