酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Python 实现普莱费尔格密码加密:密钥 “NETWORK” 加密明文 “we will have a meeting”

以下是一个使用 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) ``` ######[AI写代码神器 | 513点数解答 | 2024-09-24 18:40:04]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]