# Diffie-Hellman and secret key size

How can one guarantee that the generated DH secret key is of certain length? Say 256bit. Actually, prime length is not enough since the remainder of the last process, the modulus, may result in too small number.

• Key derivation functions such as HKDF might be your missing piece. – DannyNiu Apr 28 '19 at 15:15
• I didn't find a source stating that SSH uses HKDF. SSH makes intensive use of DH. Is it part of DH process itself? What is the source of this information. Even worse, HKDF itself needs predefined set of algorithms to be agreed on among the communicating parties. – m.nasim Apr 28 '19 at 15:19

Once you have computed a DH shared secret, $$g^{ab}$$, you always hash the result, $$k = H(g^{ab})$$, before (authenticating it and) using it as a secret key—and preferably, hash the entire transcript of the conversation so far that went into it, like $$k = H(g^a, g^b, g^{ab})$$, to prevent an adversary from tweaking any part of the handshake that is not authenticated.
The hash $$H$$ is sometimes called a key derivation function, and there are standard examples like HKDF, often with an extract/expand structure: let $$k = \operatorname{HKDF-Extract}(g^a, g^b, g^{ab})$$ be the master shared secret key, and then derive subkeys for different purposes by $$k_1 = \operatorname{HKDF-Expand}_k(\text{‘first purpose’})$$, $$k_2 = \operatorname{HKDF-Expand}_k(\text{‘second purpose’})$$, etc.