凯撒密码python
时间: 2023-07-25 21:14:13 浏览: 44
凯撒密码是一种简单的加密算法,可以通过将明文中的每个字符按照一定的规则进行替换来实现加密。在Python中,可以使用以下代码实现凯撒密码的加密和解密:
```python
def encrypt(plaintext, key):
ciphertext = ""
for char in plaintext:
if char.isalpha():
shifted = chr((ord(char) - ord('a') + key) % 26 + ord('a'))
ciphertext += shifted
else:
ciphertext += char
return ciphertext
def decrypt(ciphertext, key):
plaintext = ""
for char in ciphertext:
if char.isalpha():
shifted = chr((ord(char) - ord('a') - key) % 26 + ord('a'))
plaintext += shifted
else:
plaintext += char
return plaintext
```
其中,`encrypt`函数用于加密明文,`decrypt`函数用于解密密文。`key`参数表示加密或解密时的偏移量,可以是任意整数。需要注意的是,这里的加密和解密算法是对字母表中的字符进行操作的,因此只能加密和解密字母,其他字符(如数字、标点符号等)会被保留原样。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)