Node.js - RSA Encryption And Decryption Example

The RSA algorithm (Rivest-Shamir-Adleman) is a cryptographic algorithm that is used for specific security services or purposes, which enables public-key encryption and is widely used to secure sensitive data, particularly when it is being sent over an insecure network such as the HTTP. A public key is shared publicly, while a private key is secret and must not be shared with anyone.

The following illustration highlights how asymmetric cryptography works:

Program to demonstrate RSA encryption and decryption in Node.js,

const crypto = require("crypto")

// Generating RSA key pairs(public and private key)
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
// The length of our RSA keys is 3072 bits
modulusLength: 3072,

//print RSA public key and private key
type: "pkcs1",
format: "pem",

type: "pkcs1",
format: "pem",

// This is our secret data
const secretData = "Your Secret"

const encryptedData = crypto.publicEncrypt(
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha512",
// Converting string to a buffer
Buffer.from(secretData, 'utf-8')


//print encrypted data it in base64 format
console.log("encypted data: ", encryptedData.toString("base64"))

const decryptedData = crypto.privateDecrypt(
key: privateKey,
// decrypt the data
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha512",

// Converting buffer type to a string(original string)
console.log("decrypted data: ", decryptedData.toString())

Run the Node.js application & Verify the output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Spring Boot + Mockito simple application with 100% code coverage

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

Spring boot video streaming example-HTML5

ReactJS, Spring Boot JWT Authentication Example

Java - Blowfish Encryption and decryption Example

Custom Exception Handling in Quarkus REST API

Spring Boot + OpenCSV Export Data to CSV Example