📜  Node.js crypto.privateDecrypt() 方法

📅  最后修改于: 2022-05-13 01:56:42.175000             🧑  作者: Mango

Node.js crypto.privateDecrypt() 方法

crypto.privateDecrypt() 方法用于使用privateKey.buffer解密缓冲区的内容,该缓冲区之前使用相应的公钥加密,即 crypto.publicEncrypt()。

句法:

crypto.privateDecrypt( privateKey, buffer )

参数:此方法接受上面提到的两个参数,如下所述:

  • privateKey:可以保存 Object、 字符串 、Buffer 或 KeyObject 类型的数据。
    1. oaepHash它是字符串类型的散列函数,用于“OAEP”填充。默认值为'sha1'。
    2. oaepLabel:它是用于“OAEP”填充的标签。如果未指定,则不使用标签。它是Buffer、TypedArray 或 DataView类型。
    3. padding:它是在crypto.constants中定义的可选填充值,可以是crypto.constants.RSA_NO_PADDING、crypto.constants.RSA_PKCS1_PADDING或crypto.constants.RSA_PKCS1_OAEP_PADDING。它是crypto.constants类型。
  • 缓冲区:它的类型为Buffer、TypedArray 或 DataView

返回值:它返回一个带有解密内容的新 Buffer。

下面的示例说明了在 Node.js 中使用crypto.privateDecrypt() 方法

示例 1:

// Node.js program to demonstrate the 
// crypto.privateDecrypt() method
  
// Including the crypto and fs modules
var crypto = require('crypto');
var fs = require('fs');
  
// Reading the Public Key
pubK = fs.readFileSync('pub.key').toString();
  
// Passing the text to be encrypted using private key
var buf = Buffer.from('This is secret code', 'utf8');
  
// Encrypting the text
secretData = crypto.publicEncrypt(pubK, buf);
  
// Printing the encrypted text
console.log(secretData);
  
// Reading the Private key
privK = fs.readFileSync('priv.key').toString();
  
// Decrypting the text using public key
origData = crypto.privateDecrypt(privK, secretData);
console.log();
  
// Printing the original content
console.log(origData);

输出:




示例 2:

// Node.js program to demonstrate the 
// crypto.privateDecrypt() 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: 530,
        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 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");
}
  
// Creating a function to decrypt string
function decryptString (ciphertext, privateKeyFile) {
    const privateKey = fs.readFileSync(privateKeyFile, "utf8");
  
    // privateDecrypt() method with its parameters
    const decrypted = crypto.privateDecrypt(
      {
        key: privateKey,
        passphrase: '',
      },
      Buffer.from(ciphertext, "base64")
    );
  
    return decrypted.toString("utf8");
}
  
// Defining a text to be encrypted
const plainText = "Geeks!";
  
// Defining encrypted text
const encrypted = encryptString(plainText, "./public_key");
  
// Prints plain text
console.log("Plaintext:", plainText);
console.log();
  
// Prints buffer of encrypted content
console.log("Encrypted Text: ", encrypted);
console.log();
  
// Prints buffer of decrypted content
console.log("Decrypted Text: ", 
    decryptString(encrypted, "private_key"));

输出:

Plaintext: Geeks!

Encrypted Text:  ACks6H7InpaeGdI4w9MObyD73YB7N1V0nVsG5Jl10SNeH3no6gfgjeD4ZFsSFhCXzFkognMGbRNsg0BReVOHxRs7eQ==

Decrypted Text: Geeks!

参考: https://nodejs.org/api/crypto.html#crypto_crypto_privatedecrypt_privatekey_buffer