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.js or in any modules.
Public key encryption One key is nominated as the private key and is kept secret. The other key is distributed to anyone who wants it; this key is the public key. Anyone can encrypt a message by using your public key, but only you can read it. When you receive the message, you decrypt it by using your private key.
You use symmetric encryption if you encrypt and decrypt data using the same key. Asymmetric encryption is used if different keys are used for encryption and decryption. To protect data in Node. js applications, you have to store the hashed passwords in the database.
RSA(Rivest-Shamir-Adleman) is an Asymmetric encryption technique that uses two different keys as public and private keys to perform the encryption and decryption. With RSA, you can encrypt sensitive information with a public key and a matching private key is used to decrypt the encrypted message.
A library is not necessary. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With