Skip to content

Instantly share code, notes, and snippets.

@amitaymolko
Created August 7, 2019 07:00
Show Gist options
  • Save amitaymolko/7dc2dad8b4b08366a72effa5a02a94c7 to your computer and use it in GitHub Desktop.
Save amitaymolko/7dc2dad8b4b08366a72effa5a02a94c7 to your computer and use it in GitHub Desktop.
'use strict';
const NodeRSA = require('node-rsa');
const crypto = require('crypto')
let generateKeyPair = (password) => {
let key = new NodeRSA();
key.generateKeyPair()
let publicKey = Buffer.from(key.exportKey('public')).toString('base64')
let privateKey = Buffer.from(key.exportKey('private')).toString('base64')
if(password) {
privateKey = encryptUsingPassword(privateKey, password)
}
return {publicKey, privateKey}
}
let decryptUsingKeys = (privateKeyString, encryptedMessage) => {
let privateKey = Buffer.from(privateKeyString, 'base64').toString()
let key = {
key: privateKey,
padding: crypto.constants.RSA_PKCS1_PADDING
}
let message = crypto.privateDecrypt(key, Buffer.from(encryptedMessage, 'base64')).toString()
return message
}
let encryptUsingKeys = (publicKeyString, message) => {
let publicKey = Buffer.from(publicKeyString, 'base64').toString()
let key = {
key: publicKey,
padding: crypto.constants.RSA_PKCS1_PADDING
}
let encryptedMessage = crypto.publicEncrypt(key, Buffer.from(message)).toString('base64')
return encryptedMessage
}
module.exports = {
generate: generateKeyPair,
decrypt: decryptUsingKeys,
encrypt: encryptUsingKeys
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment