javascriptpython-3.xcryptographycryptojspython-cryptography

Crypto-js equivalent function in python


I have a javascript function which encrypt a json using AES cipher from Crypto-Js module. I want a equivalent of this function in python.

encryptAES = function(data1) {
    var keyUtf8 = CryptoJS.enc.Base64.parse('1234567890=');
    var ivUtf8 = CryptoJS.enc.Base64.parse('1234==');
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data1), keyUtf8, {
    iv: ivUtf8,
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.CBC}).toString();

console.log('encrypted===aes=='+encrypted);
return encrypted

}`

I tried finding equivalent function in python. For starters, I tried finding equivalent of CryptoJS.enc.Base64.parse() using base64 python module. But both are returning different response.


Solution

  • To replicate the functionality of your JavaScript function in Python, you will need to use the PyCryptodome library to perform the AES encryption.

    Here is the equivalent Python function:

    from Crypto.Cipher import AES
    import base64
    import json
    
    def encryptAES(data1):
        key = base64.b64decode('1234567890=')
        iv = base64.b64decode('1234==')
        cipher = AES.new(key, AES.MODE_CBC, iv)
        padded_data = _pad_data(json.dumps(data1).encode('utf-8'))
        encrypted = cipher.encrypt(padded_data)
        return base64.b64encode(encrypted).decode('utf-8')
    
    def _pad_data(data):
        padding_length = AES.block_size - len(data) % AES.block_size
        padding = chr(padding_length) * padding_length
        return data + padding.encode('utf-8')
    

    The _pad_data function pads the data with PKCS7 padding to ensure that it is a multiple of the block size before encryption. The encryptAES function takes in a JSON object, converts it to a JSON string, and encrypts it using AES with CBC mode and PKCS7 padding.

    Note that the encoded result may be different from the one returned by the JavaScript implementation, as different libraries may use different defaults for certain parameters such as the padding and block modes.