2

i am using crypto-js for encryption a text with key and IV (new byte[16]) for some reason it's giving different output from what it gives online or from my python code

my python code:

import base64
import binascii
import hashlib

from Crypto.Cipher import AES


def r_pad(payload, block_size=16):
    length = block_size - (len(payload) % block_size)
    return payload + chr(length) * length


key = "my-private-key"
body = "my-text-to-encrypt"
iv = binascii.unhexlify(16 * "00")
length = len(body)
encoded_key = key.encode('ascii')
data_from_encryption = r_pad(body).encode('utf-8')
encrypted_data = AES.new(encoded_key, AES.MODE_CBC, iv).encrypt(data_from_encryption)
encrypted_data_to_base64_str = base64.b64encode(encrypted_data).decode('utf-8')
print("Encrypted data: ", encrypted_data_to_base64_str)

my javascript code

import { Buffer } from "buffer";
import CryptoJS from "crypto-js";

const IV = Buffer.alloc(16, 0, "hex");
const key = "my-private-key";
const text = "my-text-to-encrypt"
const ciphertext = CryptoJS.AES.encrypt(text, key, {
    iv: IV,
    mode: CryptoJS.mode.CBC,
}).toString();

console.log(ciphertext)

i don't know what i am missing here which is causing problem. if i try to decrypt my encrypted javascript's code cyptherText from the code is used in python to decrypt it shows error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 1: invalid continuation byte

and there is a lot of difference in the output of the both the encryption code:

python outputs: VfCJUymqvQWJWm9Vl93A6Q==

javascript outputs: U2FsdGVkX1+/owRNxuxz16Lq7OeNxYmeBiDQZDHHEAQ=

can anybody help me to fix my javascript code?

Mohit Kumar
  • 552
  • 9
  • 29
  • I find an answer may help to locate your problem in python. https://stackoverflow.com/a/41678985/14032355 – ikhvjs Feb 01 '22 at 09:41
  • 2
    Probably the most common mistake with CryptoJS: The key must be passed as `WordArray`, for instance `const key = CryptoJS.enc.Utf8.parse("0123456789012345")`, otherwise it will be interpreted as password. Also, `Buffer` is likely to be problematic since CryptoJS uses `WordArray`, e.g. `const IV = CryptoJS.enc.Hex.parse("000000000000000000000000")` for a zero IV, however a static IV is insecure. – Topaco Feb 01 '22 at 09:48

0 Answers0