2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the solution. Just a note if anyone wants to use this. Please update the key, iv according to your need. padded_data = _pad_data(json.dumps(data1,separators=(',',':')).encode('utf-8')). This is necessary because in JSON.stringify, there are no spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.