问题描述: 当使用AES算法进行加密和解密时,输出的结果不正确。
解决方法:
示例代码:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = b"0123456789abcdef" # 16字节密钥,128位
cipher = AES.new(key, AES.MODE_ECB)
# 加密
plaintext = b"Hello, World!"
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
print("加密结果:", ciphertext)
# 解密
decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
print("解密结果:", decrypted.decode())
示例代码:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
key = get_random_bytes(16) # 16字节密钥,128位
iv = get_random_bytes(16) # 初始化向量IV,16字节,128位
cipher = AES.new(key, AES.MODE_CBC, iv)
# 加密
plaintext = b"Hello, World!"
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
print("加密结果:", ciphertext)
# 解密
decipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = unpad(decipher.decrypt(ciphertext), AES.block_size)
print("解密结果:", decrypted.decode())
示例代码:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
key = get_random_bytes(16) # 16字节密钥,128位
cipher = AES.new(key, AES.MODE_ECB)
# 加密
plaintext = b"Hello, World!"
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
print("加密结果:", ciphertext)
# 解密
decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
print("解密结果:", decrypted.decode())
示例代码:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = b"0123456789abcdef" # 16字节密钥,128位
cipher = AES.new(key, AES.MODE_ECB)
# 加密
plaintext = b"Hello, World!"
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
print("加密结果:", ciphertext.hex())
# 解密
decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
print("解密结果:", decrypted.decode())
上一篇:AES加密函数返回null
下一篇:AES密钥长度和块长度