在 Node.js 中使用公钥加密数据

问题描述:

我需要使用公钥(.pem 文件)加密字符串,然后使用私钥(也是 .pem 文件)对其进行签名.

I need to encrypt a string using a public key (.pem file), and then sign it using a private key (also a .pem).

我正在加载 .pem 文件:

I am loading the .pem files fine:

publicCert = fs.readFileSync(publicCertFile).toString();

但经过数小时的 Google 搜索后,我似乎找不到使用公钥加密数据的方法.在 PHP 中,我只是调用 openssl_public_encrypt(),但我在 Node.js 或任何模块中都没有看到任何相应的函数.

But after hours of scouring Google, I can't seem to find a way to encrypt data using the public key. In PHP I simply call openssl_public_encrypt(), but I don't see any corresponding function in Node.js or in any modules.

不需要库.输入 crypto.

这是一个可用于使用 RSA 密钥加密/解密字符串的简陋小模块:

Here's a janky little module you could use to encrypt/decrypt strings with RSA keys:

var crypto = require("crypto");
var path = require("path");
var fs = require("fs");

var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey) {
    var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
    var publicKey = fs.readFileSync(absolutePath, "utf8");
    var buffer = Buffer.from(toEncrypt);
    var encrypted = crypto.publicEncrypt(publicKey, buffer);
    return encrypted.toString("base64");
};

var decryptStringWithRsaPrivateKey = function(toDecrypt, relativeOrAbsolutePathtoPrivateKey) {
    var absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey);
    var privateKey = fs.readFileSync(absolutePath, "utf8");
    var buffer = Buffer.from(toDecrypt, "base64");
    var decrypted = crypto.privateDecrypt(privateKey, buffer);
    return decrypted.toString("utf8");
};

module.exports = {
    encryptStringWithRsaPublicKey: encryptStringWithRsaPublicKey,
    decryptStringWithRsaPrivateKey: decryptStringWithRsaPrivateKey
}

我建议尽可能不要使用同步 fs 方法,您可以使用 承诺会使它变得更好,但对于简单的用例,这是我已经看到并会采用的方法.

I would recommend not using synchronous fs methods where possible, and you could use promises to make this better, but for simple use cases this is the approach that I have seen work and would take.