Python 凯撒密码
时间: 2024-03-28 11:35:07 浏览: 44
Python 凯撒密码是一种简单的加密算法,它通过将字母按照一定的偏移量进行替换来实现加密和解密的功能。具体来说,凯撒密码将明文中的每个字母都替换为字母表中向后(或向前)移动固定位置的字母。
下面是一个简单的Python代码示例,用于实现凯撒密码的加密和解密功能:
```python
def caesar_encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
if char.isupper():
encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
else:
encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
else:
encrypted_text += char
return encrypted_text
def caesar_decrypt(encrypted_text, shift):
decrypted_text = ""
for char in encrypted_text:
if char.isalpha():
if char.isupper():
decrypted_text += chr((ord(char) - 65 - shift) % 26 + 65)
else:
decrypted_text += chr((ord(char) - 97 - shift) % 26 + 97)
else:
decrypted_text += char
return decrypted_text
```
使用上述代码,你可以调用`caesar_encrypt`函数来加密明文,调用`caesar_decrypt`函数来解密密文。其中,`text`参数表示明文或密文,`shift`参数表示偏移量,正数表示向后移动,负数表示向前移动。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.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_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)