Skip to content

Instantly share code, notes, and snippets.

@amitaymolko
Last active May 4, 2022 07:00
Show Gist options
  • Save amitaymolko/8927d471ae916f90014feaa23cf64c42 to your computer and use it in GitHub Desktop.
Save amitaymolko/8927d471ae916f90014feaa23cf64c42 to your computer and use it in GitHub Desktop.
'use strict';
var NodeRSA = require('node-rsa');
var CryptoJS = require('crypto-js');
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
}
let encryptUsingPassword = (decrypted, password) => {
return CryptoJS.AES.encrypt(decrypted, password).toString()
}
let decryptUsingPassword = (encrypted, password) => {
return CryptoJS.AES.decrypt(encrypted, password).toString(CryptoJS.enc.Utf8)
}
module.exports = {
keys: {
generate: generateKeyPair,
decrypt: decryptUsingKeys,
encrypt: encryptUsingKeys
},
password: {
decrypt: decryptUsingPassword,
encrypt: encryptUsingPassword
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment