Search code examples
node.jsencryptioncryptojs

How can I decrypt an encrypted text


I got the following code from https://blog.logrocket.com/node-js-crypto-module-a-tutorial . When I /encrypt and /decrypt the result, I get the following error while decrypting:

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
    at Decipheriv._flush (internal/crypto/cipher.js:141:29)
    at Decipheriv.prefinish (internal/streams/transform.js:147:10)

The code is:

app.post("/encrypt", (req, res) => {
  crypto.scrypt(password, "salt", 24, (err, key) => {
    if (err) throw err;
    crypto.randomFill(new Uint8Array(16), (err, iv) => {
      if (err) throw err;
      const cipher = crypto.createCipheriv(algorithm, key, iv);
      let encrypted = "";
      cipher.setEncoding("hex");
      cipher.on("data", (chunk) => (encrypted += chunk));
      cipher.on("end", () => {
        console.log(encrypted);
        res.json({ encrypted });
      });
      cipher.write(req.body.payload);
      cipher.end();
    });
  });
});
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", () => {
    console.log(decrypted);
    res.json({ decrypted });
  });
  decipher.write(req.body.payload, "hex");
  decipher.end();
});

What am I doing wrong here? the password is read from a const in the file, hence incorrect password is not the reason.


Solution

  • Thanks to @Topaco, this is what I came up with:

    app.post("/encrypt", (req, res) => {
      crypto.scrypt(password, "salt", 24, (err, key) => {
        if (err) throw err;
        const iv = Buffer.alloc(16, 0);
        const cipher = crypto.createCipheriv(algorithm, key, iv);
        let encrypted = "";
        cipher.setEncoding("hex");
        cipher.on("data", (chunk) => (encrypted += chunk));
        cipher.on("end", () => res.json({ encrypted }));
        cipher.write(req.body.payload);
        cipher.end();
      });
    });
    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();
    });