Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GuillermoPena/b87351bc4f94a221b7c6 to your computer and use it in GitHub Desktop.
Save GuillermoPena/b87351bc4f94a221b7c6 to your computer and use it in GitHub Desktop.
NodeJS - URSA : Asymmetric Cryptology
// How to encrypt/decrypt with ursa module (asymmetric cryptology)
var ursa = require('ursa')
, message = 'Hello world!'
, encoding = 'base64'
// Creating a pair of keys (a private key contains both keys...)
console.log('Generating Keys Pair...')
var keys = ursa.generatePrivateKey()
// Making a private key
var privPem = keys.toPrivatePem(encoding)
, priv = ursa.createPrivateKey(privPem, '', encoding)
console.log('Private Key:', privPem)
// Making a public key
var pubPem = keys.toPublicPem(encoding)
, pub = ursa.createPublicKey(pubPem, encoding)
console.log('\nPublic Key:', pubPem)
var data = new Buffer(message, 'ascii')
console.log('\n\nMessage:', message)
console.log('Data:', data)
// Encrypting (with the public key)
var encrypted = pub.encrypt(data, encoding)
console.log('Encrypted Data: ', encrypted)
console.log('Encrypted Message: ', encrypted.toString('ascii'))
// Decrypting (with the private key)
var decrypted = priv.decrypt(encrypted, encoding)
console.log('Decrypted Data: ', decrypted)
console.log('Decrypted Message: ', decrypted.toString('ascii'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment