Node.js crypto.publicDecrypt() Method - GeeksforGeeks

11 Oct, 2021
The crypto.publicDecrypt() method is used to decrypt the content of the buffer with key which was previously encrypted using the corresponding private key, i.e. crypto.privateEncrypt() method.
Syntax:
crypto.publicDecrypt( key, buffer )
Parameters: This method accept two parameters as mentioned avobe and described below:
key: It is of type Object, string, Buffer, or KeyObject and contains two parameters which are as follows:passphrase: It is an optional for the private key and it is of type 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.
passphrase: It is an optional for the private key and it is of type 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.
passphrase: It is an optional for the private key and it is of type 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 is of type Buffer, TypedArray, or DataView.
Return Type: It returns a new Buffer with the decrypted content.
Below examples illustrate the use of crypto.publicDecrypt() method in Node.js:
Example 1:
// Node.js program to demonstrate the // crypto.publicDecrypt() method  // Including crypto, path, and fs modulevar crypto = require('crypto');var fs = require('fs');const path = require('path');  // Generating key filesfunction 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 and private key file     fs.writeFileSync("public_key", keyPair.publicKey);    fs.writeFileSync("private_key", keyPair.privateKey);}  // Generate keysgenerateKeyFiles();  // Reading private key filevar PRIVKEY = fs.readFileSync(path.join(__dirname,                          'private_key'), 'utf8');  // Reading public key filevar PUBKEY = fs.readFileSync(path.join(__dirname,                          'public_key'), 'utf8');  // Defining my msgmyMSG = "GeeksforGeeks!";console.log("Original msg is : "+myMSG);  // RSA PRIVATE ENCRYPT -> PUBLIC DECRYPTfunction privENC_pubDEC(originMSG){    // Encrypting msg with privateEncrypt method encmsg = crypto.privateEncrypt(PRIVKEY,               Buffer.from(originMSG, 'utf8') ).toString('base64');   // Decrypting msg with publicDecrypt method msg = crypto.publicDecrypt(PUBKEY,              Buffer.from(encmsg, 'base64'));   console.log();   // Prints encrypted msg console.log("Encrypted with private key: "                      + encmsg);   console.log();   // Prints decrypted msg console.log("Decrypted with public key: "                     + msg.toString());}  // Calling privENC_pubDEC() methodprivENC_pubDEC(myMSG);
Output:
Original msg is : GeeksforGeeks!

Encrypted with private key:
knwqke0ZrpJj1sLtL978OyqBMnJUEAEgTy1qJbyEnJyWbjoQ6hO7f
2FPnVhJnZwpZlxLbFQZCV1GMmr6WWJenFo=

Decrypted with public key: GeeksforGeeks!

Example 2:
// Node.js program to demonstrate the // crypto.publicDecrypt() method  // Including the fs and crypto modulesvar crypto = require('crypto');var fs = require('fs');  // Reading the Private KeyprivK = fs.readFileSync('priv.key').toString();  // Passing the text to be encrypted// using private keyvar buf = Buffer.from('rishabh', 'utf8');  // Encrypting the textsecretData = crypto.privateEncrypt(privK, buf);  // Printing the encrypted textconsole.log(secretData);  // Reading the Public keypubK = fs.readFileSync('pub.key').toString();  // Decrypting the text using public keyorigData = crypto.publicDecrypt(pubK, secretData);  // Printing the original contentconsole.log(origData);
Output:
// Buffer 27 62 a1 2a 53 8d 0d 52 c7 3f e8 cc 89 42 c6
3e 8e 60 cd d3 57 06 d4 c9 1e 31 ba e6 23 8b 2c 10 be 
c1 fc ed 53 a4 9f f9 e0 5b da 74 d7 c2ca d0 98 f4 ... 
// Buffer 72 69 73 68 61 62 68

Reference: https://nodejs.org/api/crypto.html#crypto_crypto_publicdecrypt_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.
Node.js Export Module
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript