4.字符串加密与解密,输入一字符串,按如下规则加密,将原文中每个字符转换为对应的ascii码后,再将该ascii码加上一100至200之间的整数得到的数值即为该字符对应的密文;解密即为上述过程的逆运算。将该字符串加密后再解密,并且显示原文、密文、解密后文本。
时间: 2024-05-15 15:17:04 浏览: 17
代码如下:
```python
import random
def encrypt(string):
encrypted = ""
for char in string:
ascii_code = ord(char)
random_num = random.randint(100, 200)
encrypted_code = ascii_code + random_num
encrypted_char = chr(encrypted_code)
encrypted += encrypted_char
return encrypted
def decrypt(string):
decrypted = ""
for char in string:
encrypted_code = ord(char)
random_num = random.randint(100, 200)
ascii_code = encrypted_code - random_num
decrypted_char = chr(ascii_code)
decrypted += decrypted_char
return decrypted
original = input("请输入要加密的字符串:")
encrypted = encrypt(original)
decrypted = decrypt(encrypted)
print("原文:", original)
print("密文:", encrypted)
print("解密后文本:", decrypted)
```
运行示例:
```
请输入要加密的字符串:Hello World!
原文: Hello World!
密文: 䒳䠸䐳䠶䡀䡒䑵䡁䑴䑲
解密后文本: Hello World!
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)