Gaurav
Gaurav

Reputation: 788

Node.js Crypto throwing error

Following code give bad decryption error

vaultEngine.AESDecrypt = function (encKey, data) {
    var cipherObject = crypto.createDecipheriv('aes-256-cbc', encKey, "a2xhcgAAAAAAAAAA");
    var Fcontent = cipherObject.update(data, vaultEngine.outputEncoding, vaultEngine.inputEncoding);
    Fcontent += cipherObject.final(vaultEngine.inputEncoding);
    //console.log("Decryption data is:"+Fcontent);
    return Fcontent;
}

Specifically this error:

TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decr
ypt

Upvotes: 0

Views: 224

Answers (1)

Jason
Jason

Reputation: 13766

FIRST OF ALL

I'm concerned that your IV is hard coded directly into your method, which suggests that you're using the same IV for every encryption, which is bad bad bad. The IV should be cryptographically random (unpredictable), and different for every encryption. You can store it with your encrypted text and then pull it back out to use to decrypt, but you should not be using the same IV. If you're making this level of error, it suggests you need to do a lot more research on how to use encryption appropriately so that it actually protects the data you intend to protect. Start here.

And now to attempt to fix address your question directly:


According to the docs it looks like you've reversed your input encoding and output encoding variables, it should be:

var Fcontent = cipherObject.update(data, vaultEngine.inputEncoding, vaultEngine.outputEncoding);
Fcontent += cipherObject.final(vaultEngine.outputEncoding);

... if that doesn't work, I'd recommend the following changes:

  1. use the stream processing write() and end() methods on your cipherObject, instead of the legacy update() and final() methods. The crypto module is considered "unstable" specifically because of the update to use node streams (see here), the legacy methods may remain but they'd be the first on the chopping block if breaking changes are introduced.
  2. Create a buffer from your data before sending it to be decrypted. This will ensure that you've created your buffer correctly, and will minimize the work required at the decryption stage:

var dataBuffer = new Buffer(data, vaultEngine.inputEncoding);
cipherObject.write(dataBuffer);
cipherObject.end();
return cipherObject.read().toString(vaultEngine.outputEncoding);

Upvotes: 1

Related Questions