4 * EC Diffie-Hellman operations on Curve25519.
8 * Copyright (c) 2014 Mega Limited
9 * under the MIT License.
11 * Authors: Guy K. Kloss
13 * You should have received a copy of the license along with this program.
16 var core = require('./core');
17 var utils = require('./utils');
18 var curve255 = require('./curve255');
22 * @exports jodid25519/dh
23 * EC Diffie-Hellman operations on Curve25519.
26 * EC Diffie-Hellman operations on Curve25519.
31 function _toString(vector) {
32 var u = new Uint16Array(vector);
33 return (new Buffer(new Uint8Array(u.buffer)));
36 function _fromString(vector) {
37 if (Buffer.isBuffer(vector)) {
38 var u = new Uint8Array(vector);
39 return (new Uint16Array(u.buffer));
42 var result = new Array(16);
43 for (var i = 0, l = 0; i < vector.length; i += 2) {
44 result[l] = (vector.charCodeAt(i + 1) << 8) | vector.charCodeAt(i);
52 * Computes a key through scalar multiplication of a point on the curve 25519.
54 * This function is used for the DH key-exchange protocol. It computes a
55 * key based on a secret key with a public component (opponent's public key
56 * or curve base point if not given) by using scalar multiplication.
58 * Before multiplication, some bit operations are applied to the
59 * private key to ensure it is a valid Curve25519 secret key.
60 * It is the user's responsibility to make sure that the private
61 * key is a uniformly random, secret value.
64 * @param privateComponent {string}
65 * Private point as byte string on the curve.
66 * @param publicComponent {string}
67 * Public point as byte string on the curve. If not given, the curve's
70 * Key point as byte string resulting from scalar product.
72 ns.computeKey = function(privateComponent, publicComponent) {
73 if (publicComponent) {
74 return _toString(curve255.curve25519(_fromString(privateComponent),
75 _fromString(publicComponent)));
77 return _toString(curve255.curve25519(_fromString(privateComponent)));
82 * Computes the public key to a private key on the curve 25519.
84 * Before multiplication, some bit operations are applied to the
85 * private key to ensure it is a valid Curve25519 secret key.
86 * It is the user's responsibility to make sure that the private
87 * key is a uniformly random, secret value.
90 * @param privateKey {string}
91 * Private point as byte string on the curve.
93 * Public key point as byte string resulting from scalar product.
95 ns.publicKey = function(privateKey) {
96 return _toString(curve255.curve25519(_fromString(privateKey)));
101 * Generates a new random private key of 32 bytes length (256 bit).
105 * Byte string containing a new random private key seed.
107 ns.generateKey = function() {
108 return core.generateKey(true);