python实现aes256加解密代码
时间: 2023-07-23 18:34:34 浏览: 87
以下是Python实现AES256加解密的代码示例:
```
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
# 加密函数
def encrypt_AES256(key, plaintext):
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))
return iv + ciphertext
# 解密函数
def decrypt_AES256(key, ciphertext):
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode('utf-8')
# 测试代码
key = get_random_bytes(32) # 生成256位随机密钥
plaintext = "Hello World!"
ciphertext = encrypt_AES256(key, plaintext)
print("加密后的密文:", ciphertext)
decrypted_plaintext = decrypt_AES256(key, ciphertext)
print("解密后的明文:", decrypted_plaintext)
```
注意:以上代码依赖于`pycryptodome`库,需要先安装该库。
阅读全文