# How to generate Large Prime numbers for RSA Algorithm

The security of the RSA algorithm is based on the difficulty of factorizing very large numbers. The setup of an RSA cryptosystem involves the generation of two large primes, say p and q, from which, the RSA modulus is calculated as n = p * q. The greater the modulus size, the higher is the security level of the RSA system. The recommended RSA modulus size for most settings is 2048 bits to 4096 bits. Thus, the primes to be generated need to be 1024 bit to 2048 bit long. For the synthesis of such large primes, instead of depending on deterministic methods, we rely on finding numbers that are prime with a satisfactorily high level of probability.

## Large Prime Generation Procedure:

• The goal is to efficiently compute very large random prime numbers with a specified bit-size. The standard method of manually implementing a random prime number generator which can generate prime values with a satisfactory level of accuracy is given as follows:

1. Preselect a random number with the desired bit-size
2. Ensure the chosen number is not divisible by the first few hundred primes (these are pre-generated)
3. Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime

### Below are the steps to implement the above procedure:

1. Picking a Random Prime Candidate
• The generation of a random number with n-bits means the random number is in the range 0 and . Some considerations when generating the random number are:

1. Picking of small primes, such as 3, 5, 7…, must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1
2. Since all primes (> 2) are odd, for better performace, just odd number may be picked
• Thus, we pick any random number in the range `def` `nBitRandom(n): ` ` `  `    ``# Returns a random number ` `    ``# between 2**(n-1)+1 and 2**n-1''' ` `    ``return``(random.randrange(``2``*``*``(n``-``1``)``+``1``, ``2``*``*``n``-``1``)) `

2. Division with First Primes (Low-Level Primality Test)
• This step is a a low level primality test which requires the pre-calculation of the first few hundred primes (using Sieve of Eratosthenes).
• The prime candidate is divided by the pre-generated primes to check for divisibility. If the prime candidate is perfectly divisible by any of these pre-generated primes, the test fails and a new prime candidate must be picked and tested. This is repeated as long as a value which is coprime to all the primes in our generated primes list is found

 `def` `getLowLevelPrime(n): ` `    ``'''Generate a prime candidate divisible ` `      ``by first primes'''` ` `  `    ``# Repeat until a number satisfying ` `    ``# the test isn't found ` `    ``while` `True``:  ` ` `  `        ``# Obtain a random number ` `        ``prime_candidate ``=` `nBitRandom(n)  ` ` `  `        ``for` `divisor ``in` `first_primes_list:  ` `            ``if` `prime_candidate ``%` `divisor ``=``=` `0`  `            ``and` `divisor``*``*``2` `<``=` `prime_candidate: ` `                ``break` `            ``# If no divisor found, return value ` `            ``else``: ``return` `prime_candidate  `

3. Rabin Miller Primality Test (High-Level Primality Test)
• A prime candidate passing the low-level test is then tested again using the Rabin Miller Primality Test.
• For extremely large numbers, such as ones used in RSA, deterministic testing of whether the chosen value is prime or not is highly impractical as it requires an unreasonable amount of computing resources.
• A probabilistic approach is preferred as such. If an inputted value passes a single iteration of the Rabin Miller test, the probability of the number being prime is 75%.
• Thus, a candidate passing the test, an adequate number of times, can be considered to be a prime with a satisfactory level of probability.
• Usually, in commercial applications, we require error probabilities to be less than .

 `def` `isMillerRabinPassed(miller_rabin_candidate): ` `    ``'''Run 20 iterations of Rabin Miller Primality test'''` ` `  `    ``maxDivisionsByTwo ``=` `0` `    ``evenComponent ``=` `miller_rabin_candidate``-``1` ` `  `    ``while` `evenComponent ``%` `2` `=``=` `0``: ` `        ``evenComponent >>``=` `1` `        ``maxDivisionsByTwo ``+``=` `1` `    ``assert``(``2``*``*``maxDivisionsByTwo ``*` `evenComponent ``=``=` `miller_rabin_candidate``-``1``) ` ` `  `    ``def` `trialComposite(round_tester): ` `        ``if` `pow``(round_tester, evenComponent,  ` `               ``miller_rabin_candidate) ``=``=` `1``: ` `            ``return` `False` `        ``for` `i ``in` `range``(maxDivisionsByTwo): ` `            ``if` `pow``(round_tester, ``2``*``*``i ``*` `evenComponent, ` `                   ``miller_rabin_candidate)  ` `            ``=``=` `miller_rabin_candidate``-``1``: ` `                ``return` `False` `        ``return` `True` ` `  `    ``# Set number of trials here ` `    ``numberOfRabinTrials ``=` `20`  `    ``for` `i ``in` `range``(numberOfRabinTrials): ` `        ``round_tester ``=` `random.randrange(``2``, ` `                       ``miller_rabin_candidate) ` `        ``if` `trialComposite(round_tester): ` `            ``return` `False` `    ``return` `True`

4. Combining the above steps to generate the code
• Finally, we can combine the above functions to create a three-step process to generate large primes. The steps would be

1. Random number generation by calling nBitRandom(bitsize)
2. Basic division test by calling getLowLevelPrime(prime_candidate)
3. Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)
• If the chosen random value passes all primality tests, it is returned as the n-bit prime number. Otherwise, in the case of test-failure, a new random value is picked and tested for primality. The process is repeated until the desired prime is found.

### Below is the complete implementation of the above approach

 `# Large Prime Generation for RSA ` `import` `random ` ` `  `# Pre generated primes ` `first_primes_list ``=` `[``2``, ``3``, ``5``, ``7``, ``11``, ``13``, ``17``, ``19``, ``23``, ``29``, ` `                     ``31``, ``37``, ``41``, ``43``, ``47``, ``53``, ``59``, ``61``, ``67``,  ` `                     ``71``, ``73``, ``79``, ``83``, ``89``, ``97``, ``101``, ``103``,  ` `                     ``107``, ``109``, ``113``, ``127``, ``131``, ``137``, ``139``,  ` `                     ``149``, ``151``, ``157``, ``163``, ``167``, ``173``, ``179``,  ` `                     ``181``, ``191``, ``193``, ``197``, ``199``, ``211``, ``223``, ` `                     ``227``, ``229``, ``233``, ``239``, ``241``, ``251``, ``257``, ` `                     ``263``, ``269``, ``271``, ``277``, ``281``, ``283``, ``293``, ` `                     ``307``, ``311``, ``313``, ``317``, ``331``, ``337``, ``347``, ``349``] ` ` `  `def` `nBitRandom(n): ` `    ``return` `random.randrange(``2``*``*``(n``-``1``)``+``1``, ``2``*``*``n ``-` `1``) ` ` `  `def` `getLowLevelPrime(n): ` `    ``'''Generate a prime candidate divisible  ` `    ``by first primes'''` `    ``while` `True``: ` `        ``# Obtain a random number ` `        ``pc ``=` `nBitRandom(n)  ` ` `  `         ``# Test divisibility by pre-generated  ` `         ``# primes ` `        ``for` `divisor ``in` `first_primes_list: ` `            ``if` `pc ``%` `divisor ``=``=` `0` `and` `divisor``*``*``2` `<``=` `pc: ` `                ``break` `        ``else``: ``return` `pc ` ` `  `def` `isMillerRabinPassed(mrc): ` `    ``'''Run 20 iterations of Rabin Miller Primality test'''` `    ``maxDivisionsByTwo ``=` `0` `    ``ec ``=` `mrc``-``1` `    ``while` `ec ``%` `2` `=``=` `0``: ` `        ``ec >>``=` `1` `        ``maxDivisionsByTwo ``+``=` `1` `    ``assert``(``2``*``*``maxDivisionsByTwo ``*` `ec ``=``=` `mrc``-``1``) ` ` `  `    ``def` `trialComposite(round_tester): ` `        ``if` `pow``(round_tester, ec, mrc) ``=``=` `1``: ` `            ``return` `False` `        ``for` `i ``in` `range``(maxDivisionsByTwo): ` `            ``if` `pow``(round_tester, ``2``*``*``i ``*` `ec, mrc) ``=``=` `mrc``-``1``: ` `                ``return` `False` `        ``return` `True` ` `  `    ``# Set number of trials here ` `    ``numberOfRabinTrials ``=` `20`  `    ``for` `i ``in` `range``(numberOfRabinTrials): ` `        ``round_tester ``=` `random.randrange(``2``, mrc) ` `        ``if` `trialComposite(round_tester): ` `            ``return` `False` `    ``return` `True` ` `  `if` `__name__ ``=``=` `'__main__'``: ` `    ``while` `True``: ` `        ``n ``=` `1024` `        ``prime_candidate ``=` `getLowLevelPrime(n) ` `        ``if` `not` `isMillerRabinPassed(prime_candidate): ` `            ``continue` `        ``else``: ` `            ``print``(n, ``"bit prime is: \n"``, prime_candidate) ` `            ``break`

Output:

1024 bit prime is:
178542003245811211274167228297361192303886321036074276889145691522634525820185614278499562592134188995169731066418203258297035264969457638591284906658912408319763156912951486020761069099132619194489006875108217247513715271974383296142805846405783845170862140174184507256128825312324419293575432423822703857091

### Note: Library Generation of Large Primes in Python

The pycrypto library is a comprehensive collection of secure hash functions and various encryption algorithms. It also includes basic functions commonly required in encryption/decryption setups such as random number generation and random prime number generation. The goal of generating a random prime number with a specified bit-size can be achieved using the pycrypto getPrime module.
The syntax for generating a random n-bit prime number is:

 `from` `Crypto.Util ``import` `number ` `number.getPrime(n) `

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.