UNPKG

1.52 kBJavaScriptView Raw
1var sodium = require('../lib/sodium');
2var should = require('should');
3
4// Generate Alice's and Bob's key pairs
5var bob = new sodium.Key.ECDH();
6var alice = new sodium.Key.ECDH();
7
8// Now alice and bob exchange public keys
9// To keep this example simple the network, and public key exchanges are
10// simulated by using the variables alicePublicKey, and bobPublicKey
11alicePublicKey = alice.pk().get();
12bobPublicKey = bob.pk().get();
13
14// Once Alice gets Bob's public key she can initialize the
15// Eliptic Curve Diffie-Helman object with her secret key
16// and Bob's public key
17var aliceDH = new sodium.ECDH(bobPublicKey, alice.sk().get());
18
19// Alice calculates the Diffie-Helman secret
20var aliceSecret = aliceDH.secret();
21
22// Bob uses Alice's public key to initialize the
23// Eliptic Curve Diffie-Helman object with his secret key
24// and Alice's public key
25var bobDH = new sodium.ECDH(alicePublicKey, bob.sk().get());
26
27// Bob calculates the Diffie-Helman secret
28var bobSecret = bobDH.secret();
29
30// Alice and Bob should now have the same secret and the key exchange
31// is complete
32bobSecret.should.eql(aliceSecret);
33console.log('DH Secrets Match!');
34
35// The Diffie-Helman secret should not be used directly as an encryption key
36// You can take the secret and hash it using your "favorite" hash function or
37// you can use ECDG.sessionKey to get a valid session Key
38var bobSessionKey = bobDH.sessionKey();
39var aliceSessionKey = aliceDH.sessionKey();
40
41aliceSessionKey.should.eql(bobSessionKey);
42console.log('Sessions Keys Match!');