凯撒密码加密算法python
时间: 2023-06-12 12:05:57 浏览: 64
凯撒密码是一种简单的替换密码,它将明文中的每个字母替换为字母表中固定数量的字母后进行加密。以下是使用Python实现凯撒密码加密算法的示例代码:
```python
def caesar_cipher_encrypt(plain_text, shift):
cipher_text = ""
for char in plain_text:
if char.isalpha():
# 将字符转换为ASCII码,并且减去65或97,使A/a对应0,B/b对应1,以此类推
char_code = ord(char) - 65 if char.isupper() else ord(char) - 97
# 将字符偏移shift个位置,并且对26取模,避免偏移超出字母表范围
shifted_code = (char_code + shift) % 26
# 将偏移后的字符编码再转换为字符
shifted_char = chr(shifted_code + 65 if char.isupper() else shifted_code + 97)
cipher_text += shifted_char
else:
cipher_text += char
return cipher_text
```
示例代码中的 `plain_text` 是要加密的明文,`shift` 是偏移量,即要将明文中的每个字母偏移的位置数。函数返回加密后的密文。
例如,将明文 "hello world" 使用偏移量 3 进行加密:
```python
>>> caesar_cipher_encrypt("hello world", 3)
'khoor zruog'
```
加密后的密文为 "khoor zruog"。