# What is the recommended x length in the Diffie-Hellman algorithm?

According to RFC 3526 & RFC 2412, the prime and the generator are defined, but there is no recommended length for the parameters of random number $$x$$. What is the recommended length of random number $$x$$?

In my case, I set the length of $$x$$ at 160 bits with a 1024- & 2048-bit prime.

Is it safe?

Now, it gives two different recommendations (which sounds rather less useful than giving one); the summary is that if the size of the random number you pick is $x$ bits, then an attacker can recover the shared secret with no more than $2^{x/2}$ work. If you're happy with 80 bit security, then selecting a 160 bit random $x$ is sufficient. If you want significantly more than 80 bit security, well, you might want to rethink the 1024 bit group.
You can use the Lenstra and Verheul equations to calculate the size of the key x, e.g. by entering the prime size value at keylength.com: choose Enter basic parameter & select Enter a discrete log group size, enter the size in bits of your chosen prime and hit compute.
Note that you may want to choose something nearby that is either $2^n$ or $2^n + 2^{(n - 1)}$ just to maintain compatibility over different libraries. At a minimum you should chose something that is dividable by 8.