Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80542 views
1
var elliptic = require('elliptic');
2
var BN = require('bn.js');
3
4
module.exports = function createECDH(curve) {
5
return new ECDH(curve);
6
};
7
8
var aliases = {
9
secp256k1: {
10
name: 'secp256k1',
11
byteLength: 32
12
},
13
secp224r1: {
14
name: 'p224',
15
byteLength: 28
16
},
17
prime256v1: {
18
name: 'p256',
19
byteLength: 32
20
},
21
prime192v1: {
22
name: 'p192',
23
byteLength: 24
24
},
25
ed25519: {
26
name: 'ed25519',
27
byteLength: 32
28
}
29
};
30
31
aliases.p224 = aliases.secp224r1;
32
aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
33
aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
34
35
function ECDH(curve) {
36
this.curveType = aliases[curve];
37
if (!this.curveType ) {
38
this.curveType = {
39
name: curve
40
};
41
}
42
this.curve = new elliptic.ec(this.curveType.name);
43
this.keys = void 0;
44
}
45
46
ECDH.prototype.generateKeys = function (enc, format) {
47
this.keys = this.curve.genKeyPair();
48
return this.getPublicKey(enc, format);
49
};
50
51
ECDH.prototype.computeSecret = function (other, inenc, enc) {
52
inenc = inenc || 'utf8';
53
if (!Buffer.isBuffer(other)) {
54
other = new Buffer(other, inenc);
55
}
56
var otherPub = this.curve.keyFromPublic(other).getPublic();
57
var out = otherPub.mul(this.keys.getPrivate()).getX();
58
return formatReturnValue(out, enc, this.curveType.byteLength);
59
};
60
61
ECDH.prototype.getPublicKey = function (enc, format) {
62
var key = this.keys.getPublic(format === 'compressed', true);
63
if (format === 'hybrid') {
64
if (key[key.length - 1] % 2) {
65
key[0] = 7;
66
} else {
67
key [0] = 6;
68
}
69
}
70
return formatReturnValue(key, enc);
71
};
72
73
ECDH.prototype.getPrivateKey = function (enc) {
74
return formatReturnValue(this.keys.getPrivate(), enc);
75
};
76
77
ECDH.prototype.setPublicKey = function (pub, enc) {
78
enc = enc || 'utf8';
79
if (!Buffer.isBuffer(pub)) {
80
pub = new Buffer(pub, enc);
81
}
82
this.keys._importPublic(pub);
83
return this;
84
};
85
86
ECDH.prototype.setPrivateKey = function (priv, enc) {
87
enc = enc || 'utf8';
88
if (!Buffer.isBuffer(priv)) {
89
priv = new Buffer(priv, enc);
90
}
91
var _priv = new BN(priv);
92
_priv = _priv.toString(16);
93
this.keys._importPrivate(_priv);
94
return this;
95
};
96
97
function formatReturnValue(bn, enc, len) {
98
if (!Array.isArray(bn)) {
99
bn = bn.toArray();
100
}
101
var buf = new Buffer(bn);
102
if (len && buf.length < len) {
103
var zeros = new Buffer(len - buf.length);
104
zeros.fill(0);
105
buf = Buffer.concat([zeros, buf]);
106
}
107
if (!enc) {
108
return buf;
109
} else {
110
return buf.toString(enc);
111
}
112
}
113
114