我测试了here找到的加密/解密代码。代码是:
var crypto = require('crypto');
var encrypt = function(text){
var algorithm = 'aes-256-ctr';
var password = 'gh6ttr';
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(JSON.stringify(text),'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
var decrypt = function(text){
var algorithm = 'aes-256-ctr';
var password = 'gh6ttr';
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(JSON.stringify(text),'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
var encrypted = encrypt('test');
console.log('encrypted is ', encrypted);
var decrypted = decrypt(encrypted);
console.log('decrypted is ', decrypted);
结果是:
encrypted is 66b1f8423a42
decrypted is
解密始终为空白。知道为什么这段代码不起作用吗?
答案 0 :(得分:2)
这是因为你在加密字符串上使用JSON.stringify ......
var decrypt = function(text){
var algorithm = 'aes-256-ctr';
var password = 'gh6ttr';
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return JSON.decode(dec);
}
编辑:我需要注意的是,由于您的问题是“使用节点加密和解密字符串”,因此绝对没有理由在这两个函数中使用JSON函数。
答案 1 :(得分:1)
解密时,您不应该对加密文本进行JSON字符串化:
var dec = decipher.update(text, 'hex', 'utf8')
答案 2 :(得分:0)
请看下面的代码:
加密文字'abc'
var mykey = crypto.createCipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('abc', 'utf8', 'hex')
mystr += mykey.update.final('hex');
console.log(mystr); //34feb914c099df25794bf9ccb85bea72
解密回'abc'
var mykey = crypto.createDecipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('34feb914c099df25794bf9ccb85bea72', 'hex', 'utf8')
mystr += mykey.update.final('utf8');
console.log(mystr); //abc
希望有所帮助,
祝你好运,干杯
Ashish Sebastian