summaryrefslogtreecommitdiffstats
path: root/dom/crypto/test/test_WebCrypto_ECDH.html
blob: 8386d3c3ddb93e5e82dca31337aa7a6cf2020bdc (plain)
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
<!DOCTYPE html>
<html>

<head>
<title>WebCrypto Test Suite</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="./test_WebCrypto.css"/>
<script src="/tests/SimpleTest/SimpleTest.js"></script>

<!-- Utilities for manipulating ABVs -->
<script src="util.js"></script>

<!-- A simple wrapper around IndexedDB -->
<script src="simpledb.js"></script>

<!-- Test vectors drawn from the literature -->
<script src="./test-vectors.js"></script>

<!-- General testing framework -->
<script src="./test-array.js"></script>

<script>/* <![CDATA[*/
"use strict";

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Generate an ECDH key for named curve P-256",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };
    crypto.subtle.generateKey(alg, false, ["deriveKey", "deriveBits"]).then(
      complete(that, function(x) {
        return exists(x.publicKey) &&
               (x.publicKey.algorithm.name == alg.name) &&
               (x.publicKey.algorithm.namedCurve == alg.namedCurve) &&
               (x.publicKey.type == "public") &&
               x.publicKey.extractable &&
               (!x.publicKey.usages.length) &&
               exists(x.privateKey) &&
               (x.privateKey.algorithm.name == alg.name) &&
               (x.privateKey.algorithm.namedCurve == alg.namedCurve) &&
               (x.privateKey.type == "private") &&
               !x.privateKey.extractable &&
               (x.privateKey.usages.length == 2) &&
               (x.privateKey.usages[0] == "deriveKey") &&
               (x.privateKey.usages[1] == "deriveBits");
      }),
      error(that)
    );
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Generate an ECDH key and derive some bits",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    var pair;
    function setKeyPair(x) { pair = x; }

    function doDerive(n) {
      return function() {
        return crypto.subtle.deriveBits({ name: "ECDH", public: pair.publicKey }, pair.privateKey, n * 8);
      };
    }

    crypto.subtle.generateKey(alg, false, ["deriveBits"])
      .then(setKeyPair, error(that))
      .then(doDerive(2), error(that))
      .then(function(x) {
        // Deriving less bytes works.
        if (x.byteLength != 2) {
          throw new Error("should have derived two bytes");
        }
      })
      // Deriving more than the curve yields doesn't.
      .then(doDerive(33), error(that))
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that ECDH deriveBits() fails when the public key is not an ECDH key",
  function() {
    var that = this;
    var pubKey, privKey;
    function setPub(x) { pubKey = x.publicKey; }
    function setPriv(x) { privKey = x.privateKey; }

    function doGenerateP256() {
      var alg = { name: "ECDH", namedCurve: "P-256" };
      return crypto.subtle.generateKey(alg, false, ["deriveBits"]);
    }

    function doGenerateRSA() {
      var alg = {
        name: "RSA-OAEP",
        hash: "SHA-256",
        modulusLength: 2048,
        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      };
      return crypto.subtle.generateKey(alg, false, ["encrypt", "decrypt"]);
    }

    function doDerive() {
      var alg = { name: "ECDH", public: pubKey };
      return crypto.subtle.deriveBits(alg, privKey, 16);
    }

    doGenerateP256()
      .then(setPriv, error(that))
      .then(doGenerateRSA, error(that))
      .then(setPub, error(that))
      .then(doDerive, error(that))
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that ECDH deriveBits() fails when the given keys' curves don't match",
  function() {
    var that = this;
    var pubKey, privKey;
    function setPub(x) { pubKey = x.publicKey; }
    function setPriv(x) { privKey = x.privateKey; }

    function doGenerateP256() {
      var alg = { name: "ECDH", namedCurve: "P-256" };
      return crypto.subtle.generateKey(alg, false, ["deriveBits"]);
    }

    function doGenerateP384() {
      var alg = { name: "ECDH", namedCurve: "P-384" };
      return crypto.subtle.generateKey(alg, false, ["deriveBits"]);
    }

    function doDerive() {
      var alg = { name: "ECDH", public: pubKey };
      return crypto.subtle.deriveBits(alg, privKey, 16);
    }

    doGenerateP256()
      .then(setPriv, error(that))
      .then(doGenerateP384, error(that))
      .then(setPub, error(that))
      .then(doDerive, error(that))
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "JWK import an ECDH public and private key and derive bits (P-256)",
  function() {
    var that = this;
    var alg = { name: "ECDH" };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doDerive() {
      return crypto.subtle.deriveBits({ name: "ECDH", public: pubKey }, privKey, tv.ecdh_p256.secret.byteLength * 8);
    }

    Promise.all([
      crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_priv, alg, false, ["deriveBits"])
        .then(setPriv, error(that)),
      crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_pub, alg, false, ["deriveBits"])
        .then(setPub, error(that)),
    ]).then(doDerive, error(that))
      .then(memcmp_complete(that, tv.ecdh_p256.secret), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "JWK import an ECDH public and private key and derive bits (P-384)",
  function() {
    var that = this;
    var alg = { name: "ECDH" };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doDerive() {
      return crypto.subtle.deriveBits({ name: "ECDH", public: pubKey }, privKey, tv.ecdh_p384.secret.byteLength * 8);
    }

    Promise.all([
      crypto.subtle.importKey("jwk", tv.ecdh_p384.jwk_priv, alg, false, ["deriveBits"])
        .then(setPriv, error(that)),
      crypto.subtle.importKey("jwk", tv.ecdh_p384.jwk_pub, alg, false, ["deriveBits"])
        .then(setPub, error(that)),
    ]).then(doDerive, error(that))
      .then(memcmp_complete(that, tv.ecdh_p384.secret), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "JWK import an ECDH public and private key and derive bits (P-521)",
  function() {
    var that = this;
    var alg = { name: "ECDH" };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doDerive() {
      return crypto.subtle.deriveBits({ name: "ECDH", public: pubKey }, privKey, tv.ecdh_p521.secret.byteLength * 8);
    }

    Promise.all([
      crypto.subtle.importKey("jwk", tv.ecdh_p521.jwk_priv, alg, false, ["deriveBits"])
        .then(setPriv, error(that)),
      crypto.subtle.importKey("jwk", tv.ecdh_p521.jwk_pub, alg, false, ["deriveBits"])
        .then(setPub, error(that)),
    ]).then(doDerive, error(that))
      .then(memcmp_complete(that, tv.ecdh_p521.secret), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "JWK import/export roundtrip with ECDH (P-256)",
  function() {
    var that = this;
    var alg = { name: "ECDH" };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doExportPub() {
      return crypto.subtle.exportKey("jwk", pubKey);
    }
    function doExportPriv() {
      return crypto.subtle.exportKey("jwk", privKey);
    }

    Promise.all([
      crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_priv, alg, true, ["deriveBits"])
        .then(setPriv, error(that)),
      crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_pub, alg, true, ["deriveBits"])
        .then(setPub, error(that)),
    ]).then(doExportPub, error(that))
      .then(function(x) {
        var tp = tv.ecdh_p256.jwk_pub;
        if ((tp.kty != x.kty) &&
            (tp.crv != x.crv) &&
            (tp.x != x.x) &&
            (tp.y != x.y)) {
          throw new Error("exported public key doesn't match");
        }
      }, error(that))
      .then(doExportPriv, error(that))
      .then(complete(that, function(x) {
        var tp = tv.ecdh_p256.jwk_priv;
        return (tp.kty == x.kty) &&
               (tp.crv == x.crv) &&
               (tp.d == x.d) &&
               (tp.x == x.x) &&
               (tp.y == x.y);
      }), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "PKCS8 import/export roundtrip with ECDH (P-256)",
  function() {
    var that = this;
    var alg = { name: "ECDH",  namedCurve: "P-256" };

    function doExportPriv(x) {
      return crypto.subtle.exportKey("pkcs8", x);
    }

    crypto.subtle.importKey("pkcs8", tv.ecdh_p256.pkcs8, alg, true, ["deriveBits"])
	  .then(doExportPriv, error(that))
      .then(complete(that, function(x) {
        return util.memcmp(x, tv.ecdh_p256.pkcs8);
      }), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that importing bad JWKs fails",
  function() {
    var that = this;
    var alg = { name: "ECDH" };
    var tvs = tv.ecdh_p256_negative;

    function doTryImport(jwk) {
      return function() {
        return crypto.subtle.importKey("jwk", jwk, alg, false, ["deriveBits"]);
      };
    }

    doTryImport(tvs.jwk_bad_crv)()
      .then(error(that), doTryImport(tvs.jwk_missing_crv))
      .then(error(that), doTryImport(tvs.jwk_missing_x))
      .then(error(that), doTryImport(tvs.jwk_missing_y))
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "JWK export of a newly generated ECDH private key",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };
    var reBase64URL = /^[a-zA-Z0-9_-]+$/;

    function doExportToJWK(x) {
      return crypto.subtle.exportKey("jwk", x.privateKey);
    }

    crypto.subtle.generateKey(alg, true, ["deriveKey", "deriveBits"])
      .then(doExportToJWK)
      .then(
        complete(that, function(x) {
          return x.ext &&
                 x.kty == "EC" &&
                 x.crv == "P-256" &&
                 reBase64URL.test(x.x) &&
                 reBase64URL.test(x.y) &&
                 reBase64URL.test(x.d) &&
                 x.x.length == 43 && // 32 octets, base64-encoded
                 x.y.length == 43 && // 32 octets, base64-encoded
                 shallowArrayEquals(x.key_ops, ["deriveKey", "deriveBits"]);
          }),
        error(that)
      );
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Derive an HMAC key from two ECDH keys and test sign/verify",
  function() {
    var that = this;
    var alg = { name: "ECDH" };
    var algDerived = { name: "HMAC", hash: {name: "SHA-1"} };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doDerive() {
      return crypto.subtle.deriveKey({ name: "ECDH", public: pubKey }, privKey, algDerived, false, ["sign", "verify"])
        .then(function(x) {
          if (!hasKeyFields(x)) {
            throw new Error("Invalid key; missing field(s)");
          }

          // 512 bit is the default for HMAC-SHA1.
          if (x.algorithm.length != 512) {
            throw new Error("Invalid key; incorrect length");
          }

          return x;
        });
    }

    function doSignAndVerify(x) {
      var data = crypto.getRandomValues(new Uint8Array(1024));
      return crypto.subtle.sign("HMAC", x, data)
        .then(function(sig) {
          return crypto.subtle.verify("HMAC", x, sig, data);
        });
    }

    Promise.all([
      crypto.subtle.importKey("jwk", tv.ecdh_p521.jwk_priv, alg, false, ["deriveKey"])
        .then(setPriv),
      crypto.subtle.importKey("jwk", tv.ecdh_p521.jwk_pub, alg, false, ["deriveKey"])
        .then(setPub),
    ]).then(doDerive)
      .then(doSignAndVerify)
      .then(complete(that, x => x), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Derive an HKDF key from two ECDH keys and derive an HMAC key from that",
  function() {
    var that = this;

    async function doTest() {
      let privKey = await crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_priv, "ECDH", false, ["deriveKey"]);
      let pubKey = await crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_pub, "ECDH", false, []);
      let ecdhAlg = { name: "ECDH", public: pubKey };
      let hkdfAlg = { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: new Uint8Array() };
      let hkdfKey = await crypto.subtle.deriveKey(ecdhAlg, privKey, hkdfAlg, false, ["deriveKey"]);
      let hmacAlg = { name: "HMAC", hash: "SHA-256" };
      let hmacKey = await crypto.subtle.deriveKey(hkdfAlg, hkdfKey, hmacAlg, false, ["sign"]);
      return crypto.subtle.sign("HMAC", hmacKey, new Uint8Array());
    }
    const expected = util.hex2abv("acf62832fa93469824cd997593bc963b28a68e6f73f4516bbe51b35942fe9811");
    doTest().then(memcmp_complete(that, expected), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "SPKI import/export of public ECDH keys (P-256)",
  function() {
    var that = this;
    var alg = { name: "ECDH" };
    var keys = ["spki", "spki_id_ecpk"];

    function doImport(key) {
      return crypto.subtle.importKey("spki", tv.ecdh_p256[key], alg, true, ["deriveBits"]);
    }

    function doExport(x) {
      return crypto.subtle.exportKey("spki", x);
    }

    function nextKey() {
      var key = keys.shift();
      var imported = doImport(key);
      var derived = imported.then(doExport);

      return derived.then(function(x) {
        if (!util.memcmp(x, tv.ecdh_p256.spki_id_ecpk)) {
          throw new Error("exported key is invalid");
        }

        if (keys.length) {
          return nextKey();
        }
        return Promise.resolve();
      });
    }

    nextKey().then(complete(that), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "SPKI/JWK import ECDH keys (P-256) and derive a known secret",
  function() {
    var that = this;
    var alg = { name: "ECDH" };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doDerive() {
      return crypto.subtle.deriveBits({ name: "ECDH", public: pubKey }, privKey, tv.ecdh_p256.secret.byteLength * 8);
    }

    Promise.all([
      crypto.subtle.importKey("spki", tv.ecdh_p256.spki, alg, false, ["deriveBits"])
        .then(setPub),
      crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_priv, alg, false, ["deriveBits"])
        .then(setPriv),
    ]).then(doDerive)
      .then(memcmp_complete(that, tv.ecdh_p256.secret), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Raw import/export of a public ECDH key (P-256)",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    function doExport(x) {
      return crypto.subtle.exportKey("raw", x);
    }

    crypto.subtle.importKey("raw", tv.ecdh_p256.raw, alg, true, ["deriveBits"])
      .then(doExport)
      .then(memcmp_complete(that, tv.ecdh_p256.raw), error(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that importing bad raw ECDH keys fails",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    crypto.subtle.importKey("raw", tv, alg, false, ["deriveBits"])
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that importing ECDH keys with an unknown format fails",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    crypto.subtle.importKey("unknown", tv, alg, false, ["deriveBits"])
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that importing too short raw ECDH keys fails",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    crypto.subtle.importKey("raw", tv, alg, false, ["deriveBits"])
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that importing too long raw ECDH keys fails",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    crypto.subtle.importKey("raw", tv, alg, false, ["deriveBits"])
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "Test that importing compressed raw ECDH keys fails",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    crypto.subtle.importKey("raw", tv, alg, false, ["deriveBits"])
      .then(error(that), complete(that));
  }
);

// -----------------------------------------------------------------------------
TestArray.addTest(
  "RAW/JWK import ECDH keys (P-256) and derive a known secret",
  function() {
    var that = this;
    var alg = { name: "ECDH", namedCurve: "P-256" };

    var pubKey, privKey;
    function setPub(x) { pubKey = x; }
    function setPriv(x) { privKey = x; }

    function doDerive() {
      return crypto.subtle.deriveBits({ name: "ECDH", public: pubKey }, privKey, tv.ecdh_p256.secret.byteLength * 8);
    }

    Promise.all([
      crypto.subtle.importKey("raw", tv.ecdh_p256.raw, alg, false, ["deriveBits"])
        .then(setPub),
      crypto.subtle.importKey("jwk", tv.ecdh_p256.jwk_priv, alg, false, ["deriveBits"])
        .then(setPriv),
    ]).then(doDerive)
      .then(memcmp_complete(that, tv.ecdh_p256.secret), error(that));
  }
);
/* ]]>*/</script>
</head>

<body>

<div id="content">
	<div id="head">
		<b>Web</b>Crypto<br>
	</div>

    <div id="start" onclick="start();">RUN ALL</div>

    <div id="resultDiv" class="content">
    Summary:
    <span class="pass"><span id="passN">0</span> passed, </span>
    <span class="fail"><span id="failN">0</span> failed, </span>
    <span class="pending"><span id="pendingN">0</span> pending.</span>
    <br/>
    <br/>

    <table id="results">
        <tr>
            <th>Test</th>
            <th>Result</th>
            <th>Time</th>
        </tr>
    </table>

    </div>

    <div id="foot"></div>
</div>

</body>
</html>