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.

110 Chapter 4 ■ Cryptographic Math and Frequency Analysis

If the modulus is prime, Python provides an internal function called pow that

takes a, p − 2, and p to compute the inverse modulo. Consider the following

example:

>>> a = 14

>>> p = 101

>>> a_inv = pow(a, p-2, p)

>>> a_check = a * a_inv % p

>>> print("The modular inverse is ", a_inv)

The modular inverse is 65

>>> print("The check value should equal 1. It equals ", a_check)

The check value should equal 1. It equals 1

Fermat’s Little Theorem to Find the Inverse

As mentioned earlier in this chapter, we can use Fermat’s little theorem to calculate

the inverse if we know that m is prime:

a (m − 1) ≡ 1 (mod m)

a −1 ≡ a m − 2 (mod m)

Here’s the Python code to calculate the inverse if we know that m is prime:

# Fermat's little theorem.

# modular inverse of a under modulo m using

# Assumption: m is prime

def gcd(a,b):

if (b == 0):

return a

else:

return gcd(b, a % b)

# To compute x^y under modulo m

def power(x,y,m):

if (y == 0):

return 1

p = power(x, y // 2, m) % m

p = (p * p) % m

return p if(y % 2 == 0) else (x * p) % m

# Function to find modular inverse of a under modulo m

def modInverse(a,m):

if (gcd(a, m) != 1):

print("Inverse doesn't exist")

else:

# If a and m are relatively prime, then

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

Saved successfully!

Ooh no, something went wrong!