使用自定义字母表解密密文时遇到问题(Python)
问题:自定义字母表加密正常,但解密功能失效
已实现基于自定义字母表的加密功能,运行正常,但解密时无法还原明文——要么返回加密后的消息,要么返回错误的变体。尝试将解密逻辑里的+改成-还会报错,原以为这是正确的实现方式。
原代码如下:
alphabet = "abcdefghijklmnopqrstuvwxyz" key = "zjrekydnqoluaxmicvpgtfbhws" def decryptMessage(ciphertext, key): plaintext = "" for char in ciphertext: if alphabet.find(char) < +1: plaintext += key[alphabet.find(char)] else: plaintext += char return plaintext def encryptMessage(plaintext, key): ciphertext = "" for char in plaintext: if alphabet.find(char) > -1: ciphertext += key[alphabet.find(char)] else: ciphertext += char return ciphertext message = input("Type a message to encrypt: ") encrypted = encryptMessage(message, key) decrypted = decryptMessage(encrypted, key) print("Plaintext message: " + message) print("Encrypted message: " + encrypted) print("Decrypted message: " + decrypted)
错误原因分析
- 解密逻辑完全倒置:加密是用标准字母表的索引取key对应字符,解密需要反向操作——用key的索引取标准字母表的字符。原解密函数仍在拿标准字母表的索引去取key字符,等于重复执行加密,自然返回加密消息。
- 判断条件逻辑错误:
alphabet.find(char) < +1仅能匹配到字符a或找不到的字符,完全不符合解密时需要匹配key中字符的需求。 - 改
+为-报错的原因:当字符不在标准字母表中时,alphabet.find(char)返回-1,减1后得到-2,用负数索引访问字符串会触发索引越界错误。
修正后的代码
alphabet = "abcdefghijklmnopqrstuvwxyz" key = "zjrekydnqoluaxmicvpgtfbhws" def decryptMessage(ciphertext, key): plaintext = "" for char in ciphertext: # 获取当前密文字符在key中的索引 key_index = key.find(char) # 找到则用该索引取标准字母表对应字符(解密) if key_index > -1: plaintext += alphabet[key_index] # 非字母字符直接保留 else: plaintext += char return plaintext def encryptMessage(plaintext, key): ciphertext = "" for char in plaintext: alpha_index = alphabet.find(char) if alpha_index > -1: ciphertext += key[alpha_index] else: ciphertext += char return ciphertext message = input("Type a message to encrypt: ") encrypted = encryptMessage(message, key) decrypted = decryptMessage(encrypted, key) print("Plaintext message: " + message) print("Encrypted message: " + encrypted) print("Decrypted message: " + decrypted)
核心逻辑说明
- 加密:遍历明文,将标准字母表中的字符替换为key对应位置的字符,非字母字符直接保留。
- 解密:遍历密文,将key中的字符替换为标准字母表对应位置的字符,完成明文还原,非字母字符直接保留。
内容的提问来源于stack exchange,提问作者Tydus X
相关产品推荐
相关产品推荐

