python凯撒密码加密解密
时间: 2023-07-25 17:42:46 浏览: 122
python实现凯撒密码加密解密
5星 · 资源好评率100%
以下是Python实现凯撒密码加密和解密的示例代码:
加密:
```python
def caesar_encrypt(plain_text, shift):
"""
凯撒密码加密
:param plain_text: 明文
:param shift: 移位数
:return: 密文
"""
cipher_text = ''
for char in plain_text:
if char.isalpha():
cipher_text += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
else:
cipher_text += char
return cipher_text
```
解密:
```python
def caesar_decrypt(cipher_text, shift):
"""
凯撒密码解密
:param cipher_text: 密文
:param shift: 移位数
:return: 明文
"""
plain_text = ''
for char in cipher_text:
if char.isalpha():
plain_text += chr((ord(char) - ord('a') - shift + 26) % 26 + ord('a'))
else:
plain_text += char
return plain_text
```
使用示例:
```python
plain_text = 'hello world'
shift = 3
cipher_text = caesar_encrypt(plain_text, shift)
print(cipher_text) # khoor zruog
decrypted_text = caesar_decrypt(cipher_text, shift)
print(decrypted_text) # hello world
```
注:以上代码中,只考虑了小写字母的情况。如果需要加密或解密大写字母或其他字符,请自行修改代码。
阅读全文