Skip to content

Instantly share code, notes, and snippets.

@mrPrateek95
Last active July 2, 2020 11:46
Show Gist options
  • Save mrPrateek95/23ecc0373336d47f9fcb8dc3387f8e90 to your computer and use it in GitHub Desktop.
Save mrPrateek95/23ecc0373336d47f9fcb8dc3387f8e90 to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
function GenerateKeyPair()
{
try
{
const RsaOptions =
{
modulusLength: 2048,
publicKeyEncoding:
{
type: 'pkcs1',
format: 'pem'
},
privateKeyEncoding:
{
type: 'pkcs8',
format: 'pem'
}
}
const keyPair = crypto.generateKeyPairSync('rsa', RsaOptions);
const result =
{
privateKey: keyPair.privateKey,
publicKey: keyPair.publicKey
};
return result;
}
catch (error)
{
throw error;
}
}
function EncryptMessage(messageToEncrypt, publicKey)
{
try
{
konsole.info("Encrypting message...")
const buffer = Buffer.from(messageToEncrypt)
const encryptedMessage = crypto.publicEncrypt(publicKey, buffer).toString("base64");
return encryptedMessage
}
catch (error)
{
throw error;
}
}
function DecryptMessage(messageToDecrypt, privateKey)
{
try
{
konsole.info("Decrypting message...")
const buffer = Buffer.from(messageToDecrypt, "base64")
const decryptedMessage = crypto.privateDecrypt(privateKey, buffer).toString();
return decryptedMessage;
}
catch (error)
{
throw error;
}
}
module.exports =
{
GenerateKeyPair,
EncryptMessage,
DecryptMessage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment