用python编写凯撒加密解密
时间: 2024-09-19 20:06:31 浏览: 78
python实现凯撒密码加密解密
5星 · 资源好评率100%
凯撒加密(Caesar Cipher),又称为移位密码,是一种简单的替换式加密技术。在Python中实现凯撒加密的基本步骤如下:
1. **加密**:
```python
def caesar_encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
# A-Z变为Z-Y+shift,a-z变为z-x+shift(注意大写和小写的处理)
shifted = ord(char) + shift % 26
if char.isupper():
encrypted_text += chr(((shifted - 65) % 26) + 65)
else:
encrypted_text += chr(((shifted - 97) % 26) + 97)
else:
encrypted_text += char
return encrypted_text
# 示例
plaintext = "Hello, World!"
shift = 3
encrypted = caesar_encrypt(plaintext, shift)
print(f"Encrypted text: {encrypted}")
```
2. **解密**:
```python
def caesar_decrypt(encrypted_text, shift):
return caesar_encrypt(encrypted_text, -shift)
decrypted = caesar_decrypt(encrypted, shift)
print(f"Decrypted text: {decrypted}")
```
阅读全文