# 创建字母表 defcreatLetterList(): letterList = [] for i inrange(ord("a"), ord("z") + 1): letterList.append(chr(i)) return letterList
# 判断互质 defjudgeCoPrime(a, b): # 求最大公因数 defmaxCommonFactor(m, n): result = 0 while m % n > 0: result = m % n m = n n = result return result if maxCommonFactor(a, b) == 1: returnTrue returnFalse
# 求逆元 defgetInverse(a, b): # 扩展的欧几里得 defextGcd(a_, b_, arr): if b_ == 0: arr[0] = 1 arr[1] = 0 return a_ g = extGcd(b_, a_ % b_, arr) t = arr[0] arr[0] = arr[1] arr[1] = t - int(a_ / b_) * arr[1] return g # 求a模b的乘法逆x arr = [0,1,] gcd = extGcd(a, b, arr) if gcd == 1: return (arr[0] % b + b) % b else: return -1
# 加密 defencrypt(massage, keyOne, keyTwo): massageList = [] # 存储明文字母转换的对应数字 cipherTextList = [] # 密文列表 letterList = creatLetterList() # 字母列表 for i in massage: massageList.append(letterList.index(i)) for i in massageList: cipherTextList.append((keyOne * i + keyTwo) % 26) return cipherTextList
# 解密 defdecrypt(cipherTextList, keyOne, keyTwo): plainTextList = [] letterList = creatLetterList() # 求keyOne对于26的逆元 inverse_keyOne = getInverse(keyOne, 26) for i in cipherTextList: plainTextList.append((inverse_keyOne * (i - keyTwo)) % 26) for i inrange(len(plainTextList)): plainTextList[i] = letterList[plainTextList[i]] # 将列表整合为字符串 plianText = "".join(plainTextList) return plianText