简体   繁体   中英

Node JS crypto “Bad input string”

Want to decrypt a string from file.

But when i use nodejs decipher on the string from fs, it gives the error "Bad input string"

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

tried just making a string like this it works

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

Tho console.log(data) from fs also gives 'encryptedString'

The problem with your code is NOTHING. The problem is the string that you're trying to decrypt. The string that you want to decrypt can't be any string. It must be a string generated from a similar encrypt function.

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

For example, this code works perfectly fine with no errors.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM