Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active October 11, 2016 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/cd6bbfd3c81d76e6b3978ce9fbf845d2 to your computer and use it in GitHub Desktop.
Save branneman/cd6bbfd3c81d76e6b3978ce9fbf845d2 to your computer and use it in GitHub Desktop.
Node.js Public-key cryptography microlib :: Encypt against public key & Decrypt against private key
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
// Expose module
module.exports = { encrypt, decrypt };
/**
* Encypt against public key
* @param {String} str - The string to encrypt
* @param {String} pathToPublicKey - The path to the public key, in .pem format
* @example $ openssl rsautl -sign -inkey key.pem -in plain.txt -out encrypted.txt
* @returns {String}
*/
function encrypt(str, pathToPublicKey) {
const absolutePath = path.resolve(pathToPublicKey);
const publicKey = fs.readFileSync(absolutePath, 'utf8');
const encrypted = crypto.publicEncrypt(publicKey, new Buffer(str));
return encrypted.toString('base64');
}
/**
* Decrypt against private key
* @param {String} str - The string to decrypt
* @param {String} pathToPrivateKey - The path to the private key
* @example $ openssl rsautl -verify -inkey key.pem -in encrypted.txt -out decrypted.txt
* @returns {String}
*/
function decrypt(str, pathToPrivateKey) {
const absolutePath = path.resolve(pathToPrivateKey);
const privateKey = fs.readFileSync(absolutePath, 'utf8');
const decrypted = crypto.privateDecrypt(privateKey, new Buffer(str, 'base64'));
return decrypted.toString('utf8');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment