使用prompt()函数实现一个简单的加密解密程序(Python)
发布时间:2023-12-14 06:50:30
使用 Python 的 input() 函数和 ord()、chr() 函数可以实现一个简单的加密解密程序。
加密过程:
1. 提示用户输入要加密的消息。
2. 遍历消息中的每个字符,获取其 ASCII 值。
3. 把 ASCII 值加上一个固定的加密偏移值。
4. 将加密后的 ASCII 值转换为字符,并存入一个列表中。
5. 将列表中的字符连接起来形成加密字符串。
解密过程:
1. 提示用户输入要解密的加密字符串。
2. 遍历加密字符串的每个字符,获取其 ASCII 值。
3. 把 ASCII 值减去加密时的偏移值。
4. 将还原后的 ASCII 值转换为字符,并存入一个列表中。
5. 将列表中的字符连接起来形成解密后的字符串。
下面是一个使用例子:
def encrypt(message, offset):
encrypted_str = ""
for char in message:
ascii_val = ord(char)
encrypted_val = ascii_val + offset
encrypted_char = chr(encrypted_val)
encrypted_str += encrypted_char
return encrypted_str
def decrypt(encrypted_message, offset):
decrypted_str = ""
for char in encrypted_message:
ascii_val = ord(char)
decrypted_val = ascii_val - offset
decrypted_char = chr(decrypted_val)
decrypted_str += decrypted_char
return decrypted_str
# 加密过程
prompt_message = "请输入要加密的消息:"
encryption_offset = 3
message_to_encrypt = input(prompt_message)
encrypted_message = encrypt(message_to_encrypt, encryption_offset)
print(f"加密后的消息:{encrypted_message}")
# 解密过程
prompt_encrypted = "请输入要解密的加密字符串:"
decryption_offset = 3
encrypted_to_decrypt = input(prompt_encrypted)
decrypted_message = decrypt(encrypted_to_decrypt, decryption_offset)
print(f"解密后的消息:{decrypted_message}")
运行该程序,将提示用户输入要加密或解密的消息,并显示加密/解密后的结果。在加密和解密过程中使用了一个偏移值,这个值为 3,但你可以根据需要自行修改。
