Search code examples
javascriptpythonaes

Decrypt AES-generated hex from aes-js(Javascript) to pycryptodome(Python)


So im trying to decrypt a string I cryptographed with JS in Python. I used the aes-js library. I get this: caba6777379a00d12dcd0447015cd4dbcba649857866072d. This is my JS code:

var key = aesjs.utils.utf8.toBytes("ThisKeyIs16Bytes");
console.log(`Key (bytes): ${key}`);

var text = 'psst... this is a secret';
var textBytes = aesjs.utils.utf8.toBytes(text);

var aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(textBytes);

var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(`Hex: ${key}`);

I've tried a few things in python, but this is what I currently have:

from Crypto.Cipher import AES

ciphered_data = bytearray.fromhex('caba6777379a00d12dcd0447015cd4dbcba649857866072d')
key = b'ThisKeyIs16Bytes'

cipher = AES.new(key, AES.MODE_CTR)
original_data = cipher.decrypt(ciphered_data)
print(original_data.decode("utf-8", errors="ignore"))

But I just recieve a mess.=*լ☻ve↕-:tQɊ#¶.


Solution

  • The CTR mode is used. In the Pyton code the initialization of the counter is missing, i.e. the definition of the correct start value, e.g.

    ...
    cipher = AES.new(key, AES.MODE_CTR, nonce = b'', initial_value = 5)
    ...
    

    or alternatively using a Counter object:

    from Crypto.Util import Counter
    ...
    counter = Counter.new(128, initial_value = 5)
    cipher = AES.new(key, AES.MODE_CTR, counter = counter)
    ...
    

    With one of these two changes the decryption works.