Hacking Secret Ciphers with Python

(Ann) #1

210 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The // Integer Division Operator


You may have noticed the // operator used in the findModInverse() function above. This
is the integer division operator. It divides two numbers and rounds down. Try typing the
following into the interactive shell:





41 // 7
5
41 / 7
5.857142857142857
10 // 5
2
10 / 5
2.0





Notice that an expression with the // integer division operator always evaluates to an int, not a
float.


Source Code of the cryptomath Module


The gcd() and findModInverse() functions will be used by more than one of our cipher
programs later in this book, so we should put this code into a separate module. In the file editor,
type in the following code and save it as cryptomath.py:


Source code for cryptomath.py




  1. Cryptomath Module




  2. http://inventwithpython.com/hacking (BSD Licensed)





  3. def gcd(a, b):


  4. Return the GCD of a and b using Euclid's Algorithm



  5. while a != 0:

  6. a, b = b % a, a

  7. return b





  8. def findModInverse(a, m):


  9. Returns the modular inverse of a % m, which is




  10. the number x such that a*x % m = 1





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

  12. return None # no mod inverse if a & m aren't relatively prime




  13. Calculate using the Extended Euclidean Algorithm:



Free download pdf