When I generate a key with the a Diffie Hellman method (DH), the established shared key will be of the same size as the prime which is used. As far as I have read this should be at least 2000 bits for the classical DH, some say even more.

But normally 256 or 512 bits are needed for a symmetric scheme.

I have heard that it should be enough to just hash the established key to reduce the size, but some use a key derivation function.

Now I ask myself what is the standard way to do this? Also is it more secure to use a key derivation function?

I would appreciate if you could name the methods that are used and were I could read more about such methods.

  • A key-derivation function is little more than a hash. The main advantage of HKDF is that it produces named, arbitrary sized outputs instead of a single constant size output. HKDF is very simple to implement on top of HMAC-SHA-2. Aug 12, 2013 at 12:18

1 Answer 1


Diffie-Hellman allows two parties to generate a secret value that cannot be reconstructed from observing their communications. The size of the secret value resulting from the key exchange (ga b mod p) is indeed the same size as the prime, however its entropy may be less if a and b are chosen in a smaller space. Picking a and b to be 256-bit random numbers gives you 128-bit security for the resulting secret value.

In principle, the resulting secret value has some mathematical structure, and you shouldn't use it as is. Instead, you should hash it and use the result as your symmetric key. More precisely, you should use the shared secret as input to a key derivation function. Not a password-based key derivation function: the secret value has sufficient entropy and doesn't need to be strengthened, only stretched.

RFC 2631 specifies a way to derive key material from the shared secret: SHA-1(ZZ || type || ctr) where ZZ is a byte encoding of the shared secret, type indicates what kind of material is being derived, and ctr is a byte encoding of a counter. It's obviously ok to use another hashing function such as SHA-256 or SHA-512 instead of SHA-1.

The exact way the key material is derived isn't actually important, as long as the two parties agree. For example, if you only need 256 bits, then SHA-256(ZZ) would be ok. The point of tacking on a counter is when you need more than what one run of the hash function can provide. In the interest of future-proofing your protocol, it would be advisable to follow the RFC. If you only need to derive one key now, you can hard-code the corresponding ASN.1 encoding of the type and counter as a string literal in your application.

Actually, it turns out that using the DH shared secret directly is “not too bad”. Nonetheless, you should wring it through a KDF (at least hash it): it's easy, quick, more secure, more standard, and more future-proof.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .