Search code examples
javascriptserveruint8arraynacl-cryptography

GET request successfully returns decrypted gist first time, but empty object after restarting the server


Using JavaScript and nacl libraries to get a GitHub gist and return the decrypted content. All nacl methods accept and return UINT8 arrays, so it is worth noting that the key is also a UINT8 array of 32 random bytes.

   server.get('/fetchmessagefromself:id', (req, res) => {
      // TODO:  Retrieve and decrypt the secret gist corresponding to the given ID
      const id = req.query.id;
      github.gists.get({ id })
        .then((response) => {
          const gist = response.data;
          const file = Object.keys(gist.files);
          const box = gist.files[file].content;
          const nonce = nacl.util.decodeBase64(box.slice(-32));
          const ciphertext = nacl.util.decodeBase64(box.slice(0, -32));
          const text = nacl.secretbox.open(ciphertext, nonce, key);

          res.send(nacl.util.encodeUTF8(text));
        })
        .catch((err) => {
          res.json(err);
        });
    });

After using a separate method to create an encrypted gist on my GitHub account, the above method works the first time and successfully retrieves the decrypted gist but after restarting the server the method only returns an empty object. I cannot figure out why.


Solution

  • I figured it out; it wasn't working after restarting the server because I wasn't persisting the key--which is just an array of 32 random unsigned integers--so each time the server is restarted a new key is made.

    I persisted the key in a separate .env file and the function now works fine!