Welcome to the Ultimate Guide to Node-RSA
Node-RSA is a robust library for Node.js that allows you to perform various RSA encryption and decryption operations with ease. In this guide, we’ll introduce you to Node-RSA and share dozens of API explanations with code snippets to help you get started quickly.
Installation
To get started, install the node-rsa package using npm:
npm install node-rsa
Generating and Importing Keys
Create a new RSA key and import an existing key:
const NodeRSA = require('node-rsa');
// Generate a new 2048-bit key
const key = new NodeRSA({b: 2048});
// Import an existing PEM-formatted key
const existingKey = new NodeRSA('-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----', 'pkcs8-private-pem');
Encrypting and Decrypting Data
Encrypt and decrypt data with your RSA key:
// Encrypt data
const encrypted = key.encrypt("Hello RSA", "base64");
console.log("Encrypted:", encrypted);
// Decrypt data
const decrypted = key.decrypt(encrypted, "utf8");
console.log("Decrypted:", decrypted);
Signing and Verifying Signatures
Sign data and verify signatures:
// Sign data
const signature = key.sign("message", "base64");
console.log("Signature:", signature);
// Verify signature
const isVerified = key.verify("message", signature, "utf8", "base64");
console.log("Verified:", isVerified);
Examples of Different Key Formats
Export your keys in various formats:
// Export key to PEM format
const privateKey = key.exportKey('private');
const publicKey = key.exportKey('public');
// Export key to DER format
const privateKeyDER = key.exportKey('pkcs8-private-der');
const publicKeyDER = key.exportKey('public-der');
console.log("Private Key PEM:", privateKey);
console.log("Public Key PEM:", publicKey);
console.log("Private Key DER:", privateKeyDER);
console.log("Public Key DER:", publicKeyDER);
Full App Example
Here’s a full example demonstrating how to use the APIs introduced above in a simple app:
const NodeRSA = require('node-rsa');
// Generate and configure key
const key = new NodeRSA({b: 2048});
const publicKey = key.exportKey('public');
const privateKey = key.exportKey('private');
// Encrypt message
const plaintext = "Hello, world!";
const encrypted = key.encrypt(plaintext, "base64");
// Decrypt message
const decrypted = key.decrypt(encrypted, "utf8");
// Sign and verify message
const signature = key.sign(plaintext, "base64");
const isVerified = key.verify(plaintext, signature, "utf8", "base64");
console.log("Public Key:", publicKey);
console.log("Private Key:", privateKey);
console.log("Encrypted:", encrypted);
console.log("Decrypted:", decrypted);
console.log("Signature:", signature);
console.log("Verified:", isVerified);
With these practical examples, you can begin to harness the powerful features of Node-RSA in your applications. Start right away and implement secure encryption, decryption, and data signing in your Node.js projects.
Hash: ed14f17ce242152e7da6f5c16f33831dcfb942fc7f7736d4a988eee31c0af782