Поймайте ошибку при расшифровке с помощью криптографии и узла

#node.js #encryption #node-crypto

Вопрос:

Я пытаюсь расшифровать зашифрованный текст. Если я предоставлю правильный зашифрованный текст, он будет работать нормально. Но если я введу неправильный зашифрованный текст, приложение узла просто вылетит. Блок try catch не помогает, и ошибка не возникает.

Все, что я могу сделать, чтобы поймать ошибку и вернуть изящную ошибку 500.

 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();
});
 

Ответ №1:

Учитывая, что созданный вами объект дешифровки является потоком, вы можете прослушивать событие ошибки.

 
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");

 

События ошибок являются общими для всей библиотеки узлов. Если выдается событие ошибки и у него нет прослушивателя, оно превращается в неперехваченную ошибку, которая по умолчанию приведет к сбою процесса.

Ответ №2:

Спасибо @leitning. Это, по какой-то причине, не сработало. Для моих целей я обнаружил, что работает следующее. ( ссылка: 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 };