Open In App

Node.js crypto.publicEncrypt() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The crypto.publicEncrypt() method is an inbuilt application programming interface of the crypto module which is used to encrypt the stated content of the buffer with the parameter ‘key’.

Syntax:

crypto.publicEncrypt( key, buffer )

Parameters: This method accept two parameters as mentioned above and described below:

  • key: This parameter holds Object, string, Buffer, or KeyObject type of data and contains five parameters which are as follows:
    1. key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.
    2. oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.
    3. oaepLabel: It is the label which is used for ‘OAEP’ padding. And if it’s not specified, then no label is used. It is of type Buffer, TypedArray or DataView.
    4. passphrase: It is an optional passphrase for the private key which is either string or buffer.
    5. padding: It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING. It is of type crypto.constants.
  • buffer: It is of type Buffer, TypedArray, or DataView.

Return Value: It returns a new Buffer with the encrypted content.

Below example illustrate the use of crypto.publicEncrypt() method in Node.js:

Example 1:




// Node.js program to demonstrate the 
// crypto.publicEncrypt() method
  
// Including crypto and fs module
const crypto = require('crypto');
const fs = require("fs");
  
// Using a function generateKeyFiles
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 public key file 
    fs.writeFileSync("public_key", keyPair.publicKey);
}
  
// Generate keys
generateKeyFiles();
  
// Creating a function to encrypt string
function encryptString (plaintext, publicKeyFile) {
    const publicKey = fs.readFileSync(publicKeyFile, "utf8");
  
    // publicEncrypt() method with its parameters
    const encrypted = crypto.publicEncrypt(
         publicKey, Buffer.from(plaintext));
    return encrypted.toString("base64");
}
  
// Defining a text to be encrypted
const plainText = "GfG";
  
// Defining encrypted text
const encrypted = encryptString(plainText, "./public_key");
  
// Prints plain text
console.log("Plaintext:", plainText);
  
// Prints encrypted text
console.log("Encrypted: ", encrypted);


Output:

Plaintext: GfG
Encrypted:  l0touwFaNv1DIgPE365VQD0G4rg+IbRD5G6IBQ1arLgWtFOStKO7duYJ6/JzlOJl3eBG7obqzAEJ0V2WrxtYRTg=

Example 2:




// Node.js program to demonstrate the 
// crypto.publicEncrypt() method
  
// Including crypto and fs module
const crypto = require('crypto');
const fs = require("fs");
  
// Using a function generateKeyFiles
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 public key file 
    fs.writeFileSync("public_key", keyPair.publicKey);
}
  
// Generate keys
generateKeyFiles();
  
// Creating a function to encrypt string
function encryptString (plaintext, publicKeyFile) {
    const publicKey = fs.readFileSync(publicKeyFile, "utf8");
  
    // publicEncrypt() method with its parameters
    const encrypted = crypto.publicEncrypt(
             publicKey, Buffer.from(plaintext));
    return encrypted;
}
  
// Defining a text to be encrypted
const plainText = "Hello!";
  
// Defining encrypted text
const encrypted = encryptString(plainText, "./public_key");
  
// Prints plain text
console.log("Plaintext:", plainText);
  
// Prints buffer
console.log("Buffer: ", encrypted);


Output:

Plaintext: Hello!
Buffer: <Buffer 1b 2a c7 4d 10 44 45 8e 9d e6
53 9d 8a 5e 39 0f ea e2 96 00 d7 d3 b3 eb 54 7e
74 7d a4 62 b8 eb 68 85 cb 8e 85 a5 f7 71 2f b7
93 d6 14 1c 38 cd 45 85 ... >

Reference: https://nodejs.org/api/crypto.html#crypto_crypto_publicencrypt_key_buffer



Last Updated : 11 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads