节点 JS 加密"Bad input string"



想要从文件中解密字符串。

但是当我从 fs 对字符串使用 nodejs 解密时,它会给出错误"输入字符串错误">

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

尝试只是制作这样的字符串它有效

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

寿来自 fs 的 console.log(data( 也给出了 'encryptedString'

你的代码的问题是什么都没有。问题在于您尝试解密的字符串。要解密的字符串不能是任何字符串。它必须是从类似的encrypt函数生成的字符串。

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

例如,此代码工作正常,没有错误。

希望对您有所帮助。

相关内容

最新更新