ECDH.js 1.5 KB

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