加密的基本流程:希尔密码(Hill)使用每个字母在字母表中的顺序作为其对应的数字,即 A=0,B=1,C=2 等,然后将明文转化为 n 维向量,跟一个 n × n 的矩阵相乘,再将得出的结果模 26。注意用作加密的矩阵(即密匙)在 Zn26Z26n 必须是可逆的,否则就不可能解码。只有矩阵的行列式和 26 互质,才是可逆的。
deftext_to_list(text): # 明文转数字列表 text_list = [] for i in text: for key,value in alphabet.items(): if value == i: text_list.append(key) # print("明文转换数字完成") return text_list # print(text_list)
deftext_to_list(text): # 明文转数字列表 text_list = [] for i in text: for key,value in alphabet.items(): if value == i: text_list.append(key) # print("明文转换数字完成") return text_list # print(text_list)
defciphertext_to_text(cirphertext): # 数字密文转换为字符串密文 cirphertext = cirphertext % 26 # print(f"取余后的矩阵{cirphertext}") key_text = "" for element in cirphertext: key_text += alphabet[int(element)] print(f"转换为密文:{key_text}") return key_text
defdecrypt(ciphertext, key): # 解密函数 传入参数分别为:带解密的字符串和加密密钥 # 计算密钥矩阵的逆矩阵 inv_key = numpy.linalg.inv(key) # 字符串转数字列表 num_list = [] for i in ciphertext: for key, value in alphabet.items(): if value == i: num_list.append(key)
# 将数字转换回字母 decrypted_text = "" for element in decrypted: element = (element + 2600) % 26# +2600是为了解决和解密矩阵相乘后有负数的情况 decrypted_text += alphabet[int(element)]