Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
crypto.privateDecrypt() Method in Node.js
The crypto.privateDecrypt() method is used for decrypting data that was previously encrypted using the corresponding public key with crypto.publicEncrypt(). This method is essential for implementing asymmetric encryption in Node.js applications.
Syntax
crypto.privateDecrypt(privateKey, buffer)
Parameters
The method accepts the following parameters:
-
privateKey - Can be an Object, String, Buffer, or KeyObject containing:
oaepHash - Hash function for OAEP padding and MGF1. Default: 'sha1'
oaepLabel - Label for OAEP padding. No label if not specified
padding - Optional padding value from crypto.constants
buffer - The encrypted data to decrypt. Can be string, TypedArray, Buffer, ArrayBuffer, or DataView
Example 1: Basic Encryption and Decryption
This example demonstrates the complete flow from encryption to decryption using public and private keys:
// Node.js program to demonstrate crypto.privateDecrypt() method
const crypto = require('crypto');
const fs = require('fs');
// Reading the Public Key
// You can generate these keys using generateKeyPair()
const publicKey = fs.readFileSync('public_key').toString();
// Text to be encrypted
const buf = Buffer.from('Hello TutorialsPoint', 'utf8');
// Encrypting the text with public key
const secretData = crypto.publicEncrypt(publicKey, buf);
// Printing the encrypted data
console.log('Encrypted data:');
console.log(secretData);
// Reading the Private key
const privateKey = fs.readFileSync('private_key').toString();
// Decrypting the encrypted data with private key
const origData = crypto.privateDecrypt(privateKey, secretData);
console.log('\nDecrypted data:');
console.log(origData);
console.log('\nDecrypted text:', origData.toString());
Encrypted data: <Buffer 15 4b 51 02 e7 1c ec 11 20 55 ee 92 b2 18 7b ce f1 e1 97 bd b7 0d 54 21 18 ea 0c e7 cd 51 36 f5 13 df fb 41 c1 63 bb ac ee 94 12 df f6 d6 04 b1 9c 11 ... > Decrypted data: <Buffer 48 65 6c 6c 6f 20 54 75 74 6f 72 69 61 6c 73 50 6f 69 6e 74> Decrypted text: Hello TutorialsPoint
Example 2: Complete Key Generation and Encryption Flow
This example shows how to generate key pairs, encrypt data, and decrypt it back to the original text:
// Node.js program demonstrating complete encryption/decryption flow
const crypto = require('crypto');
const fs = require('fs');
// Generate RSA key pair
function generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: ''
}
});
// Write keys to files
fs.writeFileSync("public_key", keyPair.publicKey);
fs.writeFileSync("private_key", keyPair.privateKey);
}
// Encrypt string using public key
function encryptString(plaintext, publicKeyFile) {
const publicKey = fs.readFileSync(publicKeyFile, "utf8");
const encrypted = crypto.publicEncrypt(
publicKey,
Buffer.from(plaintext)
);
return encrypted.toString("base64");
}
// Decrypt string using private key
function decryptString(ciphertext, privateKeyFile) {
const privateKey = fs.readFileSync(privateKeyFile, "utf8");
const decrypted = crypto.privateDecrypt(
{
key: privateKey,
passphrase: '',
},
Buffer.from(ciphertext, "base64")
);
return decrypted.toString("utf8");
}
// Generate key files
generateKeyFiles();
const plainText = "TutorialsPoint!";
// Encrypt the text
const encrypted = encryptString(plainText, "./public_key");
console.log("Plaintext:", plainText);
console.log();
console.log("Encrypted Text:", encrypted);
console.log();
console.log("Decrypted Text:", decryptString(encrypted, "private_key"));
Plaintext: TutorialsPoint! Encrypted Text: AbSrqG4qFBG1q9KUBt8ddJxk9uNanOHXqY19N0mNHx0fm4M119dZVhcNrAvM8UaIRJvh7AsdWyjv1s cPA25KpeJuJQ== Decrypted Text: TutorialsPoint!
Key Points
Data encrypted with a public key can only be decrypted with the corresponding private key
The method returns a Buffer containing the decrypted data
Use
toString()to convert the Buffer back to readable textEnsure proper key management and secure storage of private keys
Conclusion
The crypto.privateDecrypt() method is essential for asymmetric decryption in Node.js. Always pair it with crypto.publicEncrypt() and ensure secure handling of private keys in production applications.
