Generating DH key with specific bit-length In PKCS#3 the generation for DH secrets mandates to generate them with a minimum size if length is specified:

The central authority may optionally select an integer $\ell$,
the private-value length in bits, that satisfies $2^{\ell-1} \le p$.
[…]
An integer $x$, the private value, shall be generated
privately and randomly. This integer shall satisfy $0 &lt; x &lt; p-1$,
unless the central authority specifies a private-value
length $\ell$, in which case the integer shall satisfy
$2^{\ell-1} \le x &lt; 2^\ell$.

(Math formulas re-typeset in LaTeX for readability; see comments.)
The normal way to do this would be generate a random number over the whole range and loop if it does not fit (pseudo Java):
do {
    x = new BigInteger(lSize, random);
} while(2^(lSize-1) &gt; x || x &gt; 2^lSize || x &gt; p-1); // x.bitLength!=lSize || x &gt; p-1

However this results in looping at least half of the time. Would it be safe to set the most significant bit by hand and generate the rest randomly. I think yes - as the bits are supposed to be independent:
do {
    x = new BigInteger(lSize-1, random);
    x = x.setBit(lSize);
} while (x &gt; p-1);

Is this an acceptable optimization?
Sure thing. You'd lose up to one bit of security, but that's generally acceptable.