编写一个解码凯撒密码的程序
时间: 2023-08-08 16:07:34 浏览: 46
好的,以下是一个解码凯撒密码的 Python 程序,假设密文已知并且密钥为 3:
```python
def caesar_decrypt(ciphertext, key):
plaintext = ""
for char in ciphertext:
if char.isalpha():
ascii_code = ord(char)
shifted_ascii_code = ascii_code - key
if char.isupper():
if shifted_ascii_code < 65:
shifted_ascii_code += 26
elif shifted_ascii_code > 90:
shifted_ascii_code -= 26
elif char.islower():
if shifted_ascii_code < 97:
shifted_ascii_code += 26
elif shifted_ascii_code > 122:
shifted_ascii_code -= 26
plaintext += chr(shifted_ascii_code)
else:
plaintext += char
return plaintext
```
使用方法:
```python
ciphertext = "L oryh brx zrxog iluvw wkh shuiruph lw"
key = 3
plaintext = caesar_decrypt(ciphertext, key)
print(plaintext) # I love you should give the secret away
```
程序首先定义了一个名为 `caesar_decrypt` 的函数,该函数接受两个参数:密文和密钥。函数通过遍历密文中的每个字符,将其转换为 ASCII 码,并将其减去密钥。然后,它检查字符是否是字母,并在需要时将其转换回字母。最后,它将解密后的字符添加到明文字符串中。
在上面的示例中,我们将密文和密钥传递给 `caesar_decrypt` 函数,并将返回值打印到控制台上,以显示解密后的明文。