crypto.privateEncrypt() Method in Node.js


The crypto.privateEncrypt() is used for encrypting the given data content by using the given private key parameter passed in the function.

Syntax

crypto.privateEncrypt(privateKey, buffer)

Parameters

The above parameters are described as below −

  • privateKey – It can contain following data types – Object, String, Buffer or KeyObject.

    • key – This key is a 'PEM' encoded private key. The key can be of type string, buffer or KeyObject.

    • passphrase – This is an optional passphrase value for the private key.

    • 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 – privateEncrypt.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 privateEncrypt.js

privateEncrypt.js

// Node.js program to demonstrate the flow of crypto.privateEncrypt() 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("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 privateEncrypt() method and a public key
   const encrypted = crypto.privateEncrypt(
      publicKey, Buffer.from(plaintext));

   return encrypted.toString("base64");
}

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

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

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

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

Output

C:\home
ode>> node privateEncrypt.js Plaintext: TutorialsPoint! Encrypted Text: AhphoL+l/e739LkdfCAm2XuiddgTG7jjdGlLviiRqD4LyTtxJmpkgq5bSkyI7Og4XlBtszBB9HLQRH T5j850ZAxGYA==

Example

Let's take a look at one more example.

// Node.js program to demonstrate the flow of crypto.privateEncrypt() 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("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 privateEncrypt() method and a public key
   const encrypted = crypto.privateEncrypt(
      publicKey, Buffer.from(plaintext));

   return encrypted;
}

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

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

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

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

Output

C:\home
ode>> node privateEncrypt.js Plaintext: TutorialsPoint! Encrypted Buffer: <Buffer 00 a2 ce 5d 27 d7 15 ec a7 bc 5b 12 73 62 92 82 6d f9 6b 82 38 06 dd bf b3 b8 1f 23 b4 d9 e9 aa 1c 50 0f c9 d7 12 f9 17 db 91 dc 05 46 b0 0c 08 14 50 ... >

Updated on: 20-May-2021

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements