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.

Chapter 4 ■ Cryptographic Math and Frequency Analysis 111

# modulo inverse is a^(m-2) mode m

print("Modular multiplicative inverse is ",

power(a, m - 2, m))

a = 3

m = 11

modInverse(a, m)

NOTE In the preceding code listing, the code uses a gcd() function instead of

using the built-in math library to help you understand how to code the GCD. You will

find this helpful when you use the extended GCD.

Extending the GCD

To find the inverse when you have a nonprime modulus, you need to add a new

trick: the extended Euclidean algorithm. The extended Euclidean algorithm is

useful when two integers (a, b) are coprime; two numbers are said to be coprime

if the only positive number that divides both numbers is 1.

The next example returns the inverse using the extended Euclidean algorithm:

def egcd(a, b):

if a == 0:

return (b, 0, 1)

else:

g, y, x = egcd(b % a, a)

return (g, x - (b // a) * y, y)

def modinv(a, m):

g, x, y = egcd(a, m)

if g != 1:

raise Exception('modular inverse does not exist')

else:

return x % m

a = 102721840089015263978980446

p = 6768924473842051155435121

print modinv(a, p)

4751454584755824717584097

Euler’s Theorem

Earlier in this chapter, you were introduced to Fermat’s little theorem. We will

now examine a generalization of Fermat’s theorem known as Euler’s theorem.

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

Saved successfully!

Ooh no, something went wrong!