为什么这种计算 SHA-256 哈希值的方法总是返回 44 个字符的字符串?
首先,请忽略没有盐。我去掉了盐以尽可能简化事情。
以下始终输出 44 个字符的字符串:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApplication1
{
class Program
{
private static HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
static void Main(string[] args)
{
string blah = ComputeHash("PasswordLongBlah646468468Robble");
Console.WriteLine(blah.Length);
Console.WriteLine(blah);
}
private static string ComputeHash(string input)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = hashAlgorithm.ComputeHash(inputBytes);
return Convert.ToBase64String(hashedBytes);
}
}
}
此应用程序的输出:
44
K5NtMqCN7IuYjzccr1bAdajtfiyKD2xL15Eyg5oFCOc=
如果我没记错的话,输出应该是:
64
2b936d32a08dec8b988f371caf56c075a8ed7e2c8a0f6c4b979132839a0508e7
这是怎么回事?
First off, please ignore that there is no salt. I removed the salt in order to simplify things as much as possible.
The following always outputs a 44 character string:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApplication1
{
class Program
{
private static HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
static void Main(string[] args)
{
string blah = ComputeHash("PasswordLongBlah646468468Robble");
Console.WriteLine(blah.Length);
Console.WriteLine(blah);
}
private static string ComputeHash(string input)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = hashAlgorithm.ComputeHash(inputBytes);
return Convert.ToBase64String(hashedBytes);
}
}
}
Output of this application:
44
K5NtMqCN7IuYjzccr1bAdajtfiyKD2xL15Eyg5oFCOc=
If I am not mistaken, the output should be:
64
2b936d32a08dec8b988f371caf56c075a8ed7e2c8a0f6c4b979132839a0508e7
What is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看到哪里写着
Convert.ToBase64String(hashedBytes)
了吗?它不会为您提供十六进制字符串(每个字符 4 位) - 它采用 64 基数(每个字符 6 位)。See where it says
Convert.ToBase64String(hashedBytes)
? It's not giving you a hexadecimal string (4 bits per character) - it's in base 64 (6 bits per character).您正在将其转换为 Base64 字符串...
您可能想改用它:
编辑:这又是上面发布的 BitConverter.ToString() 的穷人实现。为什么在搜索“字符串到十六进制”等常见功能时,互联网上充斥着现有框架功能的重新实现? ;-(
You're converting it to a Base64 string...
You might want to use this instead:
Edit: which once again is a poor man's implementation of the BitConverter.ToString() posted above. Why is the internet filled with reimplementations of existing framework functionality when searching for common functionality like "string to hex"? ;-(