仿射密码为单表加密的一种,字母系统中所有字母都藉一简单数学方程加密,对应至数值,或转回字母。  ——百度百科

 

辗转相除法 与 寻找模逆:

 1 # Cryptomath Module
 2 # http://inventwithpython.com/hacking (BSD Licensed)
 3 
 4 def gcd(a, b):
 5     # Return the GCD of a and b using Euclid's Algorithm
 6     while a != 0:
 7         a, b = b % a, a
 8     return b
 9 
10 
11 def findModInverse(a, m):
12     # Returns the modular inverse of a % m, which is
13     # the number x such that a*x % m = 1
14 
15     if gcd(a, m) != 1:
16         return None # no mod inverse if a & m aren't relatively prime
17 
18     # Calculate using the Extended Euclidean Algorithm:
19     u1, u2, u3 = 1, 0, a
20     v1, v2, v3 = 0, 1, m
21     while v3 != 0:
22         q = u3 // v3 # // is the integer division operator
23         v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
24     return u1 % m
cryptMath

相关文章: