Node.js crypto.privateEncrypt() Method - GeeksforGeeks

11 Oct, 2021
The crypto.privateEncrypt() method is used to encrypt the stated content of the buffer with the parameter ‘privateKey’.
Syntax:
crypto.privateEncrypt( privateKey, buffer )
Parameters: This method accept two parameters as mentioned above and described below:
privateKey: It can hold Object, string, Buffer, or KeyObject type of data.key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.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, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants.
key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.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, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants.
key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.
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, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants.
buffer: It contains Buffer, TypedArray, or DataView type of data.
Return Value: It returns a new Buffer with the encrypted content.
Below example illustrate the use of crypto.privateEncrypt() method in Node.js:
Example 1:
// Node.js program to demonstrate the // crypto.privateEncrypt() 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 private key file     fs.writeFileSync("private_key", keyPair.privateKey);}  // Generate keysgenerateKeyFiles();  // Creating a function to encrypt stringfunction encryptString (plaintext, privateKeyFile) {    const privateKey = fs.readFileSync(privateKeyFile, "utf8");      // privateEncrypt() method with its parameters    const encrypted = crypto.privateEncrypt(          privateKey, Buffer.from(plaintext));      return encrypted.toString("base64");}  // Defining a text to be encryptedconst plainText = "GfG";  // Defining encrypted textconst encrypted = encryptString(plainText, "./private_key");  // Prints plain textconsole.log("Plaintext:", plainText);  // Prints encrypted textconsole.log("Encrypted: ", encrypted);
Output:
Plaintext: GfG
Encrypted:  c60eR17GTQFkTI1ipTq5qFbYS58lIQqpDiou2UlYeOUE+u7agbtHvvwKaBpzBx4SvTCh5abpaqmyXCyGcUpGc7s=

Example 2:
// Node.js program to demonstrate the // crypto.privateEncrypt() 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 private key file     fs.writeFileSync("private_key", keyPair.privateKey);}  // Generate keysgenerateKeyFiles();  // Creating a function to encrypt stringfunction encryptString (plaintext, privateKeyFile) {    const privateKey = fs.readFileSync(privateKeyFile, "utf8");      // privateEncrypt() method with its parameters    const encrypted = crypto.privateEncrypt(         privateKey, Buffer.from(plaintext));      // Returns buffer as its not encoded    return encrypted;}  // Defining a text to be encryptedconst plainText = "GfG";  // Defining encrypted textconst encrypted = encryptString(plainText, "./private_key");  // Prints plain textconsole.log("Plaintext:", plainText);  // Prints encrypted textconsole.log("Encrypted buffer: ", encrypted);
Output:
Plaintext: GfG
Encrypted buffer:  <Buffer 14 e5 84 05 2f b5 59 64
22 d2 19 99 f9 66 e5 18 50 76 27 df 0b e6 9f 50 1d a2
51 6a 93 21 04 7b 8f 50 ba 11 82 fd 3c 6e c0 81 be 58
f9 d6 a6 c7 19 da ... >

Reference: https://nodejs.org/api/crypto.html#crypto_crypto_privateencrypt_privatekey_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.
Comments
Old Comments
Node.js path.resolve() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Node.js fs.readdir() Method
Express.js res.render() Function
Node.js First Application
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page?