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 97

A = B * Q + R and B ≠ 0 then GCD(A, B) = GCD(B,R)

Therefore, write A using the quotient remainder form: A = B * Q + R

Find GCD(B, R)

Euclid’s algorithm works by continuously dividing one number into another

and calculating the quotient and remainder at each step. Each phase produces a

decreasing sequence of remainders, which terminate at zero, and the last nonzero

remainder in the sequence is the GCD. You will revisit Euclid’s algorithm

shortly when you examine the modular inverses; for now, you can use the

algorithm to write a GCD function in Python:

def gcd(a,b):

if b == 0:

return a

else:

return gcd(b, a % b)

print(gcd(12,18))

Now that you know how to create your own GCD function, note that it is

very inefficient due to its use of recursion. Prefer using Python’s built-in GCD

function, which is part of the standard Python math library. You will see an

example of this when you explore Euler’s totient function later in this chapter.

Prime Numbers

Prime numbers in cryptography are vital to the security of our encryption

schemes. Prime factorization, also known as integer factorization, is a mathematical

problem that is used to secure public-key encryption schemes. This is achieved

by using extremely large semiprime numbers that are a result of the multiplication

of two prime numbers. As you may remember, a prime number is

any number that is only divisible by 1 and itself. The first prime number is 2.

Additional prime numbers include 3, 5, 7, 11, 13, 17, 19, 23, and so on. An infinite

number of prime numbers exist, and all numbers have one prime factorization.

A semiprime number, also known as biprime, 2-almost prime, or a pq number,

is a natural number that is the product of two prime numbers. The semiprimes

less than 50 are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, and 49.

Prime numbers are significant in cryptography. Here is a simple Python script

that tests if an integer value is prime:

def isprime(x):

x = abs(int(x))

if x < 2:

return "Less 2", False

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

Saved successfully!

Ooh no, something went wrong!