crypto.publicDecrypt() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The crypto.publicDecrypt() is used for decrypting the given data in buffer with public key. This buffer was encrypted by using the corresponding private key i.e. crypto.privateEncrypt() method.

Syntax

crypto.publicDecrypt(key, 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.

    • passphrase - This is an optional passphrase for the private key.

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

    • encoding – This is the type of encoding that needs to be used when buffer, key, oaepLabel or passphrase value are strings.

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

Example

Create a file with name – publicDecrypt.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 publicDecrypt.js

publicDecrypt.js

// crypto.publicDecrypt Demo Example

// Importing the crypto, fs and path module
var crypto = require('crypto');
var fs = require('fs');
const path = require('path');

// Creating below function for generating keys
function generateKeyFiles() {

   const keyPair = crypto.generateKeyPairSync('rsa', {
      modulusLength: 520,
      publicKeyEncoding: {
         type: 'spki',
         format: 'pem'
      },
      privateKeyEncoding: {
         type: 'pkcs8',
         format: 'pem',
         cipher: 'aes-256-cbc',
         passphrase: ''
      }
   });

   // Creating the public key file with the below name
   fs.writeFileSync("public_key", keyPair.publicKey);
   fs.writeFileSync("private_key", keyPair.privateKey);
}

// Calling Generate keys method
generateKeyFiles();

// Reading the Private and Public Key
var private = fs.readFileSync('private_key');
var public = fs.readFileSync('public_key');

// Defining the original data
var data = 'Welcome to TutorialsPoint';
console.log("Original Data is: "+data);

// Encrypting the data using private key
encrypted = crypto.privateEncrypt(private, Buffer.from(data, 'utf8')).toString('base64');

// Decrypting the data usig publicKey
originalData = crypto.publicDecrypt(public, Buffer.from(encrypted, 'base64'));

console.log();

// Printing encrypted msg
console.log("Encrypted with private key: " + encrypted);

console.log();

// Printing decrypted msg
console.log("Decrypted with public key: " + originalData.toString());

Output

C:\home\node>> node publicDecrypt.js
Original Data is: Welcome to TutorialsPoint

Encrypted with private key:
EFBihrKebXb0gfCF7nTnw82yXpToH5eVBpLc8O5QL/ZgfZ/qJT5I/BejSMwV4NFCp+AIKnz2lrjmFh
IhnpZWbF4=

Decrypted with public key: Welcome to TutorialsPoint

Example

Let's take a look at one more example.

// crypto.publicDecrypt Demo Example

// Importing the crypto and fs module
var crypto = require('crypto');
var fs = require('fs');

// Creating below function for generating keys
function generateKeyFiles() {

   const keyPair = crypto.generateKeyPairSync('rsa', {
      modulusLength: 520,
      publicKeyEncoding: {
         type: 'spki',
         format: 'pem'
      },
      privateKeyEncoding: {
         type: 'pkcs8',
         format: 'pem',
         cipher: 'aes-256-cbc',
         passphrase: ''
      }
   });

   // Creating the public key file with the below name
   fs.writeFileSync("public_key", keyPair.publicKey);
   fs.writeFileSync("private_key", keyPair.privateKey);
}

// Calling Generate keys method
generateKeyFiles();

// Reading the Private Key
privateKey = fs.readFileSync('private_key').toString();
var buffer = Buffer.from('Welcome to TutorialsPoint', 'utf8');
console.log("Data buffer before encryption")
console.log(buffer);

// Encrpting the buffer text
encrypted = crypto.privateEncrypt(privateKey, buffer);

// Printing the data after encryption
console.log("Data after encryption: ");
console.log(encrypted);

// Reading the Public key
publicKey = fs.readFileSync('public_key').toString();

// Decrypting the encrypted text using public key
decryptedData = crypto.publicDecrypt(publicKey, encrypted);

// Printing the original content
console.log("Data after decryption: ");
console.log(decryptedData);

Output

C:\home\node>> node publicDecrypt.js
Data buffer before encryption
<Buffer 57 65 6c 63 6f 6d 65 20 74 6f 20 54 75 74 6f 72 69 61 6c 73 50 6f 69
6e 74>
Data after encryption:
<Buffer a6 9d e3 86 9f 3f 4b b9 3f f7 a6 9c 7c 16 0f 04 b9 c4 16 0b 08 f1 06
39 de 32 75 7c 26 88 fa 49 bd 31 6b 4b 4d 02 e6 87 56 ee 9c 95 53 10 8f 28 49
f5 ... >
Data after decryption:
<Buffer 57 65 6c 63 6f 6d 65 20 74 6f 20 54 75 74 6f 72 69 61 6c 73 50 6f 69
6e 74>
raja
Published on 20-May-2021 12:50:22
Advertisements