Node.js crypto.publicEncrypt() Method - GeeksforGeeks

11 Oct, 2021
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:key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.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.passphrase: It is an optional passphrase for the private key which is either string or buffer.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.
key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.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.passphrase: It is an optional passphrase for the private key which is either string or buffer.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.
key: It is a ‘PEM’ encoded public key or private key. It is of type string, Buffer, and KeyObject.
oaepHash: It is the hash function of type string which is used for ‘OAEP’ padding. And the default value is ‘sha1’.
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.
passphrase: It is an optional passphrase for the private key which is either string or buffer.
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 moduleconst crypto = require('crypto');const fs = require("fs");  // Using a function generateKeyFilesfunction 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 keysgenerateKeyFiles();  // Creating a function to encrypt stringfunction 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 encryptedconst plainText = "GfG";  // Defining encrypted textconst encrypted = encryptString(plainText, "./public_key");  // Prints plain textconsole.log("Plaintext:", plainText);  // Prints encrypted textconsole.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 moduleconst crypto = require('crypto');const fs = require("fs");  // Using a function generateKeyFilesfunction 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 keysgenerateKeyFiles();  // Creating a function to encrypt stringfunction 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 encryptedconst plainText = "Hello!";  // Defining encrypted textconst encrypted = encryptString(plainText, "./public_key");  // Prints plain textconsole.log("Plaintext:", plainText);  // Prints bufferconsole.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
Node.js-crypto-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
Node.js fs.readdirSync() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript