Last active
October 11, 2016 06:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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