以下是代码:
var kk = JSON.stringify(object);
console.log(kk);
var kk1 = encrypt(kk);
console.log(kk1)
var kk2 = decrypt(kk1);
console.log(kk2)
this.write(encrypt(kk))
功能:
var encrypt = function (data) {
var cipher = crypto.createCipher('aes-256-ecb', password)
cipher.update(data, 'utf8')
return cipher.final('hex')
}
var decrypt = function (data) {
var cipher = crypto.createDecipher('aes-256-ecb', password)
cipher.update(data, 'hex')
return cipher.final('utf8')
}
控制台消息:
{"action":"ping","ping":30989}
4613a3a8719c921eed61e19b7480de9c
,"ping":30989}
为什么解密不会导致初始字符串?
答案 0 :(得分:11)
.update()
会返回部分加密/解密的内容,您可以立即丢弃该数据。您还错过了.update()
的输出编码,该编码与您在.final()
中使用的内容相匹配。试试这个:
function encrypt(data) {
var cipher = crypto.createCipher('aes-256-ecb', password);
return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
}
function decrypt(data) {
var cipher = crypto.createDecipher('aes-256-ecb', password);
return cipher.update(data, 'hex', 'utf8') + cipher.final('utf8');
}
答案 1 :(得分:0)
鉴于.update()
和.final()
是mentioned to be legacy methods in the crypto module,我认为我提供了第二种方式。密码对象为streams,因此您可以执行以下操作:
function encrypt(data) {
var text = JSON.stringify(data);
var textBuffer = new Buffer(text, 'utf8');
var cipher = crypto.createCipher('aes-256-ecb', password);
cipher.write(textBuffer);
cipher.end();
return cipher.read().toString('hex');
}
function decrypt(hexString) {
var hexBuffer = new Buffer(hexString, 'hex');
var decipher = crypto.createDecipher('aes-256-ecb', password);
decipher.write(hexBuffer);
decipher.end();
var data = decipher.read().toString('utf8');
return JSON.parse(data);
}
我添加了JSON.stringify并解析以处理数字/对象。