凯撒算法python代码
时间: 2023-05-24 21:01:28 浏览: 61
以下是凯撒算法的Python代码:
```python
def caesar_cipher(plaintext, shift):
"""
Encrypts plaintext using the Caesar cipher with a given shift.
plaintext: A string containing the plaintext to be encrypted.
shift: An integer indicating the number of positions to shift the characters in the plaintext.
Returns a string containing the encrypted ciphertext.
"""
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ciphertext += chr((ord(char) + shift - 65) % 26 + 65)
else:
ciphertext += chr((ord(char) + shift - 97) % 26 + 97)
else:
ciphertext += char
return ciphertext
```
该函数将给定的明文使用凯撒密码进行加密,其中 shift 参数表示字符需要向右移动的字符数。该函数将返回加密后的密文。
请注意,凯撒密码是一种简单的替换密码,容易被破解,因此在实际应用中不建议使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)