1
$\begingroup$

For learning purpose, I'm trying to implement HMAC using SHA256.

In the pseudo code proposed in Wikipedia, the algorithm first focus on how to shorten or expand the key :

if (length(key) > blocksize) {
    key = hash(key) // keys longer than blocksize are shortened
}
if (length(key) < blocksize) {
    // keys shorter than blocksize are zero-padded (where ∥ is concatenation)
    key = key ∥ [0x00 * (blocksize - length(key))] // Where * is repetition.
}

Given I'm using SHA-256 that has a blocksize of 64 bytes and an output of 32 bytes :

  • if the key length is greater than 64 bytes, it will be shortened to 32 bytes
  • if the key length is less than 64 bytes, it will be expanded to 64 bytes

From what I read 32 bytes should provide enough security. But doesn't that seem odd that a 65 bytes key will provide less security than a 63 bytes key ?

$\endgroup$
1
  • 1
    $\begingroup$ Granted, it's a bit weird. But they would have to jump through hoops to leave 64 bytes of input material, and more than 64 bytes simply don't fit. In the end the output will just be 32 bytes though. $\endgroup$
    – Maarten Bodewes
    Dec 10, 2016 at 0:30

1 Answer 1

3
$\begingroup$

From the HMAC-RFC 2104, section 3
(B = blocksize, L = hash output length):

The key for HMAC can be of any length (keys longer than B bytes are first hashed using H). However, less than L bytes is strongly discouraged as it would decrease the security strength of the function. Keys longer than L bytes are acceptable but the extra length would not significantly increase the function strength. (A longer key may be advisable if the randomness of the key is considered weak.)

Tldr, unlike you, they don't consider a longer key to be more secure.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.