diff --git a/crypto/hmac_drbg.c b/crypto/hmac_drbg.c index fa4569f49..639fed841 100644 --- a/crypto/hmac_drbg.c +++ b/crypto/hmac_drbg.c @@ -118,9 +118,9 @@ void hmac_drbg_generate(HMAC_DRBG_CTX *ctx, uint8_t *buf, size_t len) { size_t i = 0; while (i < len) { update_v(ctx); - for (size_t j = 0; j < 8; j++) { + for (size_t j = 0; j < 8 && i < len; j++) { uint32_t r = ctx->v[j]; - for (int k = 24; k >= 0; k -= 8) { + for (int k = 24; k >= 0 && i < len; k -= 8) { buf[i++] = (r >> k) & 0xFF; } } diff --git a/crypto/tests/test_check.c b/crypto/tests/test_check.c index ff4256239..310640ced 100644 --- a/crypto/tests/test_check.c +++ b/crypto/tests/test_check.c @@ -4637,6 +4637,7 @@ START_TEST(test_hmac_drbg) { "c3e66ea1b1a064b005de914eac2e9d4f2d72a8616a80225422918250ff66a41bd2f864a6" "a38cc5b6499dc43f7f2bd09e1e0f8f5885935124"; uint8_t result[128]; + uint8_t null_bytes[128] = {0}; uint8_t nonce_bytes[16]; memcpy(nonce_bytes, fromhex(nonce), sizeof(nonce_bytes)); @@ -4648,12 +4649,16 @@ START_TEST(test_hmac_drbg) { hmac_drbg_generate(&ctx, result, sizeof(result)); ck_assert_mem_eq(result, fromhex(expected), sizeof(result)); - hmac_drbg_init(&ctx, fromhex(entropy), strlen(entropy) / 2, nonce_bytes, - strlen(nonce) / 2); - hmac_drbg_reseed(&ctx, fromhex(reseed), strlen(reseed) / 2, NULL, 0); - hmac_drbg_generate(&ctx, result, sizeof(result) - 13); - hmac_drbg_generate(&ctx, result, sizeof(result) - 17); - ck_assert_mem_eq(result, fromhex(expected), sizeof(result) - 17); + for (size_t i = 0; i <= sizeof(result); ++i) { + hmac_drbg_init(&ctx, fromhex(entropy), strlen(entropy) / 2, nonce_bytes, + strlen(nonce) / 2); + hmac_drbg_reseed(&ctx, fromhex(reseed), strlen(reseed) / 2, NULL, 0); + hmac_drbg_generate(&ctx, result, sizeof(result) - 13); + memset(result, 0, sizeof(result)); + hmac_drbg_generate(&ctx, result, i); + ck_assert_mem_eq(result, fromhex(expected), i); + ck_assert_mem_eq(result + i, null_bytes, sizeof(result) - i); + } } END_TEST