RSA Encryption in Node.js with Code Samples (2024)

A guide on RSA Encryption in Node.js with code samples.

By Nikhil Vijayan on 2022-02-06

cryptoencryptionjavascriptrsanodejs

RSA Encryption in Node.js with Code Samples (1)

Node.js comes with a 'crypto' module that helps you create public and private key pairs to use public-key cryptography.

Public key cryptography explained:

This is a great article I came across that explains it well: RSA Encryption, Decryption and Signing in Node.js (Javascript) - With Examples*This post will explain the RSA algorithm, and how we can implement RSA Encryption, Decryption and Signing in Node.js…*www.sohamkamani.com

(Please do read this article since I don't cover this in the post)

Where it fell apart for me was actually implementation, since the keys created were in-memory and ephemeral. I'm writing this with code samples that you can run to:

  1. Create a public/private key pair

  2. Export it, and write it to your file system (as public.pem & private.pem files)

  3. Create some sample data to encrypt (this is our secret we don't want anyone else knowing)

  4. Encrypting said data, saving it in a file so we can see what it looks like

  5. Decrypting this encrypted data to get our original secret data

Here's the Github repository:

GitHub - nkhil/node-crypto

You don't need to npm i as there are no dependencies, and the crypto module comes with node.

  1. To create some data to encrypt, run this command

    npm run create-data

You should now have a file called data_to_encrypt.txt in the project root. This is some arbitrary data created using Node.js's crypto module. If you're interested, have a look here: https://github.com/nkhil/node-crypto/blob/master/src/rsa/create-data-to-encrypt.js

OK, so now we have some secret data to encrypt 🎉

In order to encrypt it, we need to first create our Public-Private key pair. In the real world, we would give our public key publicly, and anyone would be able to use the public key to encrypt data, send it to us, and only we would be able to read that data (using our private key that only we will have).

Sidenote: This is a great little comic that explains public-private keys: How HTTPS works*In this scenario, there is only one key to encrypt and decrypt a message. Before sending a message to BrowserBird, I…*howhttps.works

Creating our public-private key pair

Here's how we will create our public-private key pair, export it and write it to file.

const crypto = require("crypto");const fs = require("fs");const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { // The standard secure default length for RSA keys is 2048 bits modulusLength: 2048,});// *********************************************************************//// To export the public key and write it to file:const exportedPublicKeyBuffer = publicKey.export({ type: "pkcs1", format: "pem",});fs.writeFileSync("public.pem", exportedPublicKeyBuffer, { encoding: "utf-8" });// *********************************************************************// *********************************************************************//// To export the private key and write it to fileconst exportedPrivateKeyBuffer = privateKey.export({ type: "pkcs1", format: "pem",});fs.writeFileSync("private.pem", exportedPrivateKeyBuffer, { encoding: "utf-8",});// *********************************************************************

2. To create the public / private key pair, you can run:

npm run create-keys

Note that we write it to the project root, and are named private.pem and public.pem.

Encrypting some data

Here's how we will be encrypting the data in the file called data_to_encrypt.txt that we created in step 1 (I've only numbered the commands you will be using)

const fs = require("fs");const crypto = require("crypto");const dataToEncrypt = fs.readFileSync("data_to_encrypt.txt", { encoding: "utf-8",});const publicKey = Buffer.from( fs.readFileSync("public.pem", { encoding: "utf-8" }));const encryptedData = crypto.publicEncrypt( { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256", }, // We convert the data string to a buffer using `Buffer.from` Buffer.from(dataToEncrypt));fs.writeFileSync("encrypted_data.txt", encryptedData.toString("base64"), { encoding: "utf-8",});

3. To encrypt the data in data_to_encrypt.txt (that we created in step 1 above), use

npm run encrypt-data

Once you run this ^, you should have a file named encrypted_data.txt in your project root. Feel free to open this file, this is the garbled version of our data.

Decrypt the data

Here's the code to decrypt the data

const crypto = require("crypto");const fs = require("fs");const encryptedData = fs.readFileSync("encrypted_data.txt", { encoding: "utf-8",});const privateKey = fs.readFileSync("private.pem", { encoding: "utf-8" });const decryptedData = crypto.privateDecrypt( { key: privateKey, // In order to decrypt the data, we need to specify the // same hashing function and padding scheme that we used to // encrypt the data in the previous step padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256", }, Buffer.from(encryptedData, "base64"));fs.writeFileSync("decrypted_data.txt", decryptedData.toString("utf-8"), { encoding: "utf-8",});

Your decrypted data should be the same as the contents of the file data_to_encrypt.txt .

Congratulations, you've just used RSA encryption to encrypt some data using the public key, and then use the accompanying private key to decrypt and read that information.

Some notes

Note that in the real world, you will probably not have the keys as files, but as secure environment variables that are only available within your application. I've used files as a way to be able to understand RSA encryption better.

You need to ensure that your private keys are kept safe since anyone with access to your private keys can read all the encrypted information.

I've seen private keys kept securely using a storage solution like AWS S3 buckets (or GCP storage buckets), and making it so only applications with the appropriate IAM role can access files within the bucket. This resource creation is usually managed by Terraform but we won't go into that.

It should be noted that there is a limit to the size of the data you can encrypt using RSA encryption. When I try to encrypt a 128byte string, I get the following error:

Error: error:0409A06E:rsa routines:RSA_padding_add_PKCS1_OAEP_mgf1:data too large for key size

Have a look at this Stack Overflow discussion for more information.




Continue Learning

Upload and Retrieve Photos with Amazon S3, Node.js and MongoDB

awscloud computingmongodbnodejsaws s3

How to Safely Concatenate URLs with Node.jsLearn one of the ways to safely concatenate URLs with Node.js.

javascripturlurl-concatenationnodejs

How to Upload Files to Amazon S3 using Node.js

awsjavascripts3nodejs

Static Code Analysis for Node.js and TypeScript Project using SonarQube

code qualitysonarqubestatic code analysistypescriptnodejs

How to Install Node.js on Amazon Workspaces

amazon workspacescloudnodejs

OAuth2 in NestJS for Social Login (Google, Facebook, Twitter, etc)

nodejsoauth2nestjs

RSA Encryption in Node.js with Code Samples (2024)
Top Articles
UPI Issuing bank wise limits
Rabbit Diseases & Vaccinations | RSPCA - RSPCA - rspca.org.uk
Fighter Torso Ornament Kit
Hotels Near 6491 Peachtree Industrial Blvd
Antisis City/Antisis City Gym
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Skylar Vox Bra Size
The Ivy Los Angeles Dress Code
OSRS Fishing Training Guide: Quick Methods To Reach Level 99 - Rune Fanatics
Recent Obituaries Patriot Ledger
Die Windows GDI+ (Teil 1)
سریال رویای شیرین جوانی قسمت 338
Www Thechristhospital Billpay
Music Archives | Hotel Grand Bach - Hotel GrandBach
Nieuwe en jong gebruikte campers
Marion County Wv Tax Maps
The Murdoch succession drama kicks off this week. Here's everything you need to know
Tracking Your Shipments with Maher Terminal
Lima Funeral Home Bristol Ri Obituaries
Chastity Brainwash
Billionaire Ken Griffin Doesn’t Like His Portrayal In GameStop Movie ‘Dumb Money,’ So He’s Throwing A Tantrum: Report
Welcome to GradeBook
Our History
Wbiw Weather Watchers
[PDF] NAVY RESERVE PERSONNEL MANUAL - Free Download PDF
Mtr-18W120S150-Ul
Coomeet Premium Mod Apk For Pc
Naval Academy Baseball Roster
Happy Homebodies Breakup
Aspenx2 Newburyport
Jermiyah Pryear
fft - Fast Fourier transform
Restored Republic
Warren County Skyward
Panchang 2022 Usa
Litter-Robot 3 Pinch Contact & DFI Kit
The Ride | Rotten Tomatoes
Selfservice Bright Lending
Rogers Centre is getting a $300M reno. Here's what the Blue Jays ballpark will look like | CBC News
Magicseaweed Capitola
How to play Yahoo Fantasy Football | Yahoo Help - SLN24152
Bones And All Showtimes Near Johnstown Movieplex
Sams Gas Price Sanford Fl
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
Yourcuteelena
Makes A Successful Catch Maybe Crossword Clue
Access to Delta Websites for Retirees
Canada Life Insurance Comparison Ivari Vs Sun Life
Lebron James Name Soundalikes
Puss In Boots: The Last Wish Showtimes Near Valdosta Cinemas
Shad Base Elevator
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5662

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.