在C#中使用SHA1散列算法 [英] Hashing with SHA1 Algorithm in C#
问题描述
我要哈希给予字节[]
阵列使用 SHA1
算法使用<$ C $的C> SHA1Managed 。
中的字节[]
哈希将来自单元测试。
预计哈希 0d71ee4472658cd5874c5578410a9d8611fc9aef
(区分大小写)。
我怎样才能做到这一点?
公共字符串哈希(字节[] TEMP)
{
使用(SHA1Managed SHA1 =新SHA1Managed ())
{
}
}
对于那些谁希望有一个哈希的标准的文本格式,可以使用类似以下内容:
静态字符串哈希(字符串输入)
{
使用(SHA1Managed SHA1 =新SHA1Managed())
{
无功散= sha1.ComputeHash(编码.UTF8.GetBytes(输入));
变种某人=新的StringBuilder(hash.Length * 2);
的foreach(哈希字节B)
{
//可以X2,如果你想小写
sb.Append(b.ToString(X2 ));
}
返回sb.ToString();
}
}
这将产生如哈希 0C2E99D0949684278C30B9369B82638E1CEAD415
或者一个代码golfed版本:
静态字符串哈希(字符串输入)
{
VAR哈希=(新SHA1Managed())ComputeHash(Encoding.UTF8.GetBytes(输入))。
返回的string.join(,hash.Select(二= GT; b.ToString(×2))ToArray的());
}
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();
}
}
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.Join("", hash.Select(b => b.ToString("x2")).ToArray());
}
这篇关于在C#中使用SHA1散列算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!