python凯撒密码编写程序详解
时间: 2024-11-03 07:15:53 浏览: 82
凯撒密码是一种简单的替换加密技术,在这种加密中,明文中的每个字母按照固定的偏移量(通常是一个整数)向后移动字母表的位置,形成密文。在Python中编写一个基本的凯撒密码程序,你可以遵循以下步骤:
1. 定义一个函数`caesar_cipher`,它接受两个参数:原始字符串(plaintext)和偏移量(shift)。
2. 创建一个新的空字符串(ciphertext),用于存储加密后的结果。
3. 遍历输入的明文字母,如果是英文字符(区分大小写):
- 判断字母是否在字母表范围内(A-Z或a-z)。
- 使用ASCII码计算新的位置,例如,如果字母'A'加上偏移量3,新位置就是'A' + 3 = 'D'。
- 如果是大写字母,保持大写;如果是小写字母,转换为大写。
- 将新的字母添加到ciphertext中。
4. 对非字母字符不做处理,直接复制过去。
5. 返回加密后的密文。
以下是简单的Python代码示例:
```python
def caesar_cipher(plaintext, shift):
ciphertext = ""
for char in plaintext:
if 'a' <= char <= 'z':
new_char = chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
elif 'A' <= char <= 'Z':
new_char = chr(((ord(char) - ord('A') + shift) % 26) + ord('A'))
else:
new_char = char
ciphertext += new_char
return ciphertext
# 示例
plaintext = "Hello, World!"
shift = 3
encrypted_text = caesar_cipher(plaintext, shift)
print(f"Original text: {plaintext}")
print(f"Ciphered text: {encrypted_text}")
阅读全文
相关推荐


















