以下是一个使用 Python 实现普莱费尔格密码加密的示例代码: ```python import string def generate_matrix(key): # 去除重复字母并将字母转换为大写 key = ''.join(dict.fromkeys(key.upper())) alphabet = string.ascii_uppercase matrix = [] for char in key: if char not in matrix: matrix.append(char) for char in alphabet: if char not in matrix: matrix.append(char) return [matrix[i:i + 5] for i in range(0, 25, 5)] def find_pos(matrix, char): for i in range(5): for j in range(5): if matrix[i][j] == char: return i, j def encrypt(plaintext, key): matrix = generate_matrix(key) plaintext = plaintext.replace(" ", "").upper() ciphertext = "" i = 0 while i < len(plaintext): char1 = plaintext[i] if i + 1 == len(plaintext): char2 = 'X' else: char2 = plaintext[i + 1] if char1 == char2: char2 = 'X' i += 1 row1, col1 = find_pos(matrix, char1) row2, col2 = find_pos(matrix, char2) if row1 == row2: ciphertext += matrix[row1][(col1 + 1) % 5] ciphertext += matrix[row2][(col2 + 1) % 5] elif col1 == col2: ciphertext += matrix[(row1 + 1) % 5][col1] ciphertext += matrix[(row2 + 1) % 5][col2] else: ciphertext += matrix[row1][col2] ciphertext += matrix[row2][col1] i += 2 return ciphertext key = "NETWORK" plaintext = "we will have a meeting" ciphertext = encrypt(plaintext, key) print("密文:", ciphertext) ``` [2024-09-24 18:40:04 | AI写代码神器 | 513点数解答]