node crypto-js AES加密 - >解密使用?

时间:2013-12-23 07:20:01

标签: javascript node.js cryptojs

我正在尝试按如下方式生成crypto-js on node的简单测试:

'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

实际结果是:

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

什么是正确的用法?

2 个答案:

答案 0 :(得分:2)

我修改了代码以处理任何对象:

'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)));

答案 1 :(得分:0)

哦好吧.. 工作守则:

'use strict';

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

console.log(dcr(ecr('hello world')));

结果:

hello world