0

I am trying to decrypt an encrypted text. If I provide the correct encrypted text, it works fine. But if I put the wrong encrypted text, the node app just crashes. No try catch block helps and no error is thrown.

Any what can I do to catch the error and return a graceful 500 error.

app.post("/decrypt", (req, res) => {
  const key = crypto.scryptSync(password, "salt", 24);
  const iv = Buffer.alloc(16, 0);
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = "";
  decipher.on("readable", () => {
    while (null !== (chunk = decipher.read())) {
      decrypted += chunk.toString("utf8");
    }
  });
  decipher.on("end", () => res.json({ decrypted }));
  decipher.write(req.body.payload, "hex");
  decipher.end();
});
Amarsh
  • 11,214
  • 18
  • 53
  • 78

2 Answers2

2

Given that your created decipher object is a stream, you can listen for the error event.


let hadErr;
decipher.on("end", () => {
  // not entirely sure this check is necessary
  // but I'll assume you get the end event either way
  if(!hadErr)
    res.json({ decrypted });
});
decipher.on('error', (err) => {
  hadErr = true;
  console.error(err);
  res.status(500);
  res.end('An error has occurred');
})
decipher.write(req.body.payload, "hex");

Error events are common throughout the node library. If an error event is emitted and it has no listener it turns into an uncaught error which will crash the process by default.

leitning
  • 1,081
  • 1
  • 6
  • 10
0

Thanks @leitning. This, for some reason, didnt work. For my purposes, I found the following to work. ( ref: https://attacomsian.com/blog/nodejs-encrypt-decrypt-data )

const crypto = require("crypto");

const algorithm = "aes-256-ctr";
const secretKey = "vOVH6sdmpNWjRRIqCc7rdxs01lwHzfr3";
const iv = Buffer.alloc(16, 0);

const encrypt = (req, res) => {
  const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
  const encrypted = Buffer.concat([
    cipher.update(req.body.payload),
    cipher.final(),
  ]);
  res.send({ encrypted: encrypted.toString("hex") });
};

const decrypt = (req, res) => {
  const decipher = crypto.createDecipheriv(
    algorithm,
    secretKey,
    Buffer.from(iv, "hex")
  );
  const decrpyted = Buffer.concat([
    decipher.update(Buffer.from(req.body.payload, "hex")),
    decipher.final(),
  ]);
  res.send({ decrypted: decrpyted.toString() });
};

module.exports = { encrypt, decrypt };
Amarsh
  • 11,214
  • 18
  • 53
  • 78