python 凯撒密码
时间: 2023-06-19 12:09:25 浏览: 61
凯撒密码是一种简单的加密方式,它将每个字母按照一定的偏移量进行替换,从而实现加密。下面是一个 Python 实现凯撒密码的示例代码:
```python
def caesar_cipher(text, shift):
"""
实现凯撒密码的加密和解密
:param text: 明文或密文
:param shift: 偏移量
:return: 密文或明文
"""
cipher_text = ""
for char in text:
# 如果是大写字母
if char.isupper():
cipher_text += chr((ord(char) + shift - 65) % 26 + 65)
# 如果是小写字母
elif char.islower():
cipher_text += chr((ord(char) + shift - 97) % 26 + 97)
else:
cipher_text += char
return cipher_text
```
使用示例:
```python
text = "Hello, World!"
shift = 3
encrypted_text = caesar_cipher(text, shift)
print("加密后的文本:", encrypted_text)
decrypted_text = caesar_cipher(encrypted_text, -shift)
print("解密后的文本:", decrypted_text)
```
输出结果:
```
加密后的文本: Khoor, Zruog!
解密后的文本: Hello, World!
```
注意:这种加密方式非常简单,容易被破解,不适合用于保护重要信息。