在 C# 中使用 SHA1 算法进行散列 [英] Hashing with SHA1 Algorithm in C#
本文介绍了在 C# 中使用 SHA1 算法进行散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 SHA1
算法对给定的 byte[]
数组进行哈希处理,并使用 SHA1Managed
.byte[]
哈希将来自单元测试.
预期的哈希值为 0d71ee4472658cd5874c5578410a9d8611fc9aef
(区分大小写).
I want to hash given byte[]
array with using SHA1
Algorithm with the use of SHA1Managed
.
The byte[]
hash will come from unit test.
Expected hash is 0d71ee4472658cd5874c5578410a9d8611fc9aef
(case sensitive).
我怎样才能做到这一点?
How can I achieve this?
public string Hash(byte [] temp)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
}
}
推荐答案
对于那些想要哈希的标准"文本格式的人,您可以使用以下内容:
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();
}
}
这将产生一个类似于 0C2E99D0949684278C30B9369B82638E1CEAD415
的哈希值.
This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415
.
或者代码高尔夫版本:
static string Hash(string input)
{
var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
return string.Concat(hash.Select(b => b.ToString("x2")));
}
这篇关于在 C# 中使用 SHA1 算法进行散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文