sarasa
sarasa

Reputation: 95

CryptoJS decrypt object

I need to decrypt something encrypted with CryptoJS. I have the function used to encrypt, the structure of the object encrypted and data used to encrypt to encrypt but I need to know some values of that object.

The function is:

var c = CryptoJS.enc.Utf8.parse(g.slice(0, 16));
var d = CryptoJS.AES.encrypt(JSON.stringify(collectData), c, {
    iv: c,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
}).toString()

Later, to the encrypted variable the following is applied:

d.toString().replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '*');

I tried with this but I can't revert the object:

var decrypted = CryptoJS.AES.decrypt(coord, key, {
    iv: key,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
});

console.log('decrypted clean:\n' + decrypted);
console.log('decrypted JSON.stringify():\n'+ JSON.stringify(decrypted));

thanks!

Upvotes: 4

Views: 11555

Answers (2)

Jeffrey Skinner
Jeffrey Skinner

Reputation: 160

Hey your question actually help me to find a solution, encrypt takes in a object, and decrypt takes in a string, so you can do your replace

The other place that could be giving this type of error is the key, when parsing the key to Utf8 ensure that the key is exactly 16 characters you can add nulls add the end of the string to ensure it is long enough by appending '/u0000' to your string before parsing

encrypt(data) {
return CryptoJS.AES.encrypt(JSON.stringify(data), this.secret,
 {
    keySize: 128 / 8,
    iv: this.secret,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }).toString();
}

decrypt(data) {
return JSON.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(data,  this.secret, 
{
    keySize: 128 / 8,
    iv: this.secret,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })));
}

Upvotes: 5

Rohit Parte
Rohit Parte

Reputation: 4036

Encryption and decryption of JSON object

Node JS

var CryptoJS = require('node-cryptojs-aes').CryptoJS;

var data = {
  "glossary": {
  "title": "example glossary",
  }
}

var cip = CryptoJS.AES.encrypt(JSON.stringify(data), "pass").toString();
console.log("Encrypted data = " + cip);

At browser side- HTML CDN - "https://cdn.jsdelivr.net/npm/[email protected]/crypto-js.js"

var decrypted =     CryptoJS.AES.decrypt('U2FsdGVkX1/ps2tRPpM+5elyGhaT7zpp3YL45esS57GmSLoCkhcRdJDBGPUy    uvt0tf4CY6lW2+kugXocBQkc6A==', "pass");
    data = CryptoJS.enc.Utf8.stringify(decrypted)
    console.log("decrypted", JSON.parse(data))

Upvotes: 0

Related Questions