实现古典密码中的移位密码。要求用户自己输入明文密钥等参数实现移位密码的加解密,并恢复以下用移位密码加密的密文片段:
zvtlvmbznlakpwwlkpumshazvtlpuzhapuzvtlpunsvzzibalclyfvujlpuhdopslfvbmpukzvtlvuldovpzpypklzjluahukdolufvbkvuvaopundpsslclyjvtwhyl
所对应的明文和密钥。
解决方案如下:
❶设计思路
1. 加密函数,根据用户输入的明文密钥等实现移位密码的加密
2. 解密函数,根据密文和偏移量实现移位密码的解密
3. 主函数
用户输入明文和密钥
加密函数
用户输入待解密的密文
解密函数
4. 恢复所给默认密文片段
❷实验内容和代码
def shiftEncrypt(plaintext, key): ciphertext = "" for c in plaintext: if c.isalpha(): if c.isupper(): ciphertext += chr((ord(c) - 65 + key) % 26 + 65) else: ciphertext += chr((ord(c) - 97 + key) % 26 + 97) else: ciphertext += c return ciphertext def shiftDecrypt(ciphertext, key): plaintext = "" for c in ciphertext: if c.isalpha(): if c.isupper(): plaintext += chr((ord(c) - 65 - key) % 26 + 65) else: plaintext += chr((ord(c) - 97 - key) % 26 + 97) else: plaintext += c return plaintext def recoverPlaintext(ciphertext): for key in range(26): decrypted_text = shiftDecrypt(ciphertext, key) print(f"使用密钥{key}解密后的明文为:{decrypted_text}") if __name__ == "__main__": plaintext = input("请输入明文") key = int(input("请输入密钥")) print(shiftEncrypt(plaintext,key)) ciphertext = input("请输入密文") key = int(input("请输入偏移量")) print(shiftDecrypt(ciphertext,key)) print("示例解密") input() ciphertext = ("zvtlvmbznlakpwwlkpumshazvtlpuzhapuzvtlp" "unsvzzibalclyfvujlpuhdopslfvbmpukzvtlvu" "ldovpzpypklzjluahukdolufvbkvuvaopundpss" "lclyjvtwhyl") recoverPlaintext(ciphertext)
❸实验结果
❹本题中遇到的问题及解决过程
问题
情况分析不全面,代码不容错,比如明文输入数字等情况
解决
加一些判断和容错,数字不进行位移