Skip to content

Instantly share code, notes, and snippets.

@deskoh
Created May 20, 2020 02:55
Show Gist options
  • Select an option

  • Save deskoh/8d0ac1c1d6200ac6ea426efb4ffd0493 to your computer and use it in GitHub Desktop.

Select an option

Save deskoh/8d0ac1c1d6200ac6ea426efb4ffd0493 to your computer and use it in GitHub Desktop.
NodeJS RSA Cryptoraphy
const crypto = require('crypto');
const keyPair = crypto.generateKeyPairSync('rsa', {
// Max length of plaintext = (512 / 8) - 42 = 22 bytes
modulusLength: 512,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: ''
}
});
// Defining a text to be encrypted
const plainText = "1234567890123456789012";
// Defining encrypted text
const encrypted = crypto.publicEncrypt(keyPair.publicKey, Buffer.from(plainText, 'utf-8')).toString('base64');
const decrypted = crypto.privateDecrypt(keyPair.privateKey, Buffer.from(encrypted, 'base64')).toString('utf-8')
console.log("Plaintext:", plainText);
console.log("Encrypted:", encrypted);
console.log("Decrypted:", decrypted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment