-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprivateKey.js
100 lines (78 loc) · 2.68 KB
/
privateKey.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
PrivateKey = function(curve=Curve.secp256k1, secret=null) {
this.curve = curve;
if (secret) {
this.secret = secret;
} else {
this.secret = Integer.secureRandomNumber();
}
this.publicKey = function() {
let curve = this.curve;
let publicPoint = EcdsaMath.multiply(curve.G, this.secret, curve.N, curve.A, curve.P);
return new PublicKey(publicPoint, curve);
};
this.toString = function() {
return BinaryAscii.stringFromNumber(this.secret, this.curve.length());
};
this.toDer = function () {
let encodedPublicKey = this.publicKey().toString(true);
return Der.encodeSequence(
Der.encodeInteger(BigInt(1)),
Der.encodeOctetString(this.toString()),
Der.encodeConstructed(0, Der.encodeOid(this.curve.oid())),
Der.encodeConstructed(1, Der.encodeBitstring(encodedPublicKey))
);
}
this.toPem = function() {
return Der.toPem(this.toDer(), "EC PRIVATE KEY");
};
};
PrivateKey.fromPem = function(string) {
let privateKeyPem = string.split("-----BEGIN EC PRIVATE KEY-----")[1];
return this.fromDer(Der.fromPem(privateKeyPem));
};
PrivateKey.fromString = function(string, curve=EcdsaCurve.secp256k1) {
return new PrivateKey(curve, BinaryAscii.numberFromString(string));
};
PrivateKey.fromDer = function(string) {
let result = Der.removeSequence(string);
let t = result[0];
let empty = result[1];
if (empty) {
throw new Error("trailing junk after DER private key: " + BinaryAscii.hexFromBinary(empty));
};
result = Der.removeInteger(t);
let one = result[0];
t = result[1];
if (one != 1) {
throw new Error("expected '1' at start of DER private key, got " + one);
};
result = Der.removeOctetString(t);
let privateKeyStr = result[0];
t = result[1];
result = Der.removeConstructed(t);
let tag = result[0];
let curveOidStr = result[1];
t = result[2];
if (tag != 0) {
throw new Error("expected tag 0 in DER private key, got " + tag);
};
result = Der.removeObject(curveOidStr);
let oidCurve = result[0];
empty = result[1];
if (empty) {
throw new Error("trailing junk after DER private key curve_oid: " + BinaryAscii.hexFromBinary(empty));
};
let curve = Curve.secp256k1;
if (!curve._oid.equals(oidCurve)) {
let supportedCurvesNames = [];
Curve.supportedCurves.forEach((x) => {supportedCurvesNames.push(x.name)})
throw new Error(
"Unknown curve with oid " + oidCurve
+ ". Only the following are available: " + supportedCurvesNames
);
};
if (privateKeyStr.length < curve.length()) {
privateKeyStr = hexAt.repeat(curve.length() - privateKeyStr.length) + privateKeyStr;
};
return this.fromString(privateKeyStr, curve);
};