Padding is incorrect. AES Python encryption
Asked Answered
D

1

6

I'm trying to put together a simple encryption using python.

This is the encrypt:

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
BLOCK_SIZE = 32

def encrypt(message):
    obj = AES.new(b'This is a key123', AES.MODE_CBC, b'This is an IV456')
    return obj.encrypt(pad(message, BLOCK_SIZE))

Encryption seems to work as it returns this:

b'V=\t7I\x99\xa5\x06*\xa1={\x95+\xc1h\xfeY\xc2\xb5\xcf3F:\x88\xa6g\x94d\x87\xd7U'

However for decryption I use:

def decrypt(ciphertext):
    obj2 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is an IV456')
    return obj2.decrypt(unpad(ciphertext, BLOCK_SIZE))

But it shows:

Padding is incorrect

This is the entire file I'm trying to put together:

import sys
from Crypto.Cipher import AES
import importlib
try:
    importlib.import_module('psutil')
except ImportError:
    import pip
    pip.main(['install', 'psutil'])
finally:
    globals()['psutil'] = importlib.import_module('psutil')

def collect_stats():
    try:
        cpu = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory().percent
        disk = psutil.disk_usage('/').percent
        str_to_send_back = "{} {} {}".format(cpu, memory, disk)
        str_to_send_back = str_to_send_back.encode()
        str_to_send_back = encrypt(str_to_send_back)

    except Exception as e:
        print('Oops this error happened in collect_stats() inside client.py: ' + str(e))


def encrypt(message):
    obj = AES.new(b'This is a key123', AES.MODE_CBC, b'This is an IV456')
    return obj.encrypt(message)


def decrypt(ciphertext):
    obj2 = AES.new(b'This is a key123', AES.MODE_CFB, iv)
    return obj2.decrypt(ciphertext)

if __name__ == '__main__':
    collect_stats()
Duthie answered 2/1, 2018 at 18:43 Comment(2)
Umm... You encrypted with CBC mode, and decrypted with CFB mode. Even if you hadn't messed up the padding, this would be broken. Moreover, CFB mode makes AES usable as a stream cipher (so it works on any number of bytes, not just blocks of 16), so if you'd used it consistently, you wouldn't need to pad or unpad at all.Numerate
BLOCK_SIZE 32 cannot be the case it's AES (so must be 16).Privileged
M
13

When encrypting, you do the padding then the encryption:

obj.encrypt(pad(message, BLOCK_SIZE))

This would lead me to believe that when decrypting, you should decrypt first, unpad later. So:

obj2.decrypt(unpad(ciphertext, BLOCK_SIZE))

would become:

unpad(obj2.decrypt(ciphertext), BLOCK_SIZE)
Marketplace answered 2/1, 2018 at 18:48 Comment(2)
BLOCK_SIZE appears to be an argument to unpad(), not decrypt(). Otherwise, this is the same impression I got.Milicent
@Milicent woops! now fixedMarketplace

© 2022 - 2024 — McMap. All rights reserved.