[crypto] Generalise implementation of Merkle-Damgård hash algorithms

All of our current digest algorithms (MD4, MD5, SHA-1, and the SHA-2
family) use a Merkle-Damgård construction, with only the compression
function, the initial digest values, the field sizes, and the
endianness differing between algorithms.

Provide a common implementation for Merkle-Damgård hash algorithms to
reduce code size.  Values are now held as host-endian quantities, with
any swapping performed byte-by-byte as data is accumulated (using a
compile-time constant that is XORed with the byte index).

For the SHA family of algorithms, the values w[] are now calculated
iteratively as we progress through the main loop: this substantially
reduces the stack space required for the compression function.

Signed-off-by: Michael Brown <mcb30@ipxe.org>
This commit is contained in:
Michael Brown
2026-06-23 12:46:55 +01:00
parent 449d2acf3d
commit 327378a764
16 changed files with 585 additions and 908 deletions
+5 -14
View File
@@ -30,25 +30,16 @@ FILE_SECBOOT ( PERMITTED );
*
*/
#include <stdint.h>
#include <byteswap.h>
#include <ipxe/crypto.h>
#include <ipxe/sha256.h>
/** SHA-224 initial digest values */
static const struct sha256_digest sha224_init_digest = {
static const struct sha256_digest sha224_init = {
.h = {
cpu_to_be32 ( 0xc1059ed8 ),
cpu_to_be32 ( 0x367cd507 ),
cpu_to_be32 ( 0x3070dd17 ),
cpu_to_be32 ( 0xf70e5939 ),
cpu_to_be32 ( 0xffc00b31 ),
cpu_to_be32 ( 0x68581511 ),
cpu_to_be32 ( 0x64f98fa7 ),
cpu_to_be32 ( 0xbefa4fa4 ),
},
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
}
};
/** SHA-224 algorithm */
SHA256_ALGORITHM ( sha224, sha224_algorithm, SHA224_DIGEST_SIZE,
&sha224_init_digest );
SHA256_ALGORITHM ( sha224, sha224_algorithm, sha224_init, SHA224_DIGEST_SIZE );