crypto.privateDecrypt() Method in Node.js


The crypto.privateDecrypt() is used for decrypting the given data content by using a private key passed in the parameter that was previously encrypted using the corresponding public key with crypto.publicEncrypt() method.

Syntax

crypto.privateDecrypt(privateKey, buffer)

Parameters

The above parameters are described as below −

  • key – It can contain the below 5 types of data of the following type – Object, String, Buffer or KeyObject.

    • oaepHash – This field contains the hash function to be used for OAEP padding and MGF1. Default value is: 'sha1'.

    • oaepLabel – This field contains the value for OAEP padding. No lable is used if not specified.

    • padding – This is an optional value defined in crypto.constants.

  • buffer – This field contains the data content to be decrypted. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView.

Example

Create a file with name – privateDecrypt.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node privateDecrypt.js

privateDecrypt.js

// Node.js program to demonstrate the flow of crypto.privateDecrypt() method

// Importing crypto and fs module
const crypto = require('crypto');
const fs = require("fs");

// Reading the Public Key.
//You can generate these keys using generateKeyPair()
publicKey = fs.readFileSync('public_key').toString();

// Passing the below text to be encrypted
var buf = Buffer.from('Hello TutorialsPoint', 'utf8');

// Encrypting the above text
secretData = crypto.publicEncrypt(publicKey, buf);

// Printing the encrypted text
console.log(secretData);

// Reading the Private key
privateKey = fs.readFileSync('private_key').toString();

// Decrypting the encrypted text
origData = crypto.privateDecrypt(privateKey, secretData);
console.log();

// Printing the original text as buffer
console.log(origData);

Output

C:\home
ode>> node privateDecrypt.js <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 ... > <Buffer 48 65 6c 6c 6f 20 54 75 74 6f 72 69 61 6c 73 50 6f 69 6e 74>

Example

Let's take a look at one more example.

// Node.js program to demonstrate the flow of crypto.privateDecrypt() method

// Importing crypto and fs module
const crypto = require('crypto');
const fs = require("fs");

// Generating key files using generateKeyPairSync() method
function generateKeyFiles() {
   const keyPair = crypto.generateKeyPairSync('rsa', {
      modulusLength: 530,
      publicKeyEncoding: {
         type: 'spki',
         format: 'pem'
      },
      privateKeyEncoding: {
         type: 'pkcs8',
         format: 'pem',
         cipher: 'aes-256-cbc',
         passphrase: ''
      }
   });
   // Writing the keys in the following files
   fs.writeFileSync("public_key", keyPair.publicKey);
   fs.writeFileSync("private_key", keyPair.privateKey);
}

// Calling Generate keys method
generateKeyFiles();

// Encrypting the pased string
function encryptString (plaintext, publicKeyFile) {
   const publicKey = fs.readFileSync(publicKeyFile, "utf8");

   // Encrypting data using publicEncrypt() method and a public key
   const encrypted = crypto.publicEncrypt(
      publicKey, Buffer.from(plaintext));

   return encrypted.toString("base64");
}

// Decrypting the passed string with private Key
function decryptString (ciphertext, privateKeyFile) {
   const privateKey = fs.readFileSync(privateKeyFile, "utf8");

   // Decrypting data using privateDecrypt() method
   // and the corresponding private key
   const decrypted = crypto.privateDecrypt(
      {
         key: privateKey,
         passphrase: '',
      },
      Buffer.from(ciphertext, "base64")
   );
   return decrypted.toString("utf8");
}

// Following data will be encrypted and decrypted
const plainText = "TutorialsPoint!";

// Calling the below method to encrypt string
const encrypted = encryptString(plainText, "./public_key");

// Printing the plain text
console.log("Plaintext:", plainText);
console.log();

// Printing the encrypted text
console.log("Encrypted Text: ", encrypted);
console.log();

// Printing the decrypted text
console.log("Decrypted Text: ",
   decryptString(encrypted, "private_key"));

Output

C:\home
ode>> node privateDecrypt.js Plaintext: TutorialsPoint! Encrypted Text: AbSrqG4qFBG1q9KUBt8ddJxk9uNanOHXqY19N0mNHx0fm4M119dZVhcNrAvM8UaIRJvh7AsdWyjv1s cPA25KpeJuJQ== Decrypted Text: TutorialsPoint!

Updated on: 20-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements