Python加密项目补全:实现用户输入字符串的Playfair等加密算法
加密项目算法实现
已修正的原代码问题
- 移除过严的
isalpha()输入校验,匹配现有替换密码对空格、标点的支持逻辑 - 补全RSA算法的选项列表,修正选项选择范围不覆盖全算法的问题
- 修正拼写错误:
Cypher改为Cipher、out of rage改为“输入超出范围”、移除打印语句里多余的换行前缀n
统一实现规则
所有算法均以message为入参,执行后依次输出原始消息、加密密文、解密还原结果,和已实现的替换密码逻辑保持一致。
完整可运行代码
import random import math # 通用字母表定义(与原实现保持一致) alphabet = 'abcdefghijklmnopqrstuvwxyz.,! ' key = 'nu.t!iyvxqfl,bcjrodhkaew spzgm' # -------------------------- 已实现的替换密码封装 -------------------------- def substitution_encrypt(plaintext, key, alphabet): keyMap = dict(zip(alphabet, key)) return ''.join(keyMap.get(c.lower(), c) for c in plaintext) def substitution_decrypt(cipher, key, alphabet): keyMap = dict(zip(key, alphabet)) return ''.join(keyMap.get(c.lower(), c) for c in cipher) def substitution_cipher(message): print(f"original message: {message}") cipher = substitution_encrypt(message, key, alphabet) print(f"cipher: {cipher}") deciphered = substitution_decrypt(cipher, key, alphabet) print(f"deciphered: {deciphered}") # -------------------------- Playfair 密码实现 -------------------------- def _generate_playfair_matrix(): # 演示用固定密钥,可替换为用户自定义输入 playfair_key = "MONARCHY" matrix = [] seen = set() for c in playfair_key.upper().replace('J', 'I'): if c not in seen and c.isalpha(): matrix.append(c) seen.add(c) for c in alphabet.upper().replace('J', 'I'): if c not in seen and c.isalpha(): matrix.append(c) seen.add(c) return [matrix[i*5:(i+1)*5] for i in range(5)] def _find_pos(matrix, char): char = char.upper().replace('J', 'I') for row in range(5): for col in range(5): if matrix[row][col] == char: return (row, col) return None def playfair_cipher(message): processed = [] non_alpha = [] for c in message.lower(): if c.isalpha(): processed.append(c.upper().replace('J', 'I')) else: non_alpha.append(('keep', len(processed), c)) i = 0 pairs = [] while i < len(processed): if i == len(processed)-1: pairs.append((processed[i], 'X')) i +=1 elif processed[i] == processed[i+1]: pairs.append((processed[i], 'X')) i +=1 else: pairs.append((processed[i], processed[i+1])) i +=2 matrix = _generate_playfair_matrix() cipher_parts = [] for a, b in pairs: r1, c1 = _find_pos(matrix, a) r2, c2 = _find_pos(matrix, b) if r1 == r2: cipher_parts.append(matrix[r1][(c1+1)%5]) cipher_parts.append(matrix[r2][(c2+1)%5]) elif c1 == c2: cipher_parts.append(matrix[(r1+1)%5][c1]) cipher_parts.append(matrix[(r2+1)%5][c2]) else: cipher_parts.append(matrix[r1][c2]) cipher_parts.append(matrix[r2][c1]) cipher_list = list(''.join(cipher_parts).lower()) for item in non_alpha: cipher_list.insert(item[1], item[2]) cipher = ''.join(cipher_list) alpha_cipher = [c for c in cipher if c.isalpha()] decrypt_pairs = [] i = 0 while i < len(alpha_cipher): decrypt_pairs.append((alpha_cipher[i], alpha_cipher[i+1])) i +=2 decipher_parts = [] for a, b in decrypt_pairs: r1, c1 = _find_pos(matrix, a) r2, c2 = _find_pos(matrix, b) if r1 == r2: decipher_parts.append(matrix[r1][(c1-1)%5]) decipher_parts.append(matrix[r2][(c2-1)%5]) elif c1 == c2: decipher_parts.append(matrix[(r1-1)%5][c1]) decipher_parts.append(matrix[(r2-1)%5][c2]) else: decipher_parts.append(matrix[r1][c2]) decipher_parts.append(matrix[r2][c1]) decipher_list = [c.lower() for c in ''.join(decipher_parts)] for item in non_alpha: decipher_list.insert(item[1], item[2]) deciphered = ''.join(decipher_list).replace('x', '') print(f"original message: {message}") print(f"cipher: {cipher}") print(f"deciphered: {deciphered}") # -------------------------- 置换密码实现 -------------------------- def transposition_cipher(message): col_num = 4 grid = [] for i in range(0, len(message), col_num): grid.append(message[i:i+col_num]) cipher = [] for col in range(col_num): for row in grid: if col < len(row): cipher.append(row[col]) cipher = ''.join(cipher) row_num = math.ceil(len(message)/col_num) decipher_grid = [[] for _ in range(row_num)] idx = 0 for col in range(col_num): for row in range(row_num): if idx < len(message): decipher_grid[row].append(cipher[idx]) idx +=1 deciphered = ''.join(''.join(row) for row in decipher_grid) print(f"original message: {message}") print(f"cipher: {cipher}") print(f"deciphered: {deciphered}") # -------------------------- 乘积密码实现 -------------------------- def product_cipher(message): cipher_after_sub = substitution_encrypt(message, key, alphabet) col_num = 4 grid = [] for i in range(0, len(cipher_after_sub), col_num): grid.append(cipher_after_sub[i:i+col_num]) cipher = [] for col in range(col_num): for row in grid: if col < len(row): cipher.append(row[col]) cipher = ''.join(cipher) row_num = math.ceil(len(cipher_after_sub)/col_num) decipher_grid = [[] for _ in range(row_num)] idx = 0 for col in range(col_num): for row in range(row_num): if idx < len(cipher_after_sub): decipher_grid[row].append(cipher[idx]) idx +=1 decipher_after_trans = ''.join(''.join(row) for row in decipher_grid) deciphered = substitution_decrypt(decipher_after_trans, key, alphabet) print(f"original message: {message}") print(f"cipher: {cipher}") print(f"deciphered: {deciphered}") # -------------------------- RSA 密码实现(轻量教学版) -------------------------- def rsa_cipher(message): p = 17 q = 19 n = p * q phi = (p-1)*(q-1) e = 5 d = 0 while (d * e) % phi != 1: d +=1 cipher_nums = [] for c in message.lower(): if c.isalpha(): m = ord(c) - ord('a') cipher_nums.append(str(pow(m, e, n))) else: cipher_nums.append(c) cipher = ' '.join(cipher_nums) deciphered_parts = [] for part in cipher.split(): if part.isdigit(): c = int(part) m = pow(c, d, n) deciphered_parts.append(chr(m + ord('a'))) else: deciphered_parts.append(part) deciphered = ''.join(deciphered_parts) print(f"original message: {message}") print(f"cipher: {cipher}") print(f"deciphered: {deciphered}") # -------------------------- 主交互流程 -------------------------- message = input("Enter the message you want encrypted: ") if len(message.strip()) == 0: print("User input is required in form of alphabet format") else: options = ( "1. Substitution Cipher", "2. Playfair Cipher", "3. Transposition Cipher", "4. Product Cipher", "5. RSA Cipher" ) print("Choose an encryption Cipher you would like to use:") for opt in options: print(opt) choice = int(input("Please reply with a number for choice of Cipher: ")) if 1 <= choice <=5: if choice ==1: substitution_cipher(message) elif choice ==2: playfair_cipher(message) elif choice ==3: transposition_cipher(message) elif choice ==4: product_cipher(message) else: rsa_cipher(message) else: print("The input choice you entered is out of range")
内容的提问来源于stack exchange,提问作者user10913773
相关产品推荐
相关产品推荐

