I'm writing my own security class using the crypto module of Node.js and the AES-256-CBC cipher algorithm.
But when I try to decrypt an encrypted string, encrypted from input data longer than 15 characters, fails with this error:
crypto.js:153
var ret = this._handle.final();
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
I think that the problem is with the encryption or the IV generation, in fact, the encrypted hex string is always 32 chars long.
Let's review the code together:
var crypto = require("crypto"),
password = "mySecureKey",
salt = "mySaltKey";
//generate the IV
crypto.pbkdf2(password , salt, 4096, 8, "sha1", function(err, key) {
if (err) throw err;
var cipher_iv = new Buffer(key.toString('hex'));
//encrypt the string
var input = "helloPrettyWorld";
cipher = crypto.createCipheriv("aes-256-cbc", new Buffer(password), cipher_iv);
cipher.update(input, "utf8", "hex");
var encrypted = cipher.final("hex"); //i.e: input = "hello"; encrypted = "2300743605fbdaf0171052ccc6322e96"
//decrypt the string
cipher = crypto.createDecipheriv("aes-256-cbc", new Buffer(password), cipher_iv); /* THE ERROR IS THROWN HERE */
cipher.update(encrypted, "hex", "utf8")
var decrypted = cipher.final("utf8");
});
I tried with resizing the password/salt lengths and even using string with fixed-length (32, 16, etc..), but does not to resolve the problem.
Recap:
An input data like: "helloNiceWorld" (14 chars) will be encrypted and decrypted perfectly, while an input data like "helloPrettyWorld" (16 chars) will not.