Node.js 中的 crypto.publicEncrypt() 方法
在用于通过使用在参数传递的公共密钥在缓冲区参数给定的数据进行加密。返回的数据可以使用相应的私钥解密。crypto.publicEncrypt()
语法
crypto.publicEncrypt(key, buffer)
参数
上述参数描述如下-
key –它可以包含以下5种类型的数据–Object、String、Buffer或KeyObject。
key –此字段包含PEM编码的公钥或私钥。它可以是字符串、缓冲区或keyObject类型。
oaepHash –该字段包含用于OAEP填充和MGF1的散列函数。默认值为:'sha1'。
oaepLabel –该字段包含OAEP填充的值。如果未指定,则不使用标签。
密码 -这是私钥的可选密码。
padding –这是在crypto.constants中定义的可选值。
encoding –这是当缓冲区、密钥、oaepLabel或密码值是字符串时需要使用的编码类型。
buffer –该字段包含要加密的数据内容。可能的缓冲区类型有:string、TypedArray、Buffer、ArrayBuffer、DataView。
示例
创建一个具有名称的文件-publicEncrypt.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示-
node publicEncrypt.js
公共加密.js
//Node.js程序演示crypto.publicEncrypt()方法的流程
//导入加密和fs模块
const crypto = require('crypto');
const fs = require("fs");
//创建以下用于生成密钥的函数
function generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 520,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: ''
}
});
//使用以下名称创建公钥文件
fs.writeFileSync("public_key", keyPair.publicKey);
}
//生成密钥
generateKeyFiles();
//使用以下函数加密字符串
function encryptString (plaintext, publicKeyFile) {
const publicKey = fs.readFileSync(publicKeyFile, "utf8");
//使用以下参数调用publicEncrypt()
const encrypted = crypto.publicEncrypt(
publicKey, Buffer.from(plaintext));
return encrypted.toString("base64");
}
//将被加密的文本
const plainText = "nhooo";
//定义加密文本
const encrypted = encryptString(plainText, "./public_key");
//打印纯文本
console.log("Plaintext:", plainText);
//打印加密文本
console.log("Encrypted: ", encrypted);输出结果C:\home\node>> node publicEncrypt.js Plaintext: nhooo Encrypted: kgnqPxy/n34z+/5wd7MZiMAL5LrQisTLfZiWoSChXSvxgtifMQaZ56cbF+twA55olM0rFfnuV6qqtc a8SXIHQrk=
示例
让我们再看一个例子。
//Node.js程序演示crypto.publicEncrypt()方法的流程
//导入加密和fs模块
const crypto = require('crypto');
const fs = require("fs");
//创建以下用于生成密钥的函数
function generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 520,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: ''
}
});
//创建公钥文件
fs.writeFileSync("public_key", keyPair.publicKey);
}
//生成密钥
generateKeyFiles();
//使用以下函数加密字符串
function encryptString (plaintext, publicKeyFile) {
const publicKey = fs.readFileSync(publicKeyFile, "utf8");
//使用以下参数调用publicEncrypt()
const encrypted = crypto.publicEncrypt(
publicKey, Buffer.from(plaintext));
return encrypted;
}
//将被加密的文本
const plainText = "你好教程点!";
//定义加密文本
const encrypted = encryptString(plainText, "./public_key");
//打印纯文本
console.log("Plaintext:", plainText);
//打印加密缓冲区
console.log("Buffer: ", encrypted);输出结果C:\home\node>> node publicEncrypt.js Plaintext: 你好教程点! Buffer: