节点JSencryption“错误的inputstring”

想从文件解密一个string。

但是,当我使用nodejs从fsstring解码,它会给出错误“错误的inputstring”

var fs = require('fs'); var crypto = require('crypto'); function decrypt(text){ var decipher = crypto.createDecipher('aes-256-ctr', 'password') var dec = decipher.update(text,'hex','utf8') dec += decipher.final('utf8'); return dec; } fs.readFile('./file.json', 'utf8', function (err,data) { if (err) return console.log(err); console.log(decrypt(data)); }); 

试着制作一个像这样的string

 var stringInFile= "encryptedString"; console.log(decrypt(stringInFile)); 

来自fs的console.log(数据)也给'encryptedString'

你的代码的问题是没有什么。 问题是你试图解密的string。 您要解密的string不能是任何string。 它必须是由类似的encrypt函数生成的string。

 var crypto = require('crypto'); encrypt = function(text, passPhrase){ var cipher = crypto.createCipher('AES-128-CBC-HMAC-SHA1', passPhrase); var crypted = cipher.update(text,'utf8','hex'); crypted += cipher.final('hex'); return crypted; } decrypt = function(text, passPhrase){ var decipher = crypto.createDecipher('AES-128-CBC-HMAC-SHA1', passPhrase) var dec = decipher.update(text,'hex','utf8') dec += decipher.final('utf8'); return dec; } console.log(decrypt(encrypt("Hello", "123"), "123")); 

例如,这段代码工作得很好,没有错误。

希望能帮助到你。