在.NET Core中使用SHA

编程入门 行业动态 更新时间:2024-10-28 01:17:33
本文介绍了在.NET Core中使用SHA-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在dotnet核心中对字符串进行哈希处理时,我得到了奇怪的结果,我发现了类似的问题:

我已经安装了nuget软件包 System.Security.Cryptography.Algorithms (v 4.3.0)

也尝试使用 GetEncoding(0)获取sys默认编码。也不起作用。

解决方案

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

var hashString = Convert.ToBase64String(hash);

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

var bytes = Convert.FromBase64String(hashString);

另请参阅:将md5哈希字节数组转换为字符串。其中显示了表示字符串中哈希的多种方法。例如, hash.ToString( X)将使用十六进制表示形式。

针对 broodjepoep 。 :-)

I get strange results when hashing a string in dotnet core I have found this similar question: Computing SHA1 with ASP.NET Core and have found how to convert a byte array to string in core

this is my code:

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); }

and this is my test:

string test = "broodjepoep"; // forgive me string shouldBe = "b2bc870e4ddf0e15486effd19026def2c8a54753"; // according to www.sha1-online/ string wouldBe = CalculateSha1(test); System.Diagnostics.Debug.Assert(shouldBe.Equals(wouldBe));

output:

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

I have the nuget package System.Security.Cryptography.Algorithms installed (v 4.3.0)

Also tried with GetEncoding(0) to get the sys default coding. Also did not work.

解决方案

I'm not sure how 'SHA-1 Online' represents your hash, buts since it's a hash, it can contain characters that can't be represented in a (UTF8) string. I think you're better off using Convert.ToBase64String() to easily represent the byte-array hash in a string:

var hashString = Convert.ToBase64String(hash);

To convert it back to a byte-array, use Convert.FromBase64String():

var bytes = Convert.FromBase64String(hashString);

Also see: Converting a md5 hash byte array to a string. Which shows there a multiple ways to represent hash in a string. For example, hash.ToString("X") will use a hexadecimal representation.

Kudos for broodjepoep, by the way. :-)

更多推荐

在.NET Core中使用SHA

本文发布于:2023-11-04 11:24:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557798.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   Core   SHA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!