I need to apply HMAC-SHA hashes in my application. Depending on the context I'll use either HMAC-SHA512, HMAC-SHA256 or HMAC-SHA1.

Is it safe to use the same key for all of these algorithms, or do I need to use a different key for each hash type? I plan to make the key 128 bytes which I understand is long enough for all of them.

  • $\begingroup$ Why not simply use a single algorithm? $\endgroup$ Aug 11 '16 at 11:11
  • $\begingroup$ Well some of the data being hashed is guaranteed to be very short (around 120 bytes) so using a hash that is longer than the data seems wasteful. $\endgroup$ Aug 11 '16 at 11:22
  • 2
    $\begingroup$ How about choosing one of these functions and truncating the output? $\endgroup$ Aug 11 '16 at 11:24
  • 2
    $\begingroup$ Reducing the security level for shorter messages seems a bit dubious. Assuming you need a MAC/PRF and not a collision resistant hash, you could use 128 bit MACs for everything. $\endgroup$ Aug 11 '16 at 11:26
  • $\begingroup$ Well I was planning to use full HMACSHA512 for messages that are cycled through user's web-browser because I consider it high risk. Was planning to use a shorter/truncated hash for the shorter message that will be stored in a secure database to reduce the risk of tampering. But I'll take your advice and user the longer hash for everything. $\endgroup$ Aug 11 '16 at 13:31

So, the answer to your question is that while it is recommended that you never reuse keys for different algorithms, it is quite unlikely that different hashes in HMAC would interact badly.

However, that does not mean what you are planning is the way to go. It makes little sense to change the strength of the authentication based on the length of the message, unless the message length directly correlates with the security level you expect. And even if that is something you want, there is no real advantage to using different HMAC hashes.

Instead, you should pick either SHA-256 or SHA-512 and use only that hash for HMAC. You can truncate the authentication tag to the desired length, which can vary with message length. However, you must make sure an attacker cannot simply use a shorter tag in all situations. And it is not really required, since even a 64-bit tag is usually considered sufficient. So you should likely just pick one length you are comfortable with.

Oh, and a 128-byte key is overkill. 256 bits is sufficient.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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