4

Short version: When generating a prime number of N bits, should I draw random numbers from the range $[0 , 2^n]$, or $[2^{(n-1)} , 2^n]$?

Context: I'm trying to implement a toy-version of RSA as a hobby, with a Miller-Rabin test to generate primes. Initially, my function to generate the keys had the following signature:

$$generateKeys :: (Range, Seed) \rightarrow (PublicKey, PrivateKey)$$

where Range is the range of numbers in which to generate random numbers to search for primes, which initially I had set to $[2^{16}, 2^n]$ to avoid the $[0-2^{16}]$ range, given that RSA implementation guides recommend avoiding using small primes.

But I started wondering if instead I should specify the number of bits of the

$$generateKeys :: (BitsToUse, Seed)\rightarrow (PublicKey, PrivateKey)$$

And this in turn got me wondering exactly what does a "N bit prime" mean, ie, exactly which range from which to pick the prime is generally desired, specially since the range $[2^{(n-1)}, 2^n]$ is "only" half the size of $[0 , 2^n]$, although I guess primes are a bit less dense in that range.

Mike Edward Moras
  • 18,161
  • 12
  • 87
  • 240
Pepe Mandioca
  • 143
  • 1
  • 4

1 Answers1

4

In the context of RSA, when we say an "N bit prime", we mean that it's a prime in the range $[2^{n-1}, 2^n)$.

In addition, when we say an RSA key is an "N bit key", we mean that it's in the range $[2^{n-1}, 2^n)$. What this means that if you pick two random $N/2$ bit primes, and multiply them together, you'll get an $N-1$ bit modulus about half the time. To avoid this, one common practice is to select the primes from the range $(\sqrt{2}\cdot 2^{n/2-1}, 2^{n/2})$ - that way, when we multiply the two primes together, we'll always get an N-bit key.

If you're worried that restricting the primes to this range will make guessing them easier, well, that's actually not a concern. If we're generating a 1024 bit key (which by today's standards is cutting it close), there are approximately $10^{151}$ primes in the range $(\sqrt{2}\cdot 2^{511}, 2^{512})$-- it's unlikely anyone will happen to guess either one.

poncho
  • 154,064
  • 12
  • 239
  • 382