开发者

Why does this method for computing a SHA-256 hash always return a string of 44 characters?

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 = En开发者_如何学运维coding.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?


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).


You're converting it to a Base64 string...

You might want to use this instead:

 // Cut bad code

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"? ;-(

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜