面向对象Caesar密码优化:无需chr()与ord()实现加解密
凯撒密码面向对象实现优化方案
优化后的代码实现
class CaesarCipher: def __init__(self, key): # 标准化密钥:将密钥约束在0-25范围内,自动处理超大/负数密钥 self.key = key % 26 self.lowercase = 'abcdefghijklmnopqrstuvwxyz' self.uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def encrypt(self, text): result = [] for char in text: if char in self.lowercase: idx = self.lowercase.index(char) new_idx = (idx + self.key) % 26 result.append(self.lowercase[new_idx]) elif char in self.uppercase: idx = self.uppercase.index(char) new_idx = (idx + self.key) % 26 result.append(self.uppercase[new_idx]) else: # 非字母字符直接保留,不参与移位 result.append(char) return ''.join(result) def decrypt(self, text): # 解密等价于反向移位,通过负密钥取模实现 decrypt_key = (-self.key) % 26 result = [] for char in text: if char in self.lowercase: idx = self.lowercase.index(char) new_idx = (idx + decrypt_key) % 26 result.append(self.lowercase[new_idx]) elif char in self.uppercase: idx = self.uppercase.index(char) new_idx = (idx + decrypt_key) % 26 result.append(self.uppercase[new_idx]) else: result.append(char) return ''.join(result)
关键优化点说明
- 类设计规范调整:初始化仅接收密钥,加解密方法独立接收文本参数。这样同一个
CaesarCipher实例可复用处理多个文本,符合面向对象的单一职责与复用性要求。 - 摒弃
chr()/ord():通过预定义大小写字母表字符串,利用index()获取字符位置、索引访问实现字符移位,完全替代ASCII码转换逻辑,代码更直观。 - 密钥26的逻辑验证:由于字母表长度为26,
26 % 26 = 0,移位26位等价于无移位,加解密结果与原文本一致,这是符合凯撒密码逻辑的正确表现。初始化时的key % 26处理也自动解决了密钥为26、52等倍数的情况。
使用示例
# 测试密钥26的情况 cipher = CaesarCipher(26) original = "Hello, Stack Overflow!" encrypted = cipher.encrypt(original) decrypted = cipher.decrypt(encrypted) print(f"原文本: {original}") print(f"加密后: {encrypted}") # 输出与原文本完全一致 print(f"解密后: {decrypted}") # 输出与原文本完全一致 # 测试常规密钥 cipher_3 = CaesarCipher(3) test_text = "Test Message" encrypted_3 = cipher_3.encrypt(test_text) print(f"加密后: {encrypted_3}") # 输出 "Whvw Phvvdjh" print(f"解密后: {cipher_3.decrypt(encrypted_3)}") # 输出 "Test Message"
内容的提问来源于stack exchange,提问作者molly kris
相关产品推荐
相关产品推荐

