A quick how to on encrypting things using Node’s crypto module

Nikhil Vijayan
1 min readOct 1, 2021

I wanted to document something I had to do recently, which was to encrypt a password using a public key before sending it over the network.

Here’s a quick example:

const credentials = {
clientId: 'client01',
password: 'foo',

Let’s say we need to encrypt the password using a 3rd party public key, so they’re able to decrypt it using their private key (read more about public key encryption or RSA encryption here).

let’s call our third party Janet . So Janet’s given us their public key, which looks like this:

-----END PUBLIC KEY-----

Note: In our example, this public key will be stored in a file called public.pem at the root of the project directory.

So the idea here is that we’re going to use Janet’s public key to encrypt our password foo so when we send it over in the request, any third party that intercepts my request isn’t able to just read our password, and only Janet is able to use their private key to de-crypt our password.

The code ✨

import crypto from 'crypto'
import fs from 'fs'
const credentials = {
clientId: 'client01',
password: 'foo',
const janetsPublicKey = fs.readFileSync('./public.pem', 'utf-8')
const encryptedPassword = crypto.publicEncrypt({
key: janetsPublicKey,
padding: crypto.constants.RSA_PKCS1_PADDING,
const credentialsWithEncryptedPassword = {
clientId: credentials.clientId,
password: encryptedPassword,