Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Last active May 29, 2020 09:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save coolaj86/f6f36efce2821dfb046d to your computer and use it in GitHub Desktop.
Save coolaj86/f6f36efce2821dfb046d to your computer and use it in GitHub Desktop.
Example of Asymmetric Encryption in Node.js using RSA key and pub (PEM format)
// Moved to https://coolaj86.com/articles/asymmetric-public--private-key-encryption-in-node-js/
@bgelfand
Copy link

bgelfand commented Dec 5, 2014

@coolaj86 Any ideas on how to encrypt in PHP and still decrypt in Node.js? I am getting this, even though it decrypts in PHP no problem, it's really odd. Error: error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error

@coolaj86
Copy link
Author

coolaj86 commented Dec 5, 2014

It probably has to do with the padding options. I don't remember how you set those with ursa and I've never tried with PHP, but I think I got a similar error with a simple cipher once in node.

@coolaj86
Copy link
Author

After having a bit more experience I would say it may also be a simple matter of not specifying the encoding correctly (hex vs base64 vs buffer etc)

@joshuaquek
Copy link

joshuaquek commented Jul 20, 2018

I've built a library that expose pretty simple techniques to do exactly this:

https://www.npmjs.com/package/quick-encrypt

Full Example:

const QuickEncrypt = require('quick-encrypt')
 
// --- RSA Keypair Generation ---
let keys = QuickEncrypt.generate(1024) // Use either 2048 bits or 1024 bits.
console.log(keys) // Generated Public Key and Private Key pair
let publicKey = keys.public      // " -----BEGIN RSA PUBLIC KEY-----\nMIGJAoGBAIXlXZs+0FoIGBc5pjnZZxtvIzdDFtNi3SVi6vf2J...... "
let privateKey = keys.private   // " -----BEGIN RSA PUBLIC KEY-----\nMIGJAoGBAIXlXZs+0FoIGBc5pjnZZxtvIzdDFtNi3SVi6vf2J...... "
 
// --- Encrypt using public key ---
let encryptedText = QuickEncrypt.encrypt( "This is some super top secret text!", publicKey )
console.log(encryptedText) // This will print out the ENCRYPTED text, for example : " 01c066e00c660aabadfc320621d9c3ac25ccf2e4c29e8bf4c...... "
 
// --- Decrypt using private key ---
let decryptedText = QuickEncrypt.decrypt( encryptedText, privateKey)
console.log(decryptedText) // This will print out the DECRYPTED text, which is " This is some super top secret text! "

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment