[英]Node.JS Crypto Cipher/Decipher not working
这是代码:
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}
为什么解密不会产生初始字符串?
.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');
}
鉴于.update()
和.final()
是加密模块中的遗留方法 ,我想我会提供第二种方法。 密码对象是stream ,因此您可以执行以下操作:
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并解析以处理数字/对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.