凯撒加密的python代码
时间: 2023-12-15 20:31:19 浏览: 77
以下是凯撒加密的Python代码,其中包括两种实现方式:
1. 加减法运算实现:
```python
# 加减法运算实现凯撒加密
def caesar_encrypt(text, key):
result = ""
# 遍历明文中的每个字符
for i in range(len(text)):
char = text[i]
# 如果是大写字母
if char.isupper():
result += chr((ord(char) + key - 65) % 26 + 65)
# 如果是小写字母
elif char.islower():
result += chr((ord(char) + key - 97) % 26 + 97)
# 如果是其他字符
else:
result += char
return result
```
2. 取模运算及零下索引实现:
```python
# 取模运算及零下索引实现凯撒加密
def caesar_encrypt_v2(text, key):
result = ""
# 遍历明文中的每个字符
for i in range(len(text)):
char = text[i]
# 如果是大写字母
if char.isupper():
result += chr((ord(char) - 65 + key) % 26 + 65)
# 如果是小写字母
elif char.islower():
result += chr((ord(char) - 97 + key) % 26 + 97)
# 如果是其他字符
else:
result += char
return result
```
使用示例:
```python
text = "hello world"
key = 3
encrypted_text = caesar_encrypt(text, key)
print("加减法运算实现加密结果:", encrypted_text) # 输出:khoor zruog
encrypted_text_v2 = caesar_encrypt_v2(text, key)
print("取模运算及零下索引实现加密结果:", encrypted_text_v2) # 输出:khoor zruog
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)