Last active
October 4, 2017 19:19
-
-
Save jas-/9330405 to your computer and use it in GitHub Desktop.
crypto.createSign() using DH private key use case
This file contains hidden or 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
/* Bob's environment */ | |
var crypto = require('crypto'); | |
var rsa = require('ursa'); | |
crypto.DEFAULT_ENCODING = 'hex' | |
var dhBob = crypto.getDiffieHellman('modp18') | |
, kBob = dhBob.generateKeys() | |
, keysBob = { | |
pubKey: dhBob.getPublicKey(), | |
privKey: dhBob.getPrivateKey() | |
}; | |
/* Alice's envrionment setup (different computer emulation) */ | |
var dhAlice = crypto.getDiffieHellman('modp18') | |
, kAlice = dhAlice.generateKeys() | |
, keysAlice = { | |
pubKey: dhAlice.getPublicKey(), | |
privKey: dhAlice.getPrivateKey() | |
}; | |
/* Bob recieves Alice's public key & generates a shared secret */ | |
var secret = dhBob.computeSecret(keysAlice.pubKey); | |
/* Bob uses shared secret to generate RSA keys */ | |
var k = rsa.generatePrivateKey(); | |
var pk = rsa.createPrivateKey(k.toPrivatePem().toString('utf8'), secret, 'utf8'); | |
var keys = { | |
privKey: pk.toPrivatePem().toString('utf8'), | |
pubKey: pk.toPublicPem().toString('utf8') | |
} | |
/* Bob uses shared secret to create cipher text */ | |
try { | |
var cipher = crypto.createCipher('aes-256-cbc', secret) | |
, ct = []; | |
ct.push(cipher.update('This is a secret message for Alice')); | |
ct.push(cipher.final()); | |
var result = ct.join(''); | |
} catch(e){ | |
throw new Error('Could not create encryption object'); | |
} | |
/* Bob then computes a digest of the cipher text */ | |
var digest = crypto.createHmac('sha256', secret); | |
digest.update(result); | |
var hmac = digest.digest(); | |
/* Create object of ct & hmac and stringify it */ | |
var sendToAlice = JSON.stringify({ message: result, digest: hmac }); | |
/* Bob's DH privKey needs to be an RSA key */ | |
var sig = crypto.createSign('RSA-SHA256'); | |
sig.update(sendToAlice); | |
var signature = sig.sign(keys.privKey); | |
console.log('PAYLOAD: '+sendToAlice); | |
console.log('SIGNATURE '+signature); | |
/* Verify signature of payload with Bob's public key */ | |
var v = crypto.createVerify('RSA-SHA256'); | |
v.update(sendToAlice); | |
var verify = v.verify(keys.pubKey, signature); | |
console.log('VERIFY '+verify); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was helpful, thanks!