python凯撒密码加密解密
时间: 2023-05-27 07:06:26 浏览: 180
以下是Python实现的凯撒密码加密解密的示例代码:
```python
def encrypt_caesar(plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
ascii_code = ord(char) + shift
if char.isupper():
if ascii_code > ord('Z'):
ascii_code -= 26
elif ascii_code < ord('A'):
ascii_code += 26
elif char.islower():
if ascii_code > ord('z'):
ascii_code -= 26
elif ascii_code < ord('a'):
ascii_code += 26
ciphertext += chr(ascii_code)
else:
ciphertext += char
return ciphertext
def decrypt_caesar(ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
ascii_code = ord(char) - shift
if char.isupper():
if ascii_code > ord('Z'):
ascii_code -= 26
elif ascii_code < ord('A'):
ascii_code += 26
elif char.islower():
if ascii_code > ord('z'):
ascii_code -= 26
elif ascii_code < ord('a'):
ascii_code += 26
plaintext += chr(ascii_code)
else:
plaintext += char
return plaintext
# 示例用法
plaintext = "hello world"
shift = 3
ciphertext = encrypt_caesar(plaintext, shift)
print(ciphertext) # "khoor zruog"
plaintext = decrypt_caesar(ciphertext, shift)
print(plaintext) # "hello world"
```
在上面的代码中,我们定义了两个函数`encrypt_caesar`和`decrypt_caesar`,分别用于加密和解密凯撒密码。这些函数都需要两个参数:明文(或密文)和移动的位数。
加密函数的实现很简单:对于输入的每个字符,我们检查它是否是字母。如果它是一个字母,我们将其ASCII码值加上移位数,得到密文中对应字符的ASCII码值。如果超出了字母表的范围,我们需要将其循环回到字母表的另一端。最后,我们将加密后的字符添加到密文中。
解密函数的实现与加密函数类似,只是我们将移位数减去,以反向移动字符。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)