Open In App

Node.js crypto.publicEncrypt() Method

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:

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


Article Tags :