SHA256:填充 512 位长度的消息

SHA256: Padding a 512 bits length message

我目前正在为 "custom-built" 嵌入式设备实施 SHA256 哈希算法。 显然我有消息填充的问题。 我编写的例程不适用于大小 正好等于 512 位 .

的消息

那么,消息应该怎么填充呢? 即

M = "AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPP"

Z.

即使开始时刚好是 512 位,您仍然需要填充消息。

FIPS 180-4,§5.1.1解释如下:

Suppose that the length of the message, M, is L bits. Append the bit “1” to the end of the message, followed by k zero bits, where k is the smallest, non-negative solution to the equation L + 1+ k ≡ 448 mod 512 . Then append the 64-bit block that is equal to the number L expressed using a binary representation.

[我用 L 替换了一个显示不正确的字符]

对于块大小的精确倍数的数据,PKCS#7 填充表示您必须添加一个填充块,每个字节都设置为填充字节数。在 AES 的情况下,块大小为 16 个字节,因此添加 16 个字节,每个字节的值为 0x10。

PKCS#7 padding

注意:PHP mcrypt 不执行 PKCS#7 填充,必须由用户代码完成。