Is possible to decrypt data in Cordova which are encrypted in node.js?

45 Views Asked by At

I have encrypted data from backend running on node.js using crypto. I'm trying to decrypt them in my Cordova application using CryptoJS, but without success. I made simple code for testing in online node js sandbox, where I'm using both of libraries. Here is my code:

const crypto = require('crypto');
const CryptoJS = require('crypto-js');

const algorithm = 'aes-256-cbc';
const key = '01234567890123456789012345678901';
const iv = crypto.randomBytes(16);
const text = 'This is secure text';

const cipher = crypto.createCipheriv(algorithm, key, iv);
const encrypted = Buffer.concat([cipher.update(Buffer.from(text)), cipher.final()]).toString('base64');

const ciphertext = Buffer.from(encrypted, 'base64');

const decrypted = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {
  mode: CryptoJS.mode.CBC,
  iv: CryptoJS.enc.Hex.parse(iv.toString('hex')),
}).toString(CryptoJS.enc.Utf8);

console.log(decrypted);

I was trying several variations of key and data encoding (Utf8, Hex)

1

There are 1 best solutions below

0
Onlinogame On BEST ANSWER

It seems using a CryptoJS.lib.CipherParams as the first argument of the decrypt function fix the problem.

Try this

const crypto = require("crypto");
const CryptoJS = require("crypto-js");

const algorithm = "aes-256-cbc";
const key = "01234567890123456789012345678901";
const iv = crypto.randomBytes(16);
const text = "This is secure text";

const cipher = crypto.createCipheriv(algorithm, key, iv);
const encrypted = Buffer.concat([
  cipher.update(Buffer.from(text)),
  cipher.final(),
]).toString("base64");

const ciphertext = CryptoJS.enc.Base64.parse(encrypted); // Create the WordArray object

const decrypted = CryptoJS.AES.decrypt(
  { ciphertext }, // Put a CypherParams instead of a plain string
  CryptoJS.enc.Utf8.parse(key),
  {
    mode: CryptoJS.mode.CBC,
    iv: CryptoJS.enc.Hex.parse(iv.toString("hex")),
  }
).toString(CryptoJS.enc.Utf8);

console.log(decrypted);