Information Security Stack Exchange is a question and answer site for information security professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to use HMAC on a certain message to guarantee integrity, but I cannot figure out what are the requirements for the key to be given as input to the hashing algorithm.

In particular I have to do this in Java and, as I want to use HMAC with SHA256, I need to have a key of at least 32bytes, according to the HMAC RFC. For the moment (for testing) I am generating the key with SecureRandom("NativePRNG"), a Java implementation of a cryptographically strong random number generator. Is this enough for the key?

share|improve this question
Yes that's fine if your java implementation isn't broken (AFAIK some versions of Android are broken). The main issue in practice is how to share the key with your communication partners without an attacker learning what it is. – CodesInChaos Nov 15 '13 at 14:15
up vote 3 down vote accepted

The key should be the same size as the hash output. In your case you are using SHA-256 so you should use a 256-bit key (which equals 32-bytes that you mention).

The HMAC algorithm is really quite flexible, so you could use a key of any size. However, if you only use a 128-bit key then there is no point using a 256-bit hash; you might as well use a 128-bit hash like MD5.

SecureRandom in Java is quite adequate for generating keys for this purpose.

share|improve this answer
Using a wider hash which you only truncate in the end can be a good idea. For example I know of no good native 128 bit hashes, or one might want to use SHA-512 for its performance advantage on 64 bit systems despite 512 bit hashes being overkill. – CodesInChaos Nov 15 '13 at 18:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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