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
console.log(
publicKey.export({
type: "pkcs1",
format: "pem",
}),

privateKey.export({
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",
},
encryptedData
)

// 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?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

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

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete