# 字符串转单字符列表,再转为数字序列便于计算 def stoc(str): ch_list = [] for i in str: ch_list.append(i) return [ord(i)-65 for i in ch_list]
# Int to Chr # 将数字序列还原成大写字母序列 def itoc(list_int): A = [chr(i+65) for i in list_int] ch = "" for i in A: ch += i return ch
# 计算密文序列 def Encrypt(Message,k,n): print('>>>使用加法密码算法进行加密(k={}, n={})'.format(k,n)) return itoc([i+k%n for i in stoc(Message)])
# 计算明文序列 def Decrypt(Ciphertext,k,n): # 解密方式1:通过构建密码表进行查表解密 # 解密方式2:通过加密逆运算计算明文 DecryptionType = 2 if(DecryptionType == 1): print('>>>构建密码表:') A = [i for i in range(0,n)] print('>>>明文字母表:{}'.format(itoc(A))) B = Encrypt(itoc(A),k,n) print('>>>密文字母表:{}'.format(B)) CiphertextTables = dict(zip(B,A)) print('>>>构建密码表进行查表解密') return itoc([CiphertextTables[i] for i in Ciphertext]) else: print('>>>通过加密逆运算进行解密(k的逆元为:{})'.format(-k)) return itoc([c-k+n %n for c in stoc(Ciphertext)])
if __name__=='__main__': # 当前仅支持大写字母串 A = ('ABCDEF') print('输入的明文字符串为:{}'.format(A)) B = Encrypt(A,7,26) print('加密后的密文:{}'.format(B)) C = Decrypt(B,7,26) print('解密后的明文:{}'.format(C))