Ken OKABE Ken OKABE - 5 months ago 20
Node.js Question

node crypto-js AES encrypt -> decrypt usage?

I am trying to generate a simple test of crypto-js on node as follows:

'use strict';

var AES = require('crypto-js/aes');
var key = 'passPhrase';
var ecr = function(str)
{
return AES.encrypt(str, key);
};
var dcr = function(str)
{
return AES.decrypt(str, key);
};

console.log(dcr(ecr('hello world')));
// expected result is: hello world


The actual result is:

{ words: [ 1751477356, 1864398703, 1919706117, 84215045 ],
sigBytes: 11 }


What is the right usage?

Answer

I modified the code to deal any object:

'use strict';

var CryptoJS = require('crypto-js');
var key = 'pass phrase';
var ecr = function(obj)
{
    return CryptoJS.AES.encrypt(JSON.stringify(obj), key);
};
var dcr = function(obj)
{
    return JSON.parse(CryptoJS.AES.decrypt(obj, key)
        .toString(CryptoJS.enc.Utf8));
};

var s = 'hello world';
console.log(dcr(ecr(s)));

var obj = {
    id: 'ken',
    key: 'password'
};
console.log(dcr(ecr(obj)));
Comments