Tidy up HMAC_Init_ex slightly Guarding the OPENSSL_memset was unnecessary since OPENSSL_memset with zero length works fine. Also OPENSSL_memset, to workaround a C bug, internally does the same check anyway. (But also this wasn't a context where the C bug applied.) Also don't bother calling EVP_MD_block_size a second time when we already saved it into block_size. Finally, don't bother filling key_block up to the whole EVP_MAX_MD_BLOCK_SIZE size. I could believe the fixed size is easier for the compiler to optimize, but the XORs in setting up an HMAC cannot possibly be performance-sensitive, and using the actual length is clearer. Also add an assert that the hash's output size fits in the block size. We're implicitly relying on this when hashing the key down. Change-Id: I6ce37d41ea5bdbc8890bde7910e1b5651bc35709 Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/58027 Reviewed-by: Adam Langley <agl@google.com> Commit-Queue: David Benjamin <davidben@google.com> Auto-Submit: David Benjamin <davidben@google.com> Commit-Queue: Adam Langley <agl@google.com>
diff --git a/crypto/fipsmodule/hmac/hmac.c b/crypto/fipsmodule/hmac/hmac.c index ca774bc..c6f12e2 100644 --- a/crypto/fipsmodule/hmac/hmac.c +++ b/crypto/fipsmodule/hmac/hmac.c
@@ -151,6 +151,7 @@ size_t block_size = EVP_MD_block_size(md); assert(block_size <= sizeof(key_block)); + assert(EVP_MD_size(md) <= block_size); if (block_size < key_len) { // Long keys are hashed. if (!EVP_DigestInit_ex(&ctx->md_ctx, md, impl) || @@ -164,23 +165,21 @@ key_block_len = (unsigned)key_len; } // Keys are then padded with zeros. - if (key_block_len != EVP_MAX_MD_BLOCK_SIZE) { - OPENSSL_memset(&key_block[key_block_len], 0, sizeof(key_block) - key_block_len); - } + OPENSSL_memset(key_block + key_block_len, 0, block_size - key_block_len); - for (size_t i = 0; i < EVP_MAX_MD_BLOCK_SIZE; i++) { + for (size_t i = 0; i < block_size; i++) { pad[i] = 0x36 ^ key_block[i]; } if (!EVP_DigestInit_ex(&ctx->i_ctx, md, impl) || - !EVP_DigestUpdate(&ctx->i_ctx, pad, EVP_MD_block_size(md))) { + !EVP_DigestUpdate(&ctx->i_ctx, pad, block_size)) { goto out; } - for (size_t i = 0; i < EVP_MAX_MD_BLOCK_SIZE; i++) { + for (size_t i = 0; i < block_size; i++) { pad[i] = 0x5c ^ key_block[i]; } if (!EVP_DigestInit_ex(&ctx->o_ctx, md, impl) || - !EVP_DigestUpdate(&ctx->o_ctx, pad, EVP_MD_block_size(md))) { + !EVP_DigestUpdate(&ctx->o_ctx, pad, block_size)) { goto out; }