这个错误通常是由于密码的填充错误导致的。在加密和解密过程中,使用的填充方式必须是一致的,否则会导致解密错误。
以下是一些解决方法的示例代码:
方法1:使用Padding模块进行填充
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
key = b'Sixteen byte key'
cipher = AES.new(key, AES.MODE_ECB)
# 加密
data = b'hello world'
padded_data = pad(data, AES.block_size)
encrypted_data = cipher.encrypt(padded_data)
# 解密
decrypted_data = cipher.decrypt(encrypted_data)
unpadded_data = unpad(decrypted_data, AES.block_size)
print(unpadded_data.decode())
方法2:使用base64编码进行填充
import base64
from Crypto.Cipher import AES
key = b'Sixteen byte key'
cipher = AES.new(key, AES.MODE_ECB)
# 加密
data = b'hello world'
padded_data = data + (AES.block_size - len(data) % AES.block_size) * b'\0'
encrypted_data = cipher.encrypt(padded_data)
encoded_data = base64.b64encode(encrypted_data)
# 解密
decoded_data = base64.b64decode(encoded_data)
decrypted_data = cipher.decrypt(decoded_data)
unpadded_data = decrypted_data.rstrip(b'\0')
print(unpadded_data.decode())
这些示例代码演示了两种常见的填充方式:使用Padding
模块进行填充和使用base64编码进行填充。你可以根据自己的需要选择其中一种方式进行填充,但在加密和解密过程中,必须使用相同的填充方式。