0

I'm encrypting a string in a bash script and then appending the decryption key to the end of the file as follows:

random_key=$(openssl rand -hex 16)
plaintext='hello world hello world hello world hello world hello world hello world hello world hello world'
encrypted_license=$(echo -n $plaintext | openssl enc -aes-256-cbc -pbkdf2 -a -salt -pass "pass:$random_key")
encrypted_license_with_key="$encrypted_license$random_key"
echo -n $encrypted_license_with_key > encrypted_data

I can then successfully decrypt it like this:

# Read the last 32 characters of the file as the key
key=$(tail -c 32 "$input_file")

# Read the rest of the file as the encrypted message
encrypted_license=$(head -c -32 "$input_file")

# Decrypt the license using the key
decrypted_license=$(openssl enc -aes-256-cbc -pbkdf2 -a -d -salt -pass "pass:$key" <<< $encrypted_license)

The encrypted file looks e.g. like this:

U2FsdGVkX18YgNEutgGwpc4X4JI8xZ8iwRCQDVO3fHlBs/1pDIapYcBBXZpZdsfa xpF9ZuYXyvIItlkQ+R4/63FgfuGAPxibunfbm065l51eLyG0nzq5s/vhQwjstbPW ZojwCdBWrqntM97W2jtFaw==ce0319d1ec078e2b57e31b7befc82461

Now I'm trying to decrypt the same file in python, but I'm getting Error: Padding is incorrect.. The way I'm trying it now is like this:

from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import SHA256
from Crypto.Util.Padding import unpad
from Crypto.Cipher import AES
import base64

def decrypt_license(input_file):
    # Read the input file and extract the decryption key and encrypted message
    with open(input_file, 'r') as f:
        license_data = f.read().strip().split('==')
        key = base64.b64decode(license_data[1])
        encrypted_license = base64.b64decode(license_data[0] + '==')
        print(encrypted_license)
    # Extract the salt and ciphertext from the encrypted message
    salt = encrypted_license[8:16]
    ciphertext = encrypted_license[16:]

    # Reconstruct Key/IV-pair
    pbkdf2Hash = PBKDF2(str(key), salt, 48, hmac_hash_module=SHA256)
    key = pbkdf2Hash[:32]
    iv = pbkdf2Hash[32:48]

    # Decrypt with AES-256 / CBC / PKCS7 Padding
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size, style='pkcs7')

    return json.loads(decrypted.decode())

I cant spot the error that causes this, I've looked at Decrypting AES CBC in python from OpenSSL AES but still something I'm not doing correctly.

Any help would be greatly appreciated

  • `random_key` (actually not a key but a password) must be ASCII (or UTF-8) encoded in the Python code (and not Base64 decoded). In `PBKDF2()` the iteration count must be set (try `10000`). The plaintext is not a JSON string (so why `json.loads()`?). Base64 encoding has no, one or two `=` at the end depending on the data size. Thus, `split('==')` does not work reliably (neither does `base64.b64decode(license_data[0] + '==')`). Btw, the concatenation of ciphertext and password makes the encryption meaningless. – Topaco Feb 22 '23 at 15:29

0 Answers0