python3 中的 SHA256 实现,最终哈希值太短

Implementation of SHA256 in python3, final hash is too short

我正在尝试在 python 中编写 SHA-256 的实现 3. 我的版本应该采用十六进制编码并输出相应的哈希值。我使用 https://en.wikipedia.org/wiki/SHA-2#Pseudocode 作为指南。

我的函数适用于大多数输入,但有时它给出的输出仅为 63 位(而不是 64 位)。我的函数使用 32 位二进制字符串。

我想我找到了问题,在算法的最后一步二进制加法

h4 := h4 + e (or another h-vector and corresponding letter)

生成的二进制数太小。我做的最后一件事是使用 hex(),我应该得到一个 8 个字符的字符串。在这个例子中我只得到 7.

out4 = hex(int(h4,2))[2:]

一个有问题的输入是 e5e5e5 它给 h4 为“10110101111110101011010101101100”,e 为“01010001000011100101001001111111” 所以加法给出“00000111000010010000011111101011” 和 out4 = 70907eb.

遇到这些情况我该怎么办?

I should get a string of 8 characters

你为什么这么认为? hex 不允许指定输出开始的长度,因此,例如,如果正确的输出是 8 个字节的零,hex 将 return 0x0 - 可能的最短表示。

我猜正确的输出应该以零开头,但 hex 将其截断。使用格式字符串指定输出长度:

In [1]: f'{0:08x}'                                                             
Out[1]: '00000000'  # lowercase hexadecimal (x) digits that must fit into at least 8 characters, prefixed with zero (08) as needed