I am using HMAC+SHA256 to sign and verify claims in a web application. Each deployment has its own crypto-random 512-bit secret that I can use as the HMAC key, but in some cases I want to mix in another secret as well. For example, by mixing in the user's hashed password as part of the key, the token becomes invalid as soon as the user changes their password, which is useful for password reset links.

My main question is: What is the proper way to mix multiple secrets together to form an HMAC key?

One possibility is to concatenate the secrets together, but I've already hit the max effective key length of HMAC+SHA256 with my 512-bit instance-wide secret. Is XOR a better alternative?

Or is there a better way to mix multiple keys together, such as nesting HMAC calls? E.g. HMAC(HMAC(claims, secret1), secret2)?

As an ancillary question: Is it appropriate to do this in the first place? I like being able to say that if secret X changes, then the token is automatically invalid, without exposing the secret as a claim. Signing the token with multiple secrets seems like a great way to do that. Are there any concerns I should be aware of, using secrets (particularly the user's hashed password) in this way?

  • It is a good question, and it is probably disheartening not to have received an answer.
    – Patriot
    Jun 25 '19 at 5:47

At first it seemed to me that XORing the crypto-random secret keys is a good solution because the resulting key is also cryptographically secure (ref. https://crypto.stackexchange.com/questions/48145/xor-a-set-of-random-numbers), i.e. HMAC(claims, secret1 ^ secret2). But for this to work you would need to share your deployment secrets - avoid if possible.

The advantage of nesting the HMAC calculations like HMAC(HMAC(claims, secret1), secret2) is that each deployment can calculate the HMAC w/o sharing its secret with any other deployments.

As an alternative, a better solution might be XOR of the HMAC results instead of nesting them, i.e. HMAC(claims, secret1) ^ HMAC(claims, secret2). This approach retains more information from the claims for each HMAC operation.

  • Very good point that multiple processes may want to contribute their secrets without knowing each others'! Jan 8 '20 at 21:51

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.