有人能告诉我出了什么问题吗,当我试图解密我加密的密文时,它告诉我我的填充不正确

can somebody tell me what went wrong, when I am trying to decrypt the ciphertext that I encrypted, it tells me that my padding is incorrect

当试图解密我的明文时,它给我一个值错误。

mesg = b'b235dd55aae34e97a054b05c09777e18'

decipher = AES.new(key,AES.MODE_CBC,iv)
plaintext = decipher.decrypt(mesg)
truetext = unpad(plaintext,block_size=16)
print(hexa(truetext).decode())

输出表明

ValueError: Padding is incorrect.

尽管我自己使用

加密了明文
plaintext = b"hello world"
ciphertext = cipher.encrypt(pad(plaintext,16))
print(hexa(ciphertext).decode())

这是我的简单 encryption/decryption 的样子

#Pycryptodome
#unable to decrypt, padding problem
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from binascii import hexlify as hexa


key = get_random_bytes(16)  
iv = get_random_bytes(16)
cipher = AES.new(key,AES.MODE_CBC,iv)

plaintext = b"hello world"
ciphertext = cipher.encrypt(pad(plaintext,16))
print(hexa(ciphertext).decode())

mesg = b'b235dd55aae34e97a054b05c09777e18'

decipher = AES.new(key,AES.MODE_CBC,iv)
plaintext = decipher.decrypt(mesg)
truetext = unpad(plaintext,block_size=16)
print(hexa(truetext).decode())

改用此代码。

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from binascii import hexlify as hexa


key = get_random_bytes(16)  
iv = get_random_bytes(16)
cipher = AES.new(key,AES.MODE_CBC,iv)

plaintext = b"hello world"
ciphertext = cipher.encrypt(pad(plaintext,16))
print(hexa(ciphertext).decode())

# mesg = b'b235dd55aae34e97a054b05c09777e18' 
# can't be decrypted with different key/iv pair 

decipher = AES.new(key,AES.MODE_CBC,iv)
plaintext = decipher.decrypt(ciphertext)  # decrypt ciphertext instead
truetext = unpad(plaintext,block_size=16)
print(hexa(truetext).decode())

你的问题似乎是(因为我不知道 msg 的密钥和 iv)是当 msg 被解密并且 un-padded 使用 pkcs7 填充时不正确,因为 pkcs7 随后检查消息是否被正确填充(检查 wikipedia),如果消息不正确则抛出错误 padded.In 总结,plaintext 用特定的加密key/iv 对,它的密文也必须使用加密期间使用的相同 key/iv 对解密,否则您的消息将被解密为无意义或导致错误的填充错误。