Categories
JavaScript Answers

How to encrypt data with a public key in Node.js?

Spread the love

Sometimes, we want to encrypt data with a public key in Node.js.

In this article, we’ll look at how to encrypt data with a public key in Node.js.

How to encrypt data with a public key in Node.js?

To encrypt data with a public key in Node.js, we can use the fs.readFileSync method to read the public key.

Then we use the crypt module to encrypt our data.

For instance, we write

const crypto = require("crypto");
const path = require("path");
const fs = require("fs");

const encryptStringWithRsaPublicKey = (
  toEncrypt,
  relativeOrAbsolutePathToPublicKey
) => {
  const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
  const publicKey = fs.readFileSync(absolutePath, "utf8");
  const buffer = Buffer.from(toEncrypt);
  const encrypted = crypto.publicEncrypt(publicKey, buffer);
  return encrypted.toString("base64");
};

const decryptStringWithRsaPrivateKey = (
  toDecrypt,
  relativeOrAbsolutePathtoPrivateKey
) => {
  const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey);
  const privateKey = fs.readFileSync(absolutePath, "utf8");
  const buffer = Buffer.from(toDecrypt, "base64");
  const decrypted = crypto.privateDecrypt(privateKey, buffer);
  return decrypted.toString("utf8");
};

to create the encryptStringWithRsaPublicKey and decryptStringWithRsaPrivateKey functions.

In encryptStringWithRsaPublicKey, we get the publicKey with fs.readFileSync to read the public key file.

Then we convert the toEncrypt string to a buffer with Buffer.from.

And then we call crypto.publicEncrypt to encrypt the buffer with the publicKey.

In decryptStringWithRsaPrivateKey, we read the privateKey with fs.readFileSync.

Then we get the buffer from the toDecrypt string with Buffer.from.

Next, we call crypto.privateDecrypt with privateKey and buffer to decrypt the buffer with the privateKey.

Finally, we convert the decrypted content to a string with toString.

Conclusion

To encrypt data with a public key in Node.js, we can use the fs.readFileSync method to read the public key.

Then we use the crypt module to encrypt our data.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *