P1914 小书童——凯撒密码
时间: 2023-12-01 20:04:50 浏览: 54
P1914 小书童——凯撒密码是一道经典的密码学题目,题目要求是将一段明文按照凯撒密码的方式进行加密,输出密文。凯撒密码是一种简单的加密方式,它将明文中的每个字母按照一定的偏移量进行移位,得到密文。偏移量可以是任意的整数,一般情况下偏移量是3。例如,明文中的字母A经过加密后变成了D,字母B变成了E,以此类推。加密后的密文可以通过将每个字母按照偏移量进行反向移位得到明文。
下面是一种简单的凯撒密码加密方式的实现方法:
```python
def caesar_cipher(plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ciphertext += chr((ord(char) - 65 + shift) % 26 + 65)
else:
ciphertext += chr((ord(char) - 97 + shift) % 26 + 97)
else:
ciphertext += char
return ciphertext
```
其中,plaintext是明文,shift是偏移量,ciphertext是密文。这个实现方法可以将明文中的每个字母按照偏移量进行移位,得到密文。
相关问题
凯撒密码——解密 python代码
以下是一个简单的凯撒密码解密的 Python 代码示例:
```python
def caesar_decrypt(ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.islower():
plaintext += chr((ord(char) - shift - 97) % 26 + 97)
else:
plaintext += chr((ord(char) - shift - 65) % 26 + 65)
else:
plaintext += char
return plaintext
```
其中,`ciphertext` 是加密后的文本,`shift` 是密钥的移位数。解密过程就是将每个字符向左移动 `shift` 个位置,并将结果拼接起来。
注意,这个代码只适用于英文字母的加密解密。如果需要解密其他字符的凯撒密码,需要进行相应的修改。
p ython 凯撒密码加密
以下是 Python 中实现凯撒密码加密的代码:
```python
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
# 对字母进行移位操作
new_char_code = ord(char) + shift
if char.isupper():
if new_char_code > ord('Z'):
new_char_code -= 26
elif new_char_code < ord('A'):
new_char_code += 26
else:
if new_char_code > ord('z'):
new_char_code -= 26
elif new_char_code < ord('a'):
new_char_code += 26
result += chr(new_char_code)
else:
result += char
return result
```
其中,`text` 是要加密的文本,`shift` 是移动的位数,正数表示右移,负数表示左移。函数返回加密后的文本。例如,使用 `caesar_cipher('hello world', 3)` 进行加密,得到的结果是 `khoor zruog`。