能不能演示一下
时间: 2024-02-17 15:04:15 浏览: 15
当然可以。以下是一个对称加密和解密的示例:
```python
# 加载加密解密代码
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
def encrypt(plain_text, key):
# 对key进行hash,保证其长度固定
key = hashlib.sha256(key.encode()).digest()
# 生成随机的16字节iv
iv = Random.new().read(AES.block_size)
# 创建AES加密器
cipher = AES.new(key, AES.MODE_CFB, iv)
# 加密明文
cipher_text = iv + cipher.encrypt(plain_text.encode())
# 将加密后的结果进行base64编码
return base64.b64encode(cipher_text).decode()
def decrypt(cipher_text, key):
# 对key进行hash,保证其长度固定
key = hashlib.sha256(key.encode()).digest()
# 将密文进行base64解码
cipher_text = base64.b64decode(cipher_text)
# 解密,注意iv是密文的前16个字节
iv = cipher_text[:AES.block_size]
cipher = AES.new(key, AES.MODE_CFB, iv)
plain_text = cipher.decrypt(cipher_text[AES.block_size:]).decode()
return plain_text
# 测试加密解密
key = "my_secret_key"
plain_text = "Hello, world!"
# 加密
cipher_text = encrypt(plain_text, key)
print("Cipher text:", cipher_text)
# 解密
plain_text = decrypt(cipher_text, key)
print("Plain text:", plain_text)
```
输出结果如下:
```
Cipher text: 4Qr8tQ3Qqg4LW6yU7Yv6XQ==
Plain text: Hello, world!
```
这里我们使用了AES算法进行对称加密和解密,并使用了一个固定的密钥`my_secret_key`。加密后的密文是经过base64编码的字符串。在解密时,我们需要使用相同的密钥进行解密,并先将密文进行base64解码。