编程实现凯撒算法,能够实现加密和解密
时间: 2023-12-22 09:04:11 浏览: 24
凯撒算法是一种经典的密码算法,它可以对明文进行加密和解密,方法是将明文中的每个字母向后移动指定的位数,这个位数称为偏移量。以下是一个简单的 Python 代码示例:
```python
def caesar_encrypt(plaintext, offset):
ciphertext = ''
for char in plaintext:
if char.isalpha():
# 处理大写字母
if char.isupper():
ciphertext += chr((ord(char) - ord('A' ) + offset) % 26 + ord('A'))
# 处理小写字母
else:
ciphertext += chr((ord(char) - ord('a' ) + offset) % 26 + ord('a'))
else:
ciphertext += char
return ciphertext
def caesar_decrypt(ciphertext, offset):
plaintext = ''
for char in ciphertext:
if char.isalpha():
# 处理大写字母
if char.isupper():
plaintext += chr((ord(char) - ord('A' ) - offset) % 26 + ord('A'))
# 处理小写字母
else:
plaintext += chr((ord(char) - ord('a' ) - offset) % 26 + ord('a'))
else:
plaintext += char
return plaintext
```
其中,`caesar_encrypt` 函数用于加密明文,`plaintext` 是要加密的字符串,`offset` 是偏移量,返回加密后的密文。`caesar_decrypt` 函数用于解密密文,`ciphertext` 是要解密的字符串,`offset` 是偏移量,返回解密后的明文。
例如,偏移量为 3,明文为 "hello",加密后的密文为 "khoor",解密密文 "khoor" 后得到的明文为 "hello"。