07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

98 Chapter 4 ■ Cryptographic Math and Frequency Analysis

elif x == 2:

return True

elif x % 2 == 0:

return False

else:

for n in range(3, int(x**0.5)+2, 2):

if x % n == 0:

return n, False

return True

print (isprime(100000007))

Computationally speaking, it is easy to generate large prime numbers that

will require most humans to either perform math on paper or use a computer.

You can calculate a fairly large number and then check if there are any available

factors. Take, for example, 19 × 13 = 589. Both 19 and 13 are prime numbers as

their only factors are themselves and 1; the product of the two numbers results

in a semiprime. Multiplying 19 and 13 together is straightforward. However,

finding the factors of 589 is a bit more challenging. To find all factors, you will

need to examine all of the primes that are less than 589 until you find which

prime numbers are used. You can achieve this reasonably quickly for smaller

numbers, but once you start dealing with larger numbers, the amount of possible

numbers that are required to check becomes so large that even modern

computers are not able to calculate them within a reasonable time frame.

Prime Number Theorem

To estimate the generation of prime numbers, you can use the prime number

theorem. The prime number theorem returns an approximate value for the

number of primes less than or equal to a provided positive real number x. The

usual notation for this number is π(x), so that π(2) = 1, π(3.5) = 2, and π(10) = 4.

To generate large prime numbers, you will need to take an approximation and

then use a primality test to verify the number. You will see how this works at

the end of this section when you review the code listing for generating large

prime numbers.

You can write a number of primality tests in Python. Some of the examples

provided in this chapter include the school primality test, Fermat’s little theorem,

and the Miller-Rabin primality test.

School Primality Test

The school primality test solves the problem of whether an integer is prime or

not by iterating through all of the numbers starting from 2 to (n/2) using a loop

for every number check to see if it divides n. If the program finds any number

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

Saved successfully!

Ooh no, something went wrong!