crypto.publicEncrypt() Method in Node.js


The crypto.publicEncrypt() is used for encrypting the given data in buffer parameter by using a public key passed in the parameter. The data returned can be decrypted using the corresponding private key.

Syntax

crypto.publicEncrypt(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.

    • key – This field contains the PEM encoded public or private key. It can be of type 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.

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

publicEncrypt.js

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

// Importing crypto and fs module
const crypto = require('crypto');
const 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);
}
// Generating keys
generateKeyFiles();

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

   //Calling publicEncrypt() with below parameters
   const encrypted = crypto.publicEncrypt(
      publicKey, Buffer.from(plaintext));
   return encrypted.toString("base64");
}

// Text that will be encrypted
const plainText = "TutorialsPoint";

// Defining the encrypted text
const encrypted = encryptString(plainText, "./public_key");

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

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

Output

C:\home
ode>> node publicEncrypt.js Plaintext: TutorialsPoint Encrypted: kgnqPxy/n34z+/5wd7MZiMAL5LrQisTLfZiWoSChXSvxgtifMQaZ56cbF+twA55olM0rFfnuV6qqtc a8SXIHQrk=

Example

Let's take a look at one more example.

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

// Importing crypto and fs module
const crypto = require('crypto');
const 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
   fs.writeFileSync("public_key", keyPair.publicKey);
}

// Generating keys
generateKeyFiles();

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

   //Calling publicEncrypt() with below parameters
   const encrypted = crypto.publicEncrypt(
      publicKey, Buffer.from(plaintext));
   return encrypted;
}

// Text that will be encrypted
const plainText = "Hello TutorialsPoint!";

// Defining the encrypted text
const encrypted = encryptString(plainText, "./public_key");

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

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

Output

C:\home
ode>> node publicEncrypt.js Plaintext: Hello TutorialsPoint! Buffer: <Buffer 33 0b 54 96 0e 8f 34 6c b4 d5 7a cf d4 d5 ef 7b 7e c5 ec 97 cf 75 05 07 df 5a 9e d4 3d cc 3e bb 55 e7 50 1b 64 f0 c8 89 19 61 81 99 e5 88 10 4a 3b 5a ... >

Updated on: 20-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements