使用Python,编程以下问题:字符串加密与解密,输入一字符串,按如下规则加密,将原文中每个字符转换为对应的ascii码后,再将该ascii码加上一 100 100至 200 200之间的整数得到的数值即为该字符对应的密文;解密即为上述过程的逆运算。将该字符串加密后再解密,并且显示原文、密文、解密后文本。
时间: 2023-05-26 11:05:32 浏览: 60
加密程序:
```python
import random
def encrypt(string):
encrypted = ""
for char in string:
ascii_val = ord(char)
shift = random.randint(100, 200)
encrypted_char = ascii_val + shift
encrypted += str(encrypted_char) + " "
return encrypted[:-1]
string = input("请输入要加密的字符串:")
encrypted_string = encrypt(string)
print("加密后的字符串为:", encrypted_string)
```
解密程序:
```python
def decrypt(encrypted_string):
decrypted = ""
encrypted_list = encrypted_string.split(" ")
for char in encrypted_list:
ascii_val = int(char)
shift = ascii_val - 100
decrypted_char = chr(shift)
decrypted += decrypted_char
return decrypted
decrypted_string = decrypt(encrypted_string)
print("解密后的字符串为:", decrypted_string)
```
完整程序:
```python
import random
def encrypt(string):
encrypted = ""
for char in string:
ascii_val = ord(char)
shift = random.randint(100, 200)
encrypted_char = ascii_val + shift
encrypted += str(encrypted_char) + " "
return encrypted[:-1]
def decrypt(encrypted_string):
decrypted = ""
encrypted_list = encrypted_string.split(" ")
for char in encrypted_list:
ascii_val = int(char)
shift = ascii_val - 100
decrypted_char = chr(shift)
decrypted += decrypted_char
return decrypted
string = input("请输入要加密的字符串:")
encrypted_string = encrypt(string)
print("加密后的字符串为:", encrypted_string)
decrypted_string = decrypt(encrypted_string)
print("解密后的字符串为:", decrypted_string)
```
示例输入与输出:
输入:
```
请输入要加密的字符串:hello world
```
输出:
```
加密后的字符串为:210 220 206 206 201 224 227 197 220 203 207
解密后的字符串为:hello world
```