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

标签 node.js public-key-encryption encryption-asymmetric

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

我正在加载 .pem 文件:

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

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

最佳答案

库不是必需的。输入 crypto .

这是一个 janky 小模块,您可以使用 RSA key 来加密/解密字符串:

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为了让它变得更好,但对于简单的用例,这是我见过的并且会采用的方法。

关于node.js - 在 Node.js 中使用公钥加密数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8750780/

相关文章:

node.js - Nodejs node-sqlite3 运行回调不起作用

JavaScript 变量生命周期

node.js - socket.io 一直出现 404ing?

putty - 选美似乎有干扰,根本不起作用

security - 使用公钥和私钥的 SSH 通信

powershell - TPM 和私钥保护

javascript - 使用 WebCrypto API 从私钥生成公钥

使用私钥和 PKCS1 的 PHP RSA 加密

node.js - 如何安装 Node.js、npm、socket.io 并使用它们?

c# - .NET 中的 RSA 加密 - JAVA 中的解密 -> Java 抛出 "modulus not positive"错误