Question

In Python script I need to decrypt data encrypted by aes128-cbc-pkcs7

I checked example in Problem with M2Crypto's AES answer, but it describes aes128-cbc and I have no idea how to adopt it for aes128-cbc-pkcs7

All I have is a key:

key = 'MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHdH2zoKQJ43olhVZstEiBHjZvhUkGL1YcB2baSlHsHjoV5uRkYDyPEHUaN7htski3aGoIUY1vEF7nv0dJaM686KqEfkIxzlRizdnNJr+A8j1OOnOPOooqTuf06570kEEqXCW2STlLIMxwIESPHXAqiKYMPUtNGfu+PpmdY6NUHDAgMBAAE='

or

    key = """MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHdH2zoKQJ43olhVZstEiBHjZvhU
kGL1YcB2baSlHsHjoV5uRkYDyPEHUaN7htski3aGoIUY1vEF7nv0dJaM686KqEfk
IxzlRizdnNJr+A8j1OOnOPOooqTuf06570kEEqXCW2STlLIMxwIESPHXAqiKYMPU
tNGfu+PpmdY6NUHDAgMBAAE="""

I'm not sure how to store the key in a right way - with line brakes or without.

Can you please provide some example how to use aes128-cbc-pkcs7 to encode/decode that should be similar to aes128-cbc (explained in Problem with M2Crypto's AES)

Sorry if questions sounds strange, I'm total newbie in cryptography.

Was it helpful?

Solution

You cannot use encrypt using just AES if you've been given an RSA public key. You need to use hybrid encryption: generate a random AES key of 16, 24 or 32 bytes, then encrypt. You can keep to a zero IV if you generate a new AES key for each encryption.

The AES key itself can then be encrypted using the public key you've been given, using either OAEP or - for backwards compatibility - PKCS#1 v1.5 padding.

The default module does not seem to use padding, if I read the documentation correctly. I've found a padding/unpadding routine on pastebin, thanks go to Peter for sharing:

def pkcs7_pad(data, blocksize=16):
    padlen = blocksize - len(data) % blocksize
    return data + bytes([padlen]) * padlen


def pkcs7_unpad(data, blocksize=16):
    if data:
        padlen = data[-1]
        if 0 < padlen < blocksize:
            if data.endswith(bytes([padlen]) * padlen):
                return data[:-padlen]

    raise ValueError('incorrect padding')

Note that just encryption is not secure if you are using this over a communication channel. It is required to add a message authentication code (MAC), even if you just require confidentiality of the plaintext. Incorrect use of CBC mode encryption may make the protocol vulnerable to padding oracle attacks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top