python encode加解密
时间: 2023-11-07 10:53:54 浏览: 64
Python中可以使用加密算法对数据进行加解密。常用的加解密算法有AES、DES、RSA等。下面是一个使用AES算法进行加解密的示例:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_ECB)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
return ciphertext
def decrypt(ciphertext, key):
cipher = AES.new(key, AES.MODE_ECB)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext
# 生成随机密钥
key = get_random_bytes(16)
# 待加密的明文
plaintext = b"Hello, World!"
# 加密
ciphertext = encrypt(plaintext, key)
print("加密后的密文:", ciphertext)
# 解密
decrypted_plaintext = decrypt(ciphertext, key)
print("解密后的明文:", decrypted_plaintext.decode("utf-8"))
```
阅读全文