凯撒密码python
时间: 2023-07-25 20:14:08 浏览: 38
以下是一个简单的凯撒密码加密和解密的Python代码示例:
```python
def encrypt(text, shift):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
result += char
return result
def decrypt(text, shift):
return encrypt(text, 26 - shift)
# 示例
text = "Hello, World!"
shift = 3
encrypted_text = encrypt(text, shift)
print("加密后的文本:", encrypted_text)
decrypted_text = decrypt(encrypted_text, shift)
print("解密后的文本:", decrypted_text)
```
代码解释:
- `encrypt` 函数接受两个参数:要加密的文本和加密的偏移量。它遍历文本中的每个字符,并对每个字符进行加密操作。如果是大写字母,则将其转换为其 ASCII 码并用偏移量进行加密,然后将其转换回字符。小写字母和其他字符的加密方式相同。加密后的字符被添加到 `result` 变量中,然后返回 `result`。
- `decrypt` 函数接受两个参数:要解密的文本和加密的偏移量。它利用凯撒密码的特性,将加密偏移量转换为解密偏移量,并将其传递给 `encrypt` 函数进行解密操作。
- 示例中,我们将字符串 "Hello, World!" 进行加密,偏移量为 3。输出加密后的文本和解密后的文本。
请注意,这只是一个简单的示例代码,并且并不是完全安全的密码算法。在实际应用中,我们需要使用更强大的密码算法来保护数据的安全。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)