Arthur
Arthur

Reputation: 25

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

when trying to decrypt my plaintext, it's giving me a value error.

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())

the output says that

ValueError: Padding is incorrect.

even though I encrypted the plaintext myself using

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

here is what my simple encryption/decryption looks like

#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())

Upvotes: 0

Views: 2203

Answers (1)

KMG
KMG

Reputation: 1501

Use this code instead.

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())

Your problem seems like(since i don't know key and iv of msg) is that when msg is decrypted and un-padded using pkcs7 the padding is not correct since pkcs7 check if message is padded correctly afterward (check wikipedia) and throws an error if message is not correctly padded.In summery, a plaintext encrypted with a specific key/iv pair, it's ciphertext must also be decrypted using same key/iv pair used during encryption otherwise your message will be decrypted to nonsense or result in wrong padding error.

Upvotes: 1

Related Questions