What is the SHA-256 hash of a single “1” bit?

2019-03-25 11:29发布

问题:

The definition of SHA-256 appears to be such that the input consisting of a single "1" bit has a well-defined hash value, distinct from that of the "01" byte (since the padding is done based on input's length in bits).

However, due to endianness issues and the fact that no implementations that I can find support feeding in single bits, I can't quite figure out what this correct value is.

So, what is the correct hash of the 1-bit long input consisting of the bit "1"? (not the 8-bit long byte[] { 1 } input).

回答1:

OK, according to my own implementation:

1-bit string "1":

B9DEBF7D 52F36E64 68A54817 C1FA0711 66C3A63D 384850E1 575B42F7 02DC5AA1

1-bit string "0":

BD4F9E98 BEB68C6E AD3243B1 B4C7FED7 5FA4FEAA B1F84795 CBD8A986 76A2A375

I have tested this implementation on several standard multiples-of-8-bits inputs, including the 0-bit string, and the results were correct.

(of course the point of this question was to validate the above outputs in the first place, so use with care...)



回答2:

Not sure if I understand your question correctly.

SHA-256 operates with block sizes of 64 bytes (=512bits). This means smaller inputs must be padded first. The result of the padding looks like this:

For Bit 1:    1100000000000...00000000001
For Bits 01:  0110000000000...00000000010

As this results are distinct, the results of the following compression functions will be too. And therefore the hash values are. The standard document explains the padding quite descriptive: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf



回答3:

There is C code available in section 8 of RFC 4634 to compute the hash of data that is not necessarily a multiple of 8 bits. See the methods whose names are SHA*FinalBits(...).