Created
May 28, 2014 10:16
-
-
Save GuillermoPena/f67fd48741869a3f3f96 to your computer and use it in GitHub Desktop.
NodeJS - URSA : Asymmetric Cryptology With Signature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How to send message from A user to B user, encrypting it (asymetric cryptology) and sign it | |
var ursa = require('ursa') | |
, message = 'Hello world!' | |
, encoding = 'base64' | |
, buffer = new Buffer(message, 'ascii') | |
// Creating a pair of keys of user A (a private key contains both keys...) | |
console.log('Generating Keys Pair of user A...') | |
var keysA = ursa.generatePrivateKey() | |
console.log('Making public key of A...') | |
var pubPemA = keysA.toPublicPem(encoding) | |
var pubA = ursa.createPublicKey(pubPemA, encoding) | |
console.log('Making private key of A...') | |
var prvPemA = keysA.toPrivatePem(encoding) | |
var prvA = ursa.createPrivateKey(prvPemA, '', encoding) | |
// Creating a pair of keys of user B | |
console.log('\nGenerating Keys Pair of user B...') | |
var keysB = ursa.generatePrivateKey() | |
console.log('Making public key of B...') | |
var pubPemB = keysB.toPublicPem(encoding) | |
var pubB = ursa.createPublicKey(pubPemB, encoding) | |
console.log('Making private key of B...\n') | |
var prvPemB = keysB.toPrivatePem(encoding) | |
var prvB = ursa.createPrivateKey(prvPemB, '', encoding) | |
// User A sign message with his private key and encript with public key of B user | |
var algorithm = 'md5' | |
, signature = prvA.hashAndSign(algorithm, buffer, encoding, encoding) | |
, encryptedMessage = pubB.encrypt(buffer, encoding) | |
// User B verify signature with public key of A and decript with his private key | |
var decryptedMessage = prvB.decrypt(encryptedMessage, encoding) | |
, buffer2 = new Buffer(decryptedMessage, 'ascii') | |
, isValid = pubA.hashAndVerify(algorithm, buffer2, signature, encoding) | |
console.log("Original Message to send from A to B: " + message) | |
console.log("Message after encrypt and decrypt: " + decryptedMessage) | |
console.log("Signature match? " + isValid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment