Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCriptodome AES ValueError("PKCS#7 padding is incorrect.")

from Crypto.Cipher import AES

import hashlib

def encryptString(plaintext, key):
    # Encryption#
    plaintext = Padding.pad(plaintext, AES.block_size);

    iv = get_random_bytes(AES.block_size)
    print('How many:' , sys.getsizeof(key));
    cipher = AES.new(key, AES.MODE_CBC, iv)

    ciphertext = cipher.encrypt(plaintext);
    return (iv + ciphertext).hex();

def decryptString(ciphertextHex, key):
    ciphertext = binascii.unhexlify(ciphertextHex)
    iv = ciphertext[:AES.block_size]
    ciphertext = ciphertext[AES.block_size:]

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

    plaintext = cipher.decrypt(ciphertext)
    plaintext = Padding.unpad(plaintext, AES.block_size)

    return plaintext.decode('utf-8');

I created an AES encryption/decryption wrapper. It works with an example key like:

key = b'0123456789abcdef0123456789abcdef'

But if I am generating a random AES key like this (from a string)

def convertKey(self,key):
    return hashlib.sha256(key.encode()).digest();

Then it returns this error:

File "C:\Python36\lib\site-packages\Crypto\Util\Padding.py", line 93, in unpad raise ValueError("PKCS#7 padding is incorrect.") ValueError: PKCS#7 padding is incorrect.

Any ideas why it returns this, and works with a sample key?

like image 656
Ryper Avatar asked Oct 29 '25 09:10

Ryper


1 Answers

I managed to fix it: You get this error message if your keys don't match.

like image 160
Ryper Avatar answered Oct 31 '25 13:10

Ryper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!