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:

-----BEGIN PUBLIC KEY-----
MIIBCgKCAQEA+xGZ/wcz9ugFpP07Nspo6U17l0YhFiFpxxU4pTk3Lifz9R3zsIsu
ERwta7+fWIfxOo208ett/jhskiVodSEt3QBGh4XBipyWopKwZ93HHaDVZAALi/2A
+xTBtWdEo7XGUujKDvC2/aZKukfjpOiUI8AhLAfjmlcD/UZ1QPh0mHsglRNCmpCw
mwSXA9VNmhz+PiB+Dml4WWnKW/VHo2ujTXxq7+efMU4H2fny3Se3KYOsFPFGZ1TN
QSYlFuShWrHPtiLmUdPoP6CV2mML1tk+l7DIIqXrQhLUKDACeM5roMx0kLhUWB8P
+0uj1CNlNN4JRZlC7xFfqiMbFRU9Z4N6YwIDAQAB
-----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,
},
Buffer.from(credentials.password),
)
const credentialsWithEncryptedPassword = {
clientId: credentials.clientId,
password: encryptedPassword,
}

--

--