Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

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
1  
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

1 Answer 1

up vote 2 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
1  
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

 
discard

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.