编写程序,输入一个字符串作为待加密的明文,然后输入一个整数作为凯撒加密算法的密钥,最后输出该字符串使用该密钥加密后的结果。
时间: 2023-05-22 20:01:50 浏览: 245
好的,以下是一个使用凯撒加密算法加密字符串的 Python 代码示例:
```python
def caesar_cipher(plaintext, key):
ciphertext = ""
for char in plaintext:
if char.isalpha():
shifted = (ord(char) - ord('a') + key) % 26 + ord('a')
ciphertext += chr(shifted)
else:
ciphertext += char
return ciphertext
plaintext = input("请输入待加密的明文:")
key = int(input("请输入凯撒加密算法的密钥:"))
ciphertext = caesar_cipher(plaintext, key)
print("加密后的结果为:", ciphertext)
```
例如,如果输入明文为 "hello world",密钥为 3,则输出的加密结果为 "khoor zruog"。
希望这个代码能够帮到您!
相关问题
编写程序,要求输入一个字符串,然后输入一个整数作为凯撒加密算法的密钥,然后输出该字符串加密后的结果。
以下是Python的实现代码:
```python
text = input("请输入要加密的字符串:")
key = int(input("请输入密钥:"))
encrypted_text = ""
for char in text:
if char.isalpha():
shifted_char = chr((ord(char) - ord('a') + key) % 26 + ord('a'))
encrypted_text += shifted_char
else:
encrypted_text += char
print("加密后的结果为:", encrypted_text)
```
该程序首先要求用户输入要加密的字符串和密钥。然后对于字符串中的每个字符,如果它是一个字母,则将其通过凯撒加密算法进行加密,否则将其保留原样。最后输出加密后的结果。
编与一个程序,要求出入一个字符串,并输入一个整数作为凯撒加密算法的秘钥,输出该字符串加密后的结果。
以下是 Python 语言实现的示例代码:
```python
def caesar_cipher(text, key):
"""
凯撒加密算法实现函数
"""
result = ""
for char in text:
if char.isalpha():
# 处理字母
shifted = ord(char) + key
if char.isupper():
if shifted > ord('Z'):
shifted -= 26
elif shifted < ord('A'):
shifted += 26
else:
if shifted > ord('z'):
shifted -= 26
elif shifted < ord('a'):
shifted += 26
result += chr(shifted)
else:
# 非字母字符直接拼接
result += char
return result
# 示例
text = input("请输入要加密的字符串:")
key = int(input("请输入秘钥(整数):"))
encrypted_text = caesar_cipher(text, key)
print("加密后的字符串为:", encrypted_text)
```
使用方法:
1. 运行程序
2. 输入要加密的字符串
3. 输入秘钥,秘钥为一个整数
4. 程序输出加密后的字符串
注意:
- 该实现默认只能处理英文字母,对于其他字符会直接拼接到结果中
- 加密后的字符串中,大写字母仍为大写字母,小写字母仍为小写字母。如果需要转换为统一大小写,可以在处理完后添加 `.lower()` 或 `.upper()` 方法
阅读全文
相关推荐
















