Encrypting data with Public Key in node.js


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

I am loading the pem files fine:

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

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.

1/5/2012 10:26:44 PM

Accepted Answer

No library necessary friends,

Enter crypto

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

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

2/11/2019 7:55:44 PM

The updated public/private decrypt and encryption module is URSA. node-rsa module is outdated.

This Node module provides a fairly complete set of wrappers for the RSA public/private key crypto functionality of OpenSSL.

npm install ursa

See: https://github.com/Obvious/ursa

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow