07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Cryptographic Math and Frequency Analysis 103

Figure 4.1 shows the use the Miller-Rabin primality test to display all prime

numbers between 1 and 1000.

Figure 4.1: Miller.py test

Now that you have a better understanding of primality tests, you can use

the Miller-Rabin primality test to verify if much larger numbers are prime. In

the next code listing, you can test to make sure that a specific prime satisfies

a specific set of bits such as 1,024 or 2,048; large primes such as these will be

used in stronger encryption that will be introduced in Chapter 8. In the next

section, you will see the is_prime() function used to ensure that the numbers

being generated are prime.

The code will use the prime number theorem to generate an approximation

of π(n) because when n tends to infinity, π(n)/(n/ln(n)) = 1. The probability that

a randomly chosen number is prime is 1/ln(n). This is due to the fact that there

are n positive integers ≤ n and approximately n/ln(n) primes, and (n/ln(n))/

n = (1/ln(n)). To get an understanding of what the theorem states, examine the

probability of finding a prime number of 1,024 bits. Using the prime number

theorem, you will see that the probability is 1/(ln(2 1,024 )) = (1/710). Prime numbers

have to be odd since 2 will divide into any even number; the single exception

is the number 2. When attempting to generate a large prime, you can increase

the probability by 2, so on average, to generate a 1,024-bit prime number, you

may need to test 355 randomly generated numbers.

Examine the following Python code to test large prime numbers:

def is_prime(n, k=128):

""" Test if a number is prime

Args:

n -- int -- the number to test

k -- int -- the number of tests to do

return True if n is prime

"""

# Test if n is not even.

# But take care, 2 is prime !

if n == 2 or n == 3:

return True

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!