From 558d96240bea7d910144fa2cad1fe2f8061ffa74 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 17 Aug 2022 11:32:38 +0200 Subject: [PATCH] sha256: add sha256_direct()/SHA256_DIRECT() helpers --- src/basic/hmac.c | 4 +--- src/boot/efi/random-seed.c | 13 ++----------- src/fundamental/sha256.c | 7 +++++++ src/fundamental/sha256.h | 4 ++++ 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/basic/hmac.c b/src/basic/hmac.c index 1e4e380aaa9..a5f66d56056 100644 --- a/src/basic/hmac.c +++ b/src/basic/hmac.c @@ -29,9 +29,7 @@ void hmac_sha256(const void *key, /* The key needs to be block size length or less, hash it if it's longer. */ if (key_size > HMAC_BLOCK_SIZE) { - sha256_init_ctx(&hash); - sha256_process_bytes(key, key_size, &hash); - sha256_finish_ctx(&hash, replacement_key); + sha256_direct(key, key_size, replacement_key); key = replacement_key; key_size = SHA256_DIGEST_SIZE; } diff --git a/src/boot/efi/random-seed.c b/src/boot/efi/random-seed.c index 652634bdc9b..aea4f7e5326 100644 --- a/src/boot/efi/random-seed.c +++ b/src/boot/efi/random-seed.c @@ -215,17 +215,8 @@ static void validate_sha256(void) { 0xaf, 0xac, 0x45, 0x03, 0x7a, 0xfe, 0xe9, 0xd1 }}, }; - for (UINTN i = 0; i < ELEMENTSOF(array); i++) { - struct sha256_ctx hash; - uint8_t result[HASH_VALUE_SIZE]; - - sha256_init_ctx(&hash); - sha256_process_bytes(array[i].string, strlen8(array[i].string), &hash); - sha256_finish_ctx(&hash, result); - - assert(memcmp(result, array[i].hash, HASH_VALUE_SIZE) == 0); - } - + for (UINTN i = 0; i < ELEMENTSOF(array); i++) + assert(memcmp(SHA256_DIRECT(array[i].string, strlen8(array[i].string)), array[i].hash, HASH_VALUE_SIZE) == 0); #endif } diff --git a/src/fundamental/sha256.c b/src/fundamental/sha256.c index 7ead5f169c5..43ee996b6f7 100644 --- a/src/fundamental/sha256.c +++ b/src/fundamental/sha256.c @@ -289,3 +289,10 @@ static void sha256_process_block(const void *buffer, size_t len, struct sha256_c ctx->H[6] = g; ctx->H[7] = h; } + +uint8_t* sha256_direct(const void *buffer, size_t sz, uint8_t result[static SHA256_DIGEST_SIZE]) { + struct sha256_ctx ctx; + sha256_init_ctx(&ctx); + sha256_process_bytes(buffer, sz, &ctx); + return sha256_finish_ctx(&ctx, result); +} diff --git a/src/fundamental/sha256.h b/src/fundamental/sha256.h index 337e746c498..31790c2ebd1 100644 --- a/src/fundamental/sha256.h +++ b/src/fundamental/sha256.h @@ -27,3 +27,7 @@ struct sha256_ctx { void sha256_init_ctx(struct sha256_ctx *ctx); uint8_t *sha256_finish_ctx(struct sha256_ctx *ctx, uint8_t resbuf[static SHA256_DIGEST_SIZE]); void sha256_process_bytes(const void *buffer, size_t len, struct sha256_ctx *ctx); + +uint8_t* sha256_direct(const void *buffer, size_t sz, uint8_t result[static SHA256_DIGEST_SIZE]); + +#define SHA256_DIRECT(buffer, sz) sha256_direct(buffer, sz, (uint8_t[SHA256_DIGEST_SIZE]) {})