1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import numpy
alphabet = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z'}
key_list = numpy.array([[6, 13, 20], [24, 16, 17], [1, 10, 15]]) key_list_f = numpy.array([[8, 21, 21], [5, 8, 12], [10, 21, 8]])
def encrypt(text_list): list_t = [] for ch in text_list: for key, value in alphabet.items(): if ch == value: list_t.append(key) while (len(list_t) % 3) != 0: list_t.append(0)
list_ts = [] for i in range(0, len(list_t), 3): list_ts.append(list_t[i:i+3]) list_n = [] for List in list_ts: list_x = ((numpy.array(List) @ key_list) % 26).tolist() list_n.append(list_x)
list_str = "" for its in list_n: for it in its: list_str += alphabet[it]
print(f"密文为:{list_str}")
def decrypt(ciphertext, n): num_list = [] for i in ciphertext: for key, value in alphabet.items(): if value == i: num_list.append(key) while (len(num_list) % 3) != 0: num_list.append(0) chunks = [] for i in range(0, len(num_list), 3): chunks.append(num_list[i:i+3]) decrypted_blocks = [] for chunk in chunks: decrypted = ((numpy.array(chunk) @ key_list_f) % 26).tolist() decrypted_blocks.append(decrypted)
list_str = "" for nums in decrypted_blocks: for num in nums: if num in alphabet: list_str += alphabet[num]
list_str = list_str[:int(n)] print(list_str)
if __name__ == "__main__": while True: print("-------------------------------------Hill加密系统----------------------------------------------") print("1.加密") print("2.解密") print("3.退出") choose = input("请输入:") if choose == '1': text = input("输入待加密的三位小写字母字符串:") encrypt(text) elif choose == '2': key_n = input("输入待解密的字符串数量:") key_text = input("输入待解密的小写字母密文:") decrypt(key_text, key_n) elif choose == '3': print("感谢使用,期待下次使用!") break else: print("---------------------------------------非法输入!----------------------------------------------")
|