简体   繁体   English

为什么此用于计算SHA-256哈希的方法总是返回44个字符的字符串?

[英]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: 以下总是输出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);
        }
    }
}

Output of this application: 该应用程序的输出:

44 44
K5NtMqCN7IuYjzccr1bAdajtfiyKD2xL15Eyg5oFCOc= K5NtMqCN7IuYjzccr1bAdajtfiyKD2xL15Eyg5oFCOc =

If I am not mistaken, the output should be: 如果我没记错的话,输出应该是:

64 64
2b936d32a08dec8b988f371caf56c075a8ed7e2c8a0f6c4b979132839a0508e7 2b936d32a08dec8b988f371caf56c075a8ed7e2c8a0f6c4b979132839a0508e7

What is going on here? 这里发生了什么?

See where it says Convert.ToBase64String(hashedBytes) ? 看到在哪里说Convert.ToBase64String(hashedBytes)吗? It's not giving you a hexadecimal string (4 bits per character) - it's in base 64 (6 bits per character). 它没有为您提供十六进制字符串(每个字符4位),而是以64为基数(每个字符6位)。

You're converting it to a Base64 string... 您正在将其转换为Base64字符串...

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. 编辑:这是上面发布的BitConverter.ToString()的可怜人的实现。 Why is the internet filled with reimplementations of existing framework functionality when searching for common functionality like "string to hex"? 在搜索“字符串到十六进制”之类的通用功能时,为什么互联网上充满了对现有框架功能的重新实现? ;-( ;-(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM