'Node.js crypto gives this error "digital envelope routines" "bad decrypt"
I am doing a simple encryption and decryption using the crypto module in node and it works! it works fine in the first few tries and after that it gives me the following error. why is this happening? why would it work fine then suddenly stop working? has it got something to do with the algorithm used?
{
library: 'digital envelope routines',
function: 'EVP_DecryptFinal_ex',
reason: 'bad decrypt',
code: 'ERR_OSSL_EVP_BAD_DECRYPT'
}
all I'm doing is encrypting the password in register and decrypting it on login.
const { createCipheriv, createDecipheriv, randomBytes } = require("crypto");
const algorithm2 = "aes-256-cbc";
const initVector = randomBytes(16);
const SecurityKey = randomBytes(32);
const passwordHash = (password) => {
return new Promise((resolve) => {
const cipher = createCipheriv(algorithm2, SecurityKey, initVector);
let encrypted = cipher.update(password, "utf-8", "hex");
encrypted += cipher.final("hex");
resolve(encrypted);
});
};
const decryptPassword = (encryptedPassword) => {
console.log(SecurityKey, initVector);
return new Promise((resolve, reject) => {
const decipher = createDecipheriv(algorithm2, SecurityKey, initVector);
let decrypted = decipher.update(encryptedPassword, "hex", "utf-8");
decrypted += decipher.final("utf-8");
if (decrypted) {
resolve(decrypted);
} else {
reject("Password decryption failed.");
}
});
};
module.exports = {
passwordHash,
decryptPassword
};
mapping the hashed password
const { passwordHash } = require('./passwordHash'); module.exports = async function(obj1, obj2) { if(obj2.email) { obj1.email = obj2.email; } if(obj2.password) { obj1.password = await passwordHash(obj2.password); } }login and register functions
export const login = async (req, res, next) => { try { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) return res.status(400).json({ msg: "Invalid credentials." }); const decrypted = await decryptPassword(user.password); if (password !== decrypted) return res.status(400).json({ msg: "Invalid credentials." }); jwt.sign( { id: user._id }, process.env.JWT_SECRET, { expiresIn: "7d" }, (err, token) => { if (err) return next({ err }); res.status(200).json({ user, token }); } ); } catch (e) { next(e); } }; export const register = async (req, res, next) => { try { const newUser = {}; await mapUsers(newUser, req.body); const user = await User.create(newUser); res.status(200).json({ user }); } catch (e) { if (e.code === 11000) return next("Duplicate data. Please try with another one"); next(e); } };
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
