Gregor Mountain
Gregor Mountain

Reputation: 213

How to decrypt AES 128 in CryptoJS (nodejs / web browser)

I'm using a nodejs server, and i successfully encrypt/decrypt (with IV & Key) a json in Base64 with crypto node module.

However, when I send an emit action with my AES 128 CTR json to a web client, i received correctly my json with base64 data encrypted, but my problem is when i wan't to decrypt this.

In CryptoJS documentation, i found an example like this :

var text = "Hello world";
var key = CryptoJS.enc.Base64.parse("myKey");
var iv  = CryptoJS.enc.Base64.parse("myIv");

var encrypted = CryptoJS.AES.encrypt(text, key, {iv: iv});
console.log(encrypted); // print something like that s {init: function, $super: s, ciphertext: l.WordArray.t.extend.init, key: s, iv: s…}

var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv});
console.log(decrypted.toString(CryptoJS.enc.Utf8)); // print Hello world

We can easily decrypt an "Hello world" because it was encrypted by CryptoJS in my web client. But my problem is that i want to decrypt a data which is not using CryptoJS encrypt system.

I want to do something like this :

var text = "myJsonEncryptedInBase64";
var key = CryptoJS.enc.Base64.parse("myKey");
var iv  = CryptoJS.enc.Base64.parse("myIv");


var decrypted = CryptoJS.AES.decrypt(text, key, {iv: iv});
console.log(decrypted.toString(CryptoJS.enc.Utf8)); //print my decrypted json

I've got an error because CryptoJS decrypt method using an array data like this :

s {init: function, $super: s, ciphertext: l.WordArray.t.extend.init, key: s, iv: s…}

Can you please help me ?

Thanks a lot.

Edit :

Node.js input : {name:"toto", age:"15"} (encrypted with crypto in Base64).

Node.js output: mfrpKm5k5YtGkX6rp9/Bmz+cCkcz5tiLKQcxmOpDUow=

Emitting output throw socket.io to web client.

Web client JS input : mfrpKm5k5YtGkX6rp9/Bmz+cCkcz5tiLKQcxmOpDUow=

Web client JS ouput : {name:"toto", age:"15"} (Decrypting with same IV & KEY)

Upvotes: 3

Views: 16189

Answers (1)

Sohail
Sohail

Reputation: 4586

This worked for me:

var CryptoJS = require("crypto-js");
var data = JSON.stringify({abc: 'xyz'});

var encrypted = CryptoJS.AES.encrypt(data, "my-secret");
console.log(encrypted.toString());

var decrypted = CryptoJS.AES.decrypt(encrypted, "my-secret");
var object = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
console.log(object);
console.log(object.abc);

Hope this is what you wanted to do. This should also work with Base64 inputs.

Upvotes: 9

Related Questions