主要为两个函数的实现:
加密函数 : y = ax+b (mod m), (一般m设置为26),a为密钥,并且a与m互质,b为另一密钥,为任意数
解密函数:x = a^-1 (y - b) (mod m) , a^-1 为a 的逆元,在用其他语言实现求逆元时需要注意mod 取整问题;
参考代码如下,
#coding = utf-8 import math CryptoText = '' PlainText = '' txt = '' a,b,m=0,0,0 # 加密 def encode(): global a,b,CryptoText,txt if math.gcd(26,a) == 1: for i in txt: tmp = a * (ord(i)-97) + b CryptoText += chr((tmp % m) + 97) print("[+]密文为----->",CryptoText) return 0 else: print("[-]加密失败,密钥 a 与 26 不互质,请重新输入a") return 1 # 求乘法逆元 def extendEdeuclid(): global a,m x1,x2,x3 = 1,0,m y1,y2,y3 = 0,1,a while True: if y3 == 0 : return 0 if y3 == 1 : if y2<0: y2 = m+y2 return y2 q = int(x3/y3) t1,t2,t3 = x1-q*y1, x2-q*y2, x3-q*y3 x1,x2,x3 = y1,y2,y3 y1,y2,y3 = t1,t2,t3 # 解密 def decode(): global PlainText,CryptoText,a,b,m tmp = extendEdeuclid() if tmp != 0: for i in CryptoText: PlainText += chr(tmp * (ord(i)-97-b) % m + 97) print("[+]解密得到----->",PlainText) return 0 else: print("[-]解密失败,密钥",a,"与",m,"没有逆元,请重新输入密钥a") return 1 if __name__ == '__main__': print(''' ▄████████ ▄████████ ▄████████ ▄█ ███▄▄▄▄ ▄████████ ▄████████ ▄█ ▄███████▄ ▄█ █▄ ▄████████ ▄████████ ███ ███ ███ ███ ███ ███ ███ ███▀▀▀██▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ █▀ ███▌ ███ ███ ███ █▀ ███ █▀ ███▌ ███ ███ ███ ███ ███ █▀ ███ ███ ███ ███ ▄███▄▄▄ ▄███▄▄▄ ███▌ ███ ███ ▄███▄▄▄ ███ ███▌ ███ ███ ▄███▄▄▄▄███▄▄ ▄███▄▄▄ ▄███▄▄▄▄██▀ ▀███████████ ▀▀███▀▀▀ ▀▀███▀▀▀ ███▌ ███ ███ ▀▀███▀▀▀ ███ ███▌ ▀█████████▀ ▀▀███▀▀▀▀███▀ ▀▀███▀▀▀ ▀▀███▀▀▀▀▀ ███ ███ ███ ███ ███ ███ ███ ███ █▄ ███ █▄ ███ ███ ███ ███ ███ █▄ ▀███████████ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ █▀ ▀█ █▀ ██████████ ████████▀ █▀ ▄████▀ ███ █▀ ██████████ ███ ███ ███ ███ is insteresting ! 编码系统为26小写字母 ''') a,b,m=int(input("请输入密钥a: ")),int(input("请输入密钥b(任意正整数): ")),input("请输入编码数m[不输默认26]:") if m == '': m = 26 else: m = int(m) txt=input("请输入明文:") while(encode()): a = int(input("请输入密钥a: ")) while(decode()): a = int(input("请输入密钥a: "))