javascript - Node JS crypto "Bad input string" - Stack Overflow

Want to decrypt a string from file.But when i use nodejs decipher on the string from fs, it gives the e

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'

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'

Share Improve this question asked Jun 15, 2017 at 19:26 StweetStweet 7133 gold badges12 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745266428a4619484.html

相关推荐

  • javascript - Node JS crypto "Bad input string" - Stack Overflow

    Want to decrypt a string from file.But when i use nodejs decipher on the string from fs, it gives the e

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信