Neeraj joon
Neeraj joon

Reputation: 31

Decrypt AES ECB using python

I have some data i want to decrypt which is encrypted in AES ECB with PKCS5 padding using java. but i am having hard time decryptiing it. i tried many tutorials and stack overflow ans. but nothing worked for me. help me with this

i am trying like this

    BLOCK_SIZE = 16
    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]

    def decrypt(key,enc):
        enc = b64decode(enc)
        cipher = AES.new(key.encode("utf8"), AES.MODE_ECB)
        return unpad(cipher.decrypt(enc)).decode('utf8')

    key = '0vlqRTgxr0C]X29C(}{M\\&TZErb$1!f{'
    enc = 'T3cPMizpZj63+iVwXvlFUnD8Hld5XN4h3v3Ncd8YuIk='

but i am getting only empty string back

Upvotes: 3

Views: 10569

Answers (1)

Evan Su
Evan Su

Reputation: 156

It looks like you are using the PyCrypto/PyCryptoDome package for encryption. Instead of writing your own padding function, it's easier to use the built-in one. Here's the example from the docs:

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

data = b'Unaligned'   # 9 bytes
key = get_random_bytes(32)
iv = get_random_bytes(16)

cipher1 = AES.new(key, AES.MODE_CBC, iv)
ct = cipher1.encrypt(pad(data, 16))

cipher2 = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher2.decrypt(ct), 16)
assert(data == pt)

So in your case, you can get rid of the padding functions and simply rewrite the encrypt and decrypt functions to use PyCryptoDome's padding utils. I've done that for you here with two functions, encrypt and decrypt.

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from base64 import b64encode,b64decode

key = get_random_bytes(32)
iv = get_random_bytes(16)

def encrypt(plaintext,key):
    cipher = AES.new(key,AES.MODE_CBC,iv)
    return b64encode(cipher.encrypt(pad(plaintext.encode(),16))).decode()
def decrypt(ciphertext,key):
    cipher = AES.new(key,AES.MODE_CBC,iv)
    return unpad(cipher.decrypt(b64decode(ciphertext.encode())),16).decode()

And testing it:

>>> encrypt("hello",key)
'aekD8rXrimLT12hFWg22ww=='
>>> decrypt('aekD8rXrimLT12hFWg22ww==',key)
'hello'

Note that I used CBC mode because ECB mode is insecure and shouldn't ever be used. Even CBC has weaknesses, and I would recommend you use CTR mode and an HMAC, or GCM mode which will take care of everything for you.

Upvotes: 4

Related Questions