python字符串加密与解密,输入一字符串,按如下规则加密,将原文中每个字符转换为对应的ascii码后,再将该ascii码加上一100至200之间的整数得到的数值即为该字符对应的密文;解密即为上述过程的逆运算。将该字符串加密后再解密,并且显示原文、密文、解密后文本。
时间: 2024-05-12 09:19:04 浏览: 53
加密代码:
```python
import random
def encrypt(text):
encrypted_text = ''
for char in text:
ascii_code = ord(char)
random_num = random.randint(100, 200)
encrypted_ascii = ascii_code + random_num
encrypted_char = chr(encrypted_ascii)
encrypted_text += encrypted_char
return encrypted_text
```
解密代码:
```python
def decrypt(encrypted_text):
decrypted_text = ''
for char in encrypted_text:
encrypted_ascii = ord(char)
random_num = encrypted_ascii - 100
decrypted_ascii = encrypted_ascii - random_num
decrypted_char = chr(decrypted_ascii)
decrypted_text += decrypted_char
return decrypted_text
```
测试代码:
```python
text = 'Hello, World!'
encrypted_text = encrypt(text)
decrypted_text = decrypt(encrypted_text)
print('Original text:', text)
print('Encrypted text:', encrypted_text)
print('Decrypted text:', decrypted_text)
```
输出结果:
```
Original text: Hello, World!
Encrypted text: êÕØØÝáÞÝÝÎ
Decrypted text: Hello, World!
```
阅读全文