-
Notifications
You must be signed in to change notification settings - Fork 9
/
ec.ts
340 lines (317 loc) · 9.1 KB
/
ec.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import type { DhkemPrimitives } from "../../interfaces/dhkemPrimitives.ts";
import type { KdfInterface } from "../../interfaces/kdfInterface.ts";
import { NativeAlgorithm } from "../../algorithm.ts";
import { EMPTY } from "../../consts.ts";
import {
DeriveKeyPairError,
DeserializeError,
NotSupportedError,
SerializeError,
} from "../../errors.ts";
import { KemId } from "@hpke/common";
import { KEM_USAGES, LABEL_DKP_PRK } from "../../interfaces/dhkemPrimitives.ts";
import { Bignum } from "../../utils/bignum.ts";
import { base64UrlToBytes, i2Osp } from "../../utils/misc.ts";
// b"candidate"
// deno-fmt-ignore
const LABEL_CANDIDATE = new Uint8Array([
99, 97, 110, 100, 105, 100, 97, 116, 101,
]);
// the order of the curve being used.
// deno-fmt-ignore
const ORDER_P_256 = new Uint8Array([
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,
0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
]);
// deno-fmt-ignore
const ORDER_P_384 = new Uint8Array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,
0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,
0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,
]);
// deno-fmt-ignore
const ORDER_P_521 = new Uint8Array([
0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,
0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,
0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,
0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,
0x64, 0x09,
]);
// deno-fmt-ignore
const PKCS8_ALG_ID_P_256 = new Uint8Array([
48, 65, 2, 1, 0, 48, 19, 6, 7, 42,
134, 72, 206, 61, 2, 1, 6, 8, 42, 134,
72, 206, 61, 3, 1, 7, 4, 39, 48, 37,
2, 1, 1, 4, 32,
]);
// deno-fmt-ignore
const PKCS8_ALG_ID_P_384 = new Uint8Array([
48, 78, 2, 1, 0, 48, 16, 6, 7, 42,
134, 72, 206, 61, 2, 1, 6, 5, 43, 129,
4, 0, 34, 4, 55, 48, 53, 2, 1, 1,
4, 48,
]);
// deno-fmt-ignore
const PKCS8_ALG_ID_P_521 = new Uint8Array([
48, 96, 2, 1, 0, 48, 16, 6, 7, 42,
134, 72, 206, 61, 2, 1, 6, 5, 43, 129,
4, 0, 35, 4, 73, 48, 71, 2, 1, 1,
4, 66,
]);
export class Ec extends NativeAlgorithm implements DhkemPrimitives {
private _hkdf: KdfInterface;
private _alg: EcKeyGenParams;
private _nPk: number;
private _nSk: number;
private _nDh: number;
// EC specific arguments for deriving key pair.
private _order: Uint8Array;
private _bitmask: number;
private _pkcs8AlgId: Uint8Array;
constructor(kem: KemId, hkdf: KdfInterface) {
super();
this._hkdf = hkdf;
switch (kem) {
case KemId.DhkemP256HkdfSha256:
this._alg = { name: "ECDH", namedCurve: "P-256" };
this._nPk = 65;
this._nSk = 32;
this._nDh = 32;
this._order = ORDER_P_256;
this._bitmask = 0xFF;
this._pkcs8AlgId = PKCS8_ALG_ID_P_256;
break;
case KemId.DhkemP384HkdfSha384:
this._alg = { name: "ECDH", namedCurve: "P-384" };
this._nPk = 97;
this._nSk = 48;
this._nDh = 48;
this._order = ORDER_P_384;
this._bitmask = 0xFF;
this._pkcs8AlgId = PKCS8_ALG_ID_P_384;
break;
default:
// case KemId.DhkemP521HkdfSha512:
this._alg = { name: "ECDH", namedCurve: "P-521" };
this._nPk = 133;
this._nSk = 66;
this._nDh = 66;
this._order = ORDER_P_521;
this._bitmask = 0x01;
this._pkcs8AlgId = PKCS8_ALG_ID_P_521;
break;
}
}
public async serializePublicKey(key: CryptoKey): Promise<ArrayBuffer> {
await this._setup();
try {
return await (this._api as SubtleCrypto).exportKey("raw", key);
} catch (e: unknown) {
throw new SerializeError(e);
}
}
public async deserializePublicKey(key: ArrayBuffer): Promise<CryptoKey> {
await this._setup();
try {
return await this._importRawKey(key, true);
} catch (e: unknown) {
throw new DeserializeError(e);
}
}
public async serializePrivateKey(key: CryptoKey): Promise<ArrayBuffer> {
await this._setup();
try {
const jwk = await (this._api as SubtleCrypto).exportKey("jwk", key);
if (!("d" in jwk)) {
throw new Error("Not private key");
}
return base64UrlToBytes(jwk["d"] as string);
} catch (e: unknown) {
throw new SerializeError(e);
}
}
public async deserializePrivateKey(key: ArrayBuffer): Promise<CryptoKey> {
await this._setup();
try {
return await this._importRawKey(key, false);
} catch (e: unknown) {
throw new DeserializeError(e);
}
}
public async importKey(
format: "raw" | "jwk",
key: ArrayBuffer | JsonWebKey,
isPublic: boolean,
): Promise<CryptoKey> {
await this._setup();
try {
if (format === "raw") {
return await this._importRawKey(key as ArrayBuffer, isPublic);
}
// jwk
if (key instanceof ArrayBuffer) {
throw new Error("Invalid jwk key format");
}
return await this._importJWK(key as JsonWebKey, isPublic);
} catch (e: unknown) {
throw new DeserializeError(e);
}
}
public async generateKeyPair(): Promise<CryptoKeyPair> {
await this._setup();
try {
return await (this._api as SubtleCrypto).generateKey(
this._alg,
true,
KEM_USAGES,
);
} catch (e: unknown) {
throw new NotSupportedError(e);
}
}
public async deriveKeyPair(ikm: ArrayBuffer): Promise<CryptoKeyPair> {
await this._setup();
try {
const dkpPrk = await this._hkdf.labeledExtract(
EMPTY,
LABEL_DKP_PRK,
new Uint8Array(ikm),
);
const bn = new Bignum(this._nSk);
for (
let counter = 0;
bn.isZero() || !bn.lessThan(this._order);
counter++
) {
if (counter > 255) {
throw new Error("Faild to derive a key pair");
}
const bytes = new Uint8Array(
await this._hkdf.labeledExpand(
dkpPrk,
LABEL_CANDIDATE,
i2Osp(counter, 1),
this._nSk,
),
);
bytes[0] = bytes[0] & this._bitmask;
bn.set(bytes);
}
const sk = await this._deserializePkcs8Key(bn.val());
bn.reset();
return {
privateKey: sk,
publicKey: await this.derivePublicKey(sk),
};
} catch (e: unknown) {
throw new DeriveKeyPairError(e);
}
}
public async derivePublicKey(key: CryptoKey): Promise<CryptoKey> {
await this._setup();
try {
const jwk = await (this._api as SubtleCrypto).exportKey("jwk", key);
delete jwk["d"];
delete jwk["key_ops"];
return await (this._api as SubtleCrypto).importKey(
"jwk",
jwk,
this._alg,
true,
[],
);
} catch (e: unknown) {
throw new DeserializeError(e);
}
}
public async dh(sk: CryptoKey, pk: CryptoKey): Promise<ArrayBuffer> {
try {
await this._setup();
const bits = await (this._api as SubtleCrypto).deriveBits(
{
name: "ECDH",
public: pk,
},
sk,
this._nDh * 8,
);
return bits;
} catch (e: unknown) {
throw new SerializeError(e);
}
}
private async _importRawKey(
key: ArrayBuffer,
isPublic: boolean,
): Promise<CryptoKey> {
if (isPublic && key.byteLength !== this._nPk) {
throw new Error("Invalid public key for the ciphersuite");
}
if (!isPublic && key.byteLength !== this._nSk) {
throw new Error("Invalid private key for the ciphersuite");
}
if (isPublic) {
return await (this._api as SubtleCrypto).importKey(
"raw",
key,
this._alg,
true,
[],
);
}
return await this._deserializePkcs8Key(new Uint8Array(key));
}
private async _importJWK(
key: JsonWebKey,
isPublic: boolean,
): Promise<CryptoKey> {
if (typeof key.crv === "undefined" || key.crv !== this._alg.namedCurve) {
throw new Error(`Invalid crv: ${key.crv}`);
}
if (isPublic) {
if (typeof key.d !== "undefined") {
throw new Error("Invalid key: `d` should not be set");
}
return await (this._api as SubtleCrypto).importKey(
"jwk",
key,
this._alg,
true,
[],
);
}
if (typeof key.d === "undefined") {
throw new Error("Invalid key: `d` not found");
}
return await (this._api as SubtleCrypto).importKey(
"jwk",
key,
this._alg,
true,
KEM_USAGES,
);
}
private async _deserializePkcs8Key(k: Uint8Array): Promise<CryptoKey> {
const pkcs8Key = new Uint8Array(
this._pkcs8AlgId.length + k.length,
);
pkcs8Key.set(this._pkcs8AlgId, 0);
pkcs8Key.set(k, this._pkcs8AlgId.length);
return await (this._api as SubtleCrypto).importKey(
"pkcs8",
pkcs8Key,
this._alg,
true,
KEM_USAGES,
);
}
}