1 | var sodium = require('../lib/sodium');
|
2 | var should = require('should');
|
3 |
|
4 | // Generate Alice's and Bob's key pairs
|
5 | var bob = new sodium.Key.ECDH();
|
6 | var 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
|
11 | alicePublicKey = alice.pk().get();
|
12 | bobPublicKey = 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
|
17 | var aliceDH = new sodium.ECDH(bobPublicKey, alice.sk().get());
|
18 |
|
19 | // Alice calculates the Diffie-Helman secret
|
20 | var 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
|
25 | var bobDH = new sodium.ECDH(alicePublicKey, bob.sk().get());
|
26 |
|
27 | // Bob calculates the Diffie-Helman secret
|
28 | var bobSecret = bobDH.secret();
|
29 |
|
30 | // Alice and Bob should now have the same secret and the key exchange
|
31 | // is complete
|
32 | bobSecret.should.eql(aliceSecret);
|
33 | console.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
|
38 | var bobSessionKey = bobDH.sessionKey();
|
39 | var aliceSessionKey = aliceDH.sessionKey();
|
40 |
|
41 | aliceSessionKey.should.eql(bobSessionKey);
|
42 | console.log('Sessions Keys Match!');
|