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