SHA256 给出 44 长度输出而不是 64 长度 [英] SHA256 giving 44 length output instead 64 length
本文介绍了SHA256 给出 44 长度输出而不是 64 长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码来执行 SHA256.
I am using the following code to perform SHA256.
public static string GenerateSaltedHash(string plainTextString, string saltString)
{
byte[] salt = Encoding.UTF8.GetBytes(saltString);
byte[] plainText = Encoding.UTF8.GetBytes(plainTextString);
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextWithSaltBytes =
new byte[plainText.Length + salt.Length];
for (int i = 0; i < plainText.Length; i++)
{
plainTextWithSaltBytes[i] = plainText[i];
}
for (int i = 0; i < salt.Length; i++)
{
plainTextWithSaltBytes[plainText.Length + i] = salt[i];
}
byte[] bytes = algorithm.ComputeHash(plainTextWithSaltBytes);
return Convert.ToBase64String(algorithm.ComputeHash(plainTextWithSaltBytes));
}
当我使用 SHA256 时,我希望结果的长度为 64.但我得到了 44.
As I am using SHA256, I expect the length of the result to be 64. But I am getting 44.
这是什么问题?较短的长度输出会影响安全吗?
What is the issue? Will the shorter length output impact security?
推荐答案
Base-64 是每个字符 6 位 (2^6 = 64).
Base-64 is 6 bits per character (2^6 = 64).
256 bits / 6 bits per char = 42.6666 char
显然由于填充而最终变成了 44(您会在输出的末尾看到 1 或 2 个 =
).
And that has obviously ended up as 44 due to padding (you will see one or 2 =
on the end of the output).
您必须期待 base-16(也称为十六进制),即每个字符 4 位(2^4 = 16).
You must be expecting base-16 (AKA hexadecimal) which is 4 bits per character (2^4 = 16).
256 bits / 4 bits per char = 64 char
对于十六进制使用这个:
return BitConverter.ToString(bytes).Replace("-", string.Empty);
这篇关于SHA256 给出 44 长度输出而不是 64 长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文