字符串加密与解密,输入一字符串,按如下规则加密,将原文中每个字符转换为对应的ascii码后,再将该ascii码加上一100至200之间的整数得到的数值即为该字符对应的密文;解密即为上述过程的逆运算。将该字符串加密后再解密,并且显示原文、密文、解密后文本,代码用python怎么实现
时间: 2024-04-30 20:23:29 浏览: 70
加密代码如下:
```python
import random
def encrypt(string):
encrypted = ''
for char in string:
ascii_code = ord(char)
random_number = random.randint(100, 200)
encrypted_ascii = ascii_code + random_number
encrypted += chr(encrypted_ascii)
return encrypted
```
解密代码如下:
```python
def decrypt(string):
decrypted = ''
for char in string:
encrypted_ascii = ord(char)
random_number = random.randint(100, 200)
ascii_code = encrypted_ascii - random_number
decrypted += chr(ascii_code)
return decrypted
```
加密和解密的过程都是通过遍历字符串中的每个字符,先将其转换为ascii码,然后加上一个随机数得到密文(加密),或者减去同样的随机数得到明文(解密)。注意,加密和解密时的随机数必须相同,否则解密失败。
完整的代码如下:
```python
import random
def encrypt(string):
encrypted = ''
for char in string:
ascii_code = ord(char)
random_number = random.randint(100, 200)
encrypted_ascii = ascii_code + random_number
encrypted += chr(encrypted_ascii)
return encrypted
def decrypt(string):
decrypted = ''
for char in string:
encrypted_ascii = ord(char)
random_number = random.randint(100, 200)
ascii_code = encrypted_ascii - random_number
decrypted += chr(ascii_code)
return decrypted
string = input("请输入字符串:")
encrypted_string = encrypt(string)
decrypted_string = decrypt(encrypted_string)
print("原文:", string)
print("密文:", encrypted_string)
print("解密后文本:", decrypted_string)
```
阅读全文