AES encryption - from JSCrypto to python

44 views Asked by At

I want to rewrite a javascript function in python, this is the function

String.prototype.CryptoAES = function(key, iv, additionalData, tag) {
    // Replacing characters 'Ñ' with 'N' and '%' with 'A' in the key
    key = key.replace('Ñ', 'N').replace('%', 'A');
    
    // Parsing the key and IV as UTF-8 encoded strings
    var parsedKey = CryptoJS.enc.Utf8.parse(key.substring(0, 7) + iv + additionalData + tag);
    
    var parsedIV = CryptoJS.enc.Utf8.parse(iv + additionalData + key.substring(1, 5) + additionalData + tag);

    // Encrypting the string using AES encryption
    var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(this), parsedKey, {
        keySize: 128 / 8, // Key size in bits
        iv: parsedIV, // Initialization Vector
        mode: CryptoJS.mode.CBC, // Cipher Block Chaining mode
        padding: CryptoJS.pad.Pkcs7 // Padding scheme
    });
    
  
    // Returning the encrypted string
    return encrypted.toString();
}

What i achieved so far:

def CryptoAES(input_string, key, iv, additional_data, tag):
    # Replacing characters 'Ñ' with 'N' and '%' with 'A' in the key
    key = key.replace('Ñ', 'N').replace('%', 'A')

    # Concatenating key, iv, additionalData, and tag
    concatenated_key = key[:7] + iv + additional_data + tag
    concatenated_iv = iv + additional_data + key[1:5] + additional_data + tag

    # Generating key and iv from concatenated strings using scrypt
    derived_key = scrypt(concatenated_key.encode(), salt=b'', key_len=16, N=16384, r=8, p=1)
    derived_iv = scrypt(concatenated_iv.encode(), salt=b'', key_len=16, N=16384, r=8, p=1)

    # Encrypting the string using AES encryption in CBC mode with PKCS7 padding
    cipher = AES.new(derived_key, AES.MODE_CBC, iv=derived_iv)
    padded_data = pad(input_string.encode(), AES.block_size)
    encrypted_data = cipher.encrypt(padded_data)

    # Returning the encrypted string
    return base64.b64encode(encrypted_data).decode()

But they are producing different results, for example

console.log("oi".CryptoAES("a", "b", "c", "d")) // outputs 9nMnx5vBxOIb5ZGSHWDUSA==
print(CryptoAES("oi", "a", "b", "c", "d")) // outputs d+4pa99hJ6kcseKPUGRsCQ==

What am i doing wrong?

0

There are 0 answers