使用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();

但是经过数小时的搜索,我似乎找不到使用公钥加密数据的方法.在php中,我只是调用openssl_public_encrypt,但在节点或任何模块中都看不到任何对应的功能.

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 or in any modules.

如果有人有任何建议,请告诉我.

If anyone has any suggestions, let me know.

没有图书馆必要的朋友,

No library necessary friends,

输入密码

这是一个简单的小模块,可用于使用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方法,并且可以使用Promises使它更好,但是对于简单的用例,这是我见过的并且会采用的方法

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