Search code examples
javascriptnode.jsnode-crypto

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'


Solution

  • 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.