SHA256 giving 44 length output instead 64 length

China☆狼群 提交于 2019-12-10 13:38:13

问题


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

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?


回答1:


Base-64 is 6 bits per character (2^6 = 64).

256 bits / 6 bits per char = 42.6666 char

And that has obviously ended up as 44 due to padding (you will see one or 2 = on the end of the output).

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

For hex use this:

return BitConverter.ToString(bytes).Replace("-", string.Empty);


来源:https://stackoverflow.com/questions/27817282/sha256-giving-44-length-output-instead-64-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!