📜  Node.js crypto.publicEncrypt() 方法

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

Node.js crypto.publicEncrypt() 方法

crypto.publicEncrypt() 方法是加密模块的内置应用程序编程接口,用于使用参数“密钥”加密缓冲区的规定内容。

句法:

crypto.publicEncrypt( key, buffer )

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

  • key:该参数保存 Object、 字符串、Buffer 或 KeyObject 类型的数据,包含以下五个参数:
    1. 密钥:它是一个“PEM”编码的公钥或私钥。它的类型为字符串 、 Buffer 和 KeyObject
    2. oaepHash:它是字符串类型的哈希函数,用于“OAEP”填充。默认值为'sha1'。
    3. oaepLabel:它是用于“OAEP”填充的标签。如果未指定,则不使用标签。它是Buffer、TypedArray 或 DataView类型。
    4. 密码:它是私钥的可选密码,可以是字符串或缓冲区。
    5. 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.publicEncrypt() 方法的使用:

示例 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);

输出:

Plaintext: GfG
Encrypted:  l0touwFaNv1DIgPE365VQD0G4rg+IbRD5G6IBQ1arLgWtFOStKO7duYJ6/JzlOJl3eBG7obqzAEJ0V2WrxtYRTg=

示例 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);

输出:

Plaintext: Hello!
Buffer: 

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