servo-script 0.5.0

A component of the servo web-engine.
Documentation
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use elliptic_curve::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
use elliptic_curve::sec1::{ModulusSize, Sec1Point, ToSec1Point, ValidatePublicKey};
use elliptic_curve::{Curve, FieldBytesSize, Generate, PublicKey, SecretKey};
use js::context::JSContext;
use p256::NistP256;
use p384::NistP384;
use p521::NistP521;

use crate::dom::bindings::codegen::Bindings::CryptoKeyBinding::{
    CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
};
use crate::dom::bindings::codegen::Bindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::cryptokey::{CryptoKey, Handle};
use crate::dom::globalscope::GlobalScope;
use crate::dom::subtlecrypto::{
    CryptoAlgorithm, ExportedKey, JwkStringField, KeyAlgorithmAndDerivatives, NAMED_CURVE_P256,
    NAMED_CURVE_P384, NAMED_CURVE_P521, SUPPORTED_CURVES, SubtleEcKeyAlgorithm,
    SubtleEcKeyGenParams, SubtleEcKeyImportParams,
};
use crate::dom::webcrypto::subtlecrypto::JsonWebKeyExt;

#[derive(PartialEq)]
pub(crate) enum EcAlgorithm {
    Ecdsa,
    Ecdh,
}

/// <https://w3c.github.io/webcrypto/#ecdsa-operations-generate-key>
/// <https://w3c.github.io/webcrypto/#ecdh-operations-generate-key>
pub(crate) fn generate_key(
    ec_algorithm: EcAlgorithm,
    cx: &mut JSContext,
    global: &GlobalScope,
    normalized_algorithm: &SubtleEcKeyGenParams,
    extractable: bool,
    usages: Vec<KeyUsage>,
) -> Result<CryptoKeyPair, Error> {
    match ec_algorithm {
        EcAlgorithm::Ecdsa => {
            // Step 1. If usages contains a value which is not one of "sign" or "verify", then throw
            // a SyntaxError.
            if usages
                .iter()
                .any(|usage| !matches!(usage, KeyUsage::Sign | KeyUsage::Verify))
            {
                return Err(Error::Syntax(Some(
                    "Usages contains an entry which is not \"sign\" or \"verify\"".into(),
                )));
            }
        },
        EcAlgorithm::Ecdh => {
            // Step 1. If usages contains an entry which is not "deriveKey" or "deriveBits" then
            // throw a SyntaxError.
            if usages
                .iter()
                .any(|usage| !matches!(usage, KeyUsage::DeriveKey | KeyUsage::DeriveBits))
            {
                return Err(Error::Syntax(Some(
                    "Usages contains an entry which is not \"deriveKey\" or \"deriveBits\"".into(),
                )));
            }
        },
    }

    // Step 2.
    // If the namedCurve member of normalizedAlgorithm is "P-256", "P-384" or "P-521":
    //     Generate an Elliptic Curve key pair, as defined in [RFC6090] with domain parameters for
    //     the curve identified by the namedCurve member of normalizedAlgorithm.
    // If the namedCurve member of normalizedAlgorithm is a value specified in an applicable
    // specification:
    //     Perform the ECDSA generation steps specified in that specification, passing in
    //     normalizedAlgorithm and resulting in an elliptic curve key pair.
    // Otherwise:
    //     throw a NotSupportedError
    // Step 3. If performing the key generation operation results in an error, then throw an
    // OperationError.
    // NOTE: We currently do not support other applicable specifications.
    let (private_key_handle, public_key_handle) = match normalized_algorithm.named_curve.as_str() {
        NAMED_CURVE_P256 => {
            let private_key = SecretKey::<NistP256>::try_generate().map_err(|_| {
                Error::Operation(Some("Failed to generate P-256 private key".into()))
            })?;
            let public_key = private_key.public_key();
            (
                Handle::P256PrivateKey(private_key),
                Handle::P256PublicKey(public_key),
            )
        },
        NAMED_CURVE_P384 => {
            let private_key = SecretKey::<NistP384>::try_generate().map_err(|_| {
                Error::Operation(Some("Failed to generate P-384 private key".into()))
            })?;
            let public_key = private_key.public_key();
            (
                Handle::P384PrivateKey(private_key),
                Handle::P384PublicKey(public_key),
            )
        },
        NAMED_CURVE_P521 => {
            let private_key = SecretKey::<NistP521>::try_generate().map_err(|_| {
                Error::Operation(Some("Failed to generate P-521 private key".into()))
            })?;
            let public_key = private_key.public_key();
            (
                Handle::P521PrivateKey(private_key),
                Handle::P521PublicKey(public_key),
            )
        },
        named_curve => {
            return Err(Error::NotSupported(Some(format!(
                "Unsupported named curve: {}",
                named_curve
            ))));
        },
    };

    // Step 4. Let algorithm be a new EcKeyAlgorithm object.
    // Step 6. Set the namedCurve attribute of algorithm to equal the namedCurve member of
    // normalizedAlgorithm.
    let algorithm = SubtleEcKeyAlgorithm {
        name: match ec_algorithm {
            EcAlgorithm::Ecdsa => {
                // Step 5. Set the name attribute of algorithm to "ECDSA".
                CryptoAlgorithm::Ecdsa
            },
            EcAlgorithm::Ecdh => {
                // Step 5. Set the name member of algorithm to "ECDH".
                CryptoAlgorithm::Ecdh
            },
        },
        named_curve: normalized_algorithm.named_curve.clone(),
    };

    // Step 7. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
    // Step 8. Set the [[type]] internal slot of publicKey to "public"
    // Step 9. Set the [[algorithm]] internal slot of publicKey to algorithm.
    // Step 10. Set the [[extractable]] internal slot of publicKey to true.
    let public_key_usage = match ec_algorithm {
        EcAlgorithm::Ecdsa => {
            // Step 11. Set the [[usages]] internal slot of publicKey to be the usage intersection
            // of usages and [ "verify" ].
            usages
                .iter()
                .filter(|usage| **usage == KeyUsage::Verify)
                .cloned()
                .collect()
        },
        EcAlgorithm::Ecdh => {
            // Step 11. Set the [[usages]] internal slot of publicKey to be the empty list.
            Vec::new()
        },
    };
    let public_key = CryptoKey::new(
        cx,
        global,
        KeyType::Public,
        true,
        KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm.clone()),
        public_key_usage,
        public_key_handle,
    );

    // Step 12. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
    // Step 13. Set the [[type]] internal slot of privateKey to "private"
    // Step 14. Set the [[algorithm]] internal slot of privateKey to algorithm.
    // Step 15. Set the [[extractable]] internal slot of privateKey to extractable.
    let private_key_usage = match ec_algorithm {
        EcAlgorithm::Ecdsa => {
            // Step 16. Set the [[usages]] internal slot of privateKey to be the usage intersection
            // of usages and [ "sign" ].
            usages
                .iter()
                .filter(|usage| **usage == KeyUsage::Sign)
                .cloned()
                .collect()
        },
        EcAlgorithm::Ecdh => {
            // Step 16. Set the [[usages]] internal slot of privateKey to be the usage intersection
            // of usages and [ "deriveKey", "deriveBits" ].
            usages
                .iter()
                .filter(|usage| matches!(usage, KeyUsage::DeriveKey | KeyUsage::DeriveBits))
                .cloned()
                .collect()
        },
    };
    let private_key = CryptoKey::new(
        cx,
        global,
        KeyType::Private,
        extractable,
        KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
        private_key_usage,
        private_key_handle,
    );

    // Step 17. Let result be a new CryptoKeyPair dictionary.
    // Step 18. Set the publicKey attribute of result to be publicKey.
    // Step 19. Set the privateKey attribute of result to be privateKey.
    let result = CryptoKeyPair {
        publicKey: Some(public_key),
        privateKey: Some(private_key),
    };

    // Step 20. Return result.
    Ok(result)
}

/// <https://w3c.github.io/webcrypto/#ecdsa-operations-import-key>
/// <https://w3c.github.io/webcrypto/#ecdh-operations-import-key>
///
/// This implementation is based on the specification of the importKey operation of ECDSA. When
/// format is "jwk", Step 2.2 and Step 2.3 in the specification of the importKey operation of ECDH
/// are combined into a single step, and Step 2.9.1 to Step 2.9.3. here are skipped for ECDH.
#[allow(clippy::too_many_arguments)]
pub(crate) fn import_key(
    ec_algorithm: EcAlgorithm,
    cx: &mut JSContext,
    global: &GlobalScope,
    normalized_algorithm: &SubtleEcKeyImportParams,
    format: KeyFormat,
    key_data: &[u8],
    extractable: bool,
    usages: Vec<KeyUsage>,
) -> Result<DomRoot<CryptoKey>, Error> {
    // Step 1. Let keyData be the key data to be imported.

    // Step 2.
    let key = match format {
        KeyFormat::Spki => {
            match ec_algorithm {
                EcAlgorithm::Ecdsa => {
                    // Step 2.1. If usages contains a value which is not "verify" then throw a
                    // SyntaxError.
                    if usages.iter().any(|usage| *usage != KeyUsage::Verify) {
                        return Err(Error::Syntax(Some(
                            "Usages contains a value which is not \"verify\"".into(),
                        )));
                    }
                },
                EcAlgorithm::Ecdh => {
                    // Step 2.1. If usages is not empty then throw a SyntaxError.
                    if !usages.is_empty() {
                        return Err(Error::Syntax(Some("Usages list is not empty".into())));
                    }
                },
            }

            // Step 2.2. Let spki be the result of running the parse a subjectPublicKeyInfo
            // algorithm over keyData
            // Step 2.3. If an error occurred while parsing, then throw a DataError.
            // Step 2.4. If the algorithm object identifier field of the algorithm
            // AlgorithmIdentifier field of spki is not equal to the id-ecPublicKey object
            // identifier defined in [RFC5480], then throw a DataError.
            // Step 2.5. If the parameters field of the algorithm AlgorithmIdentifier field of spki
            // is absent, then throw a DataError.
            // Step 2.6. Let params be the parameters field of the algorithm AlgorithmIdentifier
            // field of spki.
            // Step 2.7. If params is not an instance of the ECParameters ASN.1 type defined in
            // [RFC5480] that specifies a namedCurve, then throw a DataError.
            // Step 2.8. Let namedCurve be a string whose initial value is undefined.
            // Step 2.9.
            //     If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
            //         Set namedCurve "P-256".
            //     If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
            //         Set namedCurve "P-384".
            //     If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
            //         Set namedCurve "P-521".
            // Step 2.10.
            //     If namedCurve is not undefined:
            //         Step 2.10.1. Let publicKey be the Elliptic Curve public key identified by
            //         performing the conversion steps defined in Section 2.3.4 of [SEC1] using the
            //         subjectPublicKey field of spki.
            //         Step 2.10.2. The uncompressed point format MUST be supported.
            //         Step 2.10.3. If the implementation does not support the compressed point
            //         format and a compressed point is provided, throw a DataError.
            //         Step 2.10.4. If a decode error occurs or an identity point is found, throw a
            //         DataError.
            //         Step 2.10.5. Let key be a new CryptoKey that represents publicKey.
            //     Otherwise:
            //         Step 2.10.1. Perform any key import steps defined by other applicable
            //         specifications, passing format, spki and obtaining namedCurve and key.
            //         Step 2.10.2. If an error occurred or there are no applicable specifications,
            //         throw a DataError.
            // Step 2.11. If namedCurve is defined, and not equal to the namedCurve member of
            // normalizedAlgorithm, throw a DataError.
            // Step 2.12. If the public key value is not a valid point on the Elliptic Curve
            // identified by the namedCurve member of normalizedAlgorithm throw a DataError.
            let handle = match normalized_algorithm.named_curve.as_str() {
                NAMED_CURVE_P256 => Handle::P256PublicKey(
                    PublicKey::<NistP256>::from_public_key_der(key_data).map_err(|_| {
                        Error::Data(Some(
                            "Failed to parse the P-256 elliptic-curve public key in SPKI format"
                                .into(),
                        ))
                    })?,
                ),
                NAMED_CURVE_P384 => Handle::P384PublicKey(
                    PublicKey::<NistP384>::from_public_key_der(key_data).map_err(|_| {
                        Error::Data(Some(
                            "Failed to parse the P-384 elliptic-curve public key in SPKI format"
                                .into(),
                        ))
                    })?,
                ),
                NAMED_CURVE_P521 => Handle::P521PublicKey(
                    PublicKey::<NistP521>::from_public_key_der(key_data).map_err(|_| {
                        Error::Data(Some(
                            "Failed to parse the P-521 elliptic-curve public key in SPKI format"
                                .into(),
                        ))
                    })?,
                ),
                _ => return Err(Error::Data(Some("Unsupported namedCurve".into()))),
            };

            // Step 2.13. Set the [[type]] internal slot of key to "public"
            // Step 2.14. Let algorithm be a new EcKeyAlgorithm.
            // Step 2.16. Set the namedCurve attribute of algorithm to namedCurve.
            // Step 2.17. Set the [[algorithm]] internal slot of key to algorithm.
            let algorithm = SubtleEcKeyAlgorithm {
                name: match ec_algorithm {
                    EcAlgorithm::Ecdsa => {
                        // Step 2.15. Set the name attribute of algorithm to "ECDSA".
                        CryptoAlgorithm::Ecdsa
                    },
                    EcAlgorithm::Ecdh => {
                        // Step 2.15. Set the name attribute of algorithm to "ECDH".
                        CryptoAlgorithm::Ecdh
                    },
                },
                named_curve: normalized_algorithm.named_curve.clone(),
            };
            CryptoKey::new(
                cx,
                global,
                KeyType::Public,
                extractable,
                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
                usages,
                handle,
            )
        },
        KeyFormat::Pkcs8 => {
            match ec_algorithm {
                EcAlgorithm::Ecdsa => {
                    // Step 2.1. If usages contains a value which is not "sign" then throw a
                    // SyntaxError.
                    if usages.iter().any(|usage| *usage != KeyUsage::Sign) {
                        return Err(Error::Syntax(Some(
                            "Usages contains an entry which is not \"sign\"".into(),
                        )));
                    }
                },
                EcAlgorithm::Ecdh => {
                    // Step 2.1. If usages contains an entry which is not "deriveKey" or
                    // "deriveBits" then throw a SyntaxError.
                    if usages
                        .iter()
                        .any(|usage| !matches!(usage, KeyUsage::DeriveKey | KeyUsage::DeriveBits))
                    {
                        return Err(Error::Syntax(Some(
                            "Usages contains an entry which is not \"deriveKey\" or \"deriveBits\""
                                .into(),
                        )));
                    }
                },
            }

            // Step 2.2. Let privateKeyInfo be the result of running the parse a privateKeyInfo
            // algorithm over keyData.
            // Step 2.3. If an error occurs while parsing, throw a DataError.
            // Step 2.4. If the algorithm object identifier field of the privateKeyAlgorithm
            // PrivateKeyAlgorithm field of privateKeyInfo is not equal to the id-ecPublicKey
            // object identifier defined in [RFC5480], throw a DataError.
            // Step 2.5. If the parameters field of the privateKeyAlgorithm
            // PrivateKeyAlgorithmIdentifier field of privateKeyInfo is not present, throw a
            // DataError.
            // Step 2.6. Let params be the parameters field of the privateKeyAlgorithm
            // PrivateKeyAlgorithmIdentifier field of privateKeyInfo.
            // Step 2.7. If params is not an instance of the ECParameters ASN.1 type defined in
            // [RFC5480] that specifies a namedCurve, then throw a DataError.
            // Step 2.8. Let namedCurve be a string whose initial value is undefined.
            // Step 2.9.
            //     If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
            //         Set namedCurve to "P-256".
            //     If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
            //         Set namedCurve to "P-384".
            //     If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
            //         Set namedCurve to "P-521".
            // Step 2.10.
            //     If namedCurve is not undefined:
            //         Step 2.10.1. Let ecPrivateKey be the result of performing the parse an ASN.1
            //         structure algorithm, with data as the privateKey field of privateKeyInfo,
            //         structure as the ASN.1 ECPrivateKey structure specified in Section 3 of
            //         [RFC5915], and exactData set to true.
            //         Step 2.10.2. If an error occurred while parsing, then throw a DataError.
            //         Step 2.10.3. If the parameters field of ecPrivateKey is present, and is not
            //         an instance of the namedCurve ASN.1 type defined in [RFC5480], or does not
            //         contain the same object identifier as the parameters field of the
            //         privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo,
            //         then throw a DataError.
            //         Step 2.10.4. Let key be a new CryptoKey that represents the Elliptic Curve
            //         private key identified by performing the conversion steps defined in Section
            //         3 of [RFC5915] using ecPrivateKey.
            //     Otherwise:
            //         Step 2.10.1. Perform any key import steps defined by other applicable
            //         specifications, passing format, privateKeyInfo and obtaining namedCurve and
            //         key.
            //         Step 2.10.2. If an error occurred or there are no applicable specifications,
            //         throw a DataError.
            // Step 2.11. If namedCurve is defined, and not equal to the namedCurve member of
            // normalizedAlgorithm, throw a DataError.
            // Step 2.12. If the private key value is not a valid point on the Elliptic Curve
            // identified by the namedCurve member of normalizedAlgorithm throw a DataError.
            let handle = match normalized_algorithm.named_curve.as_str() {
                NAMED_CURVE_P256 => Handle::P256PrivateKey(
                    SecretKey::<NistP256>::from_pkcs8_der(key_data).map_err(|_| {
                        Error::Data(Some(
                            "Failed to parse the P-256 elliptic-curve private key in PKCS#8 format"
                                .into(),
                        ))
                    })?,
                ),
                NAMED_CURVE_P384 => Handle::P384PrivateKey(
                    SecretKey::<NistP384>::from_pkcs8_der(key_data).map_err(|_| {
                        Error::Data(Some(
                            "Failed to parse the P-384 elliptic-curve private key in PKCS#8 format"
                                .into(),
                        ))
                    })?,
                ),
                NAMED_CURVE_P521 => Handle::P521PrivateKey(
                    SecretKey::<NistP521>::from_pkcs8_der(key_data).map_err(|_| {
                        Error::Data(Some(
                            "Failed to parse the P-521 elliptic-curve private key in PKCS#8 format"
                                .into(),
                        ))
                    })?,
                ),
                _ => return Err(Error::Data(Some("Unsupported namedCurve".into()))),
            };

            // Step 2.13. Set the [[type]] internal slot of key to "private".
            // Step 2.14. Let algorithm be a new EcKeyAlgorithm.
            // Step 2.16. Set the namedCurve attribute of algorithm to namedCurve.
            // Step 2.17. Set the [[algorithm]] internal slot of key to algorithm.
            let algorithm = SubtleEcKeyAlgorithm {
                name: match ec_algorithm {
                    EcAlgorithm::Ecdsa => {
                        // Step 2.15. Set the name attribute of algorithm to "ECDSA".
                        CryptoAlgorithm::Ecdsa
                    },
                    EcAlgorithm::Ecdh => {
                        // Step 2.15. Set the name attribute of algorithm to "ECDH".
                        CryptoAlgorithm::Ecdh
                    },
                },
                named_curve: normalized_algorithm.named_curve.clone(),
            };
            CryptoKey::new(
                cx,
                global,
                KeyType::Private,
                extractable,
                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
                usages,
                handle,
            )
        },
        KeyFormat::Jwk => {
            // Step 2.1.
            // If keyData is a JsonWebKey dictionary:
            //     Let jwk equal keyData.
            // Otherwise:
            //     Throw a DataError.
            let jwk = JsonWebKey::parse(cx, key_data)?;

            match ec_algorithm {
                EcAlgorithm::Ecdsa => {
                    // Step 2.2. If the d field is present and usages contains a value which is not
                    // "sign", or, if the d field is not present and usages contains a value which
                    // is not "verify" then throw a SyntaxError.
                    if jwk.d.is_some() && usages.iter().any(|usage| *usage != KeyUsage::Sign) {
                        return Err(Error::Syntax(Some(
                            "JWK `d` field is present and usages contains an entry \
                                which is not \"sign\""
                                .into(),
                        )));
                    }
                    if jwk.d.is_none() && usages.iter().any(|usage| *usage != KeyUsage::Verify) {
                        return Err(Error::Syntax(Some(
                            "JWK `d` field is not present and usages contains an entry \
                                which is not \"verify\""
                                .into(),
                        )));
                    }
                },
                EcAlgorithm::Ecdh => {
                    // Step 2.2. If the d field is present and if usages contains an entry which is
                    // not "deriveKey" or "deriveBits" then throw a SyntaxError. If the d field is
                    // not present and if usages is not empty then throw a SyntaxError.
                    if jwk.d.as_ref().is_some() &&
                        usages.iter().any(|usage| {
                            !matches!(usage, KeyUsage::DeriveKey | KeyUsage::DeriveBits)
                        })
                    {
                        return Err(Error::Syntax(Some(
                            "JWK `d` field is present and usages contains an entry \
                                which is not \"deriveKey\" or \"deriveBits\""
                                .into(),
                        )));
                    }
                    if jwk.d.as_ref().is_none() && !usages.is_empty() {
                        return Err(Error::Syntax(Some(
                            "JWK `d` field is not present and usages is not empty".into(),
                        )));
                    }
                },
            }

            // Step 2.3. If the kty field of jwk is not "EC", then throw a DataError.
            if jwk.kty.as_ref().is_none_or(|kty| kty != "EC") {
                return Err(Error::Data(Some("JWK `kty` field is not \"EC\"".into())));
            }

            match ec_algorithm {
                EcAlgorithm::Ecdsa => {
                    // Step 2.4. If usages is non-empty and the use field of jwk is present and is
                    // not "sig", then throw a DataError.
                    if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "sig") {
                        return Err(Error::Data(Some(
                            "Usages is not empty, JWK `use` field is present, \
                                and it is not \"sign\""
                                .into(),
                        )));
                    }
                },
                EcAlgorithm::Ecdh => {
                    // Step 2.4. If usages is non-empty and the use field of jwk is present and is
                    // not equal to "enc" then throw a DataError.
                    if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "enc") {
                        return Err(Error::Data(Some(
                            "Usages is not empty, JWK `use` field is present, \
                                and it is not \"enc\""
                                .into(),
                        )));
                    }
                },
            }

            // Step 2.5. If the key_ops field of jwk is present, and is invalid according to the
            // requirements of JSON Web Key [JWK], or it does not contain all of the specified
            // usages values, then throw a DataError.
            jwk.check_key_ops(&usages)?;

            // Step 2.6. If the ext field of jwk is present and has the value false and extractable
            // is true, then throw a DataError.
            if jwk.ext.is_some_and(|ext| !ext) && extractable {
                return Err(Error::Data(Some("JWK is not extractable".into())));
            }

            // Step 2.7. Let namedCurve be a string whose value is equal to the crv field of jwk.
            // Step 2.8. If namedCurve is not equal to the namedCurve member of
            // normalizedAlgorithm, throw a DataError.
            let named_curve = jwk
                .crv
                .as_ref()
                .filter(|crv| **crv == normalized_algorithm.named_curve)
                .map(|crv| crv.to_string())
                .ok_or(Error::Data(Some(
                    "JWK named curve does not match algorithm named curve".into(),
                )))?;

            // Step 2.9.
            // If namedCurve is "P-256", "P-384" or "P-521":
            let (handle, key_type) = if matches!(
                named_curve.as_str(),
                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
            ) {
                if ec_algorithm == EcAlgorithm::Ecdsa {
                    // Step 2.9.1. Let algNamedCurve be a string whose initial value is undefined.
                    // Step 2.9.2.
                    // If the alg field is not present:
                    //     Let algNamedCurve be undefined.
                    // If the alg field is equal to the string "ES256":
                    //     Let algNamedCurve be the string "P-256".
                    // If the alg field is equal to the string "ES384":
                    //     Let algNamedCurve be the string "P-384".
                    // If the alg field is equal to the string "ES512":
                    //     Let algNamedCurve be the string "P-521".
                    // otherwise:
                    //     throw a DataError.
                    let alg = jwk.alg.as_ref().map(|alg| alg.to_string());
                    let alg_named_curve = match alg.as_deref() {
                        None => None,
                        Some("ES256") => Some(NAMED_CURVE_P256),
                        Some("ES384") => Some(NAMED_CURVE_P384),
                        Some("ES521") => Some(NAMED_CURVE_P521),
                        Some(alg) => {
                            return Err(Error::Data(Some(format!(
                                "Unsupported alg field in JsonWebKey: {}",
                                alg
                            ))));
                        },
                    };

                    // Step 2.9.3. If algNamedCurve is defined, and is not equal to namedCurve,
                    // throw a DataError.
                    if alg_named_curve.is_some_and(|alg_named_curve| alg_named_curve != named_curve)
                    {
                        return Err(Error::Data(Some(
                            "The algNamedCurve is defined, and is not equal to namedCurve".into(),
                        )));
                    }
                }

                // Step 2.9.4.
                // If the d field is present:
                if jwk.d.is_some() {
                    // Step 2.9.4.1. If jwk does not meet the requirements of Section 6.2.2 of JSON
                    // Web Algorithms [JWA], then throw a DataError.
                    let x = jwk.decode_required_string_field(JwkStringField::X)?;
                    let y = jwk.decode_required_string_field(JwkStringField::Y)?;
                    let d = jwk.decode_required_string_field(JwkStringField::D)?;

                    // Step 2.9.4.2. Let key be a new CryptoKey object that represents the Elliptic
                    // Curve private key identified by interpreting jwk according to Section 6.2.2
                    // of JSON Web Algorithms [JWA].
                    // NOTE: CryptoKey is created in Step 2.12 - 2.15.
                    let handle = match named_curve.as_str() {
                        NAMED_CURVE_P256 => {
                            let private_key =
                                SecretKey::<NistP256>::from_slice(&d).map_err(|_| {
                                    Error::Data(Some("Failed to parse P-256 private key".into()))
                                })?;
                            validate_public_key::<NistP256>(
                                &private_key,
                                &x_y_to_sec1_bytes(&x, &y),
                            )?;
                            Handle::P256PrivateKey(private_key)
                        },
                        NAMED_CURVE_P384 => {
                            let private_key =
                                SecretKey::<NistP384>::from_slice(&d).map_err(|_| {
                                    Error::Data(Some("Failed to parse P-384 private key".into()))
                                })?;
                            validate_public_key::<NistP384>(
                                &private_key,
                                &x_y_to_sec1_bytes(&x, &y),
                            )?;
                            Handle::P384PrivateKey(private_key)
                        },
                        NAMED_CURVE_P521 => {
                            let private_key =
                                SecretKey::<NistP521>::from_slice(&d).map_err(|_| {
                                    Error::Data(Some("Failed to parse P-521 private key".into()))
                                })?;
                            validate_public_key::<NistP521>(
                                &private_key,
                                &x_y_to_sec1_bytes(&x, &y),
                            )?;
                            Handle::P521PrivateKey(private_key)
                        },
                        _ => unreachable!(),
                    };

                    // Step 2.9.4.3. Set the [[type]] internal slot of Key to "private".
                    // NOTE: CryptoKey is created in Step 2.12 - 2.15.
                    let key_type = KeyType::Private;

                    (handle, key_type)
                }
                // Otherwise:
                else {
                    // Step 2.9.4.1. If jwk does not meet the requirements of Section 6.2.1 of JSON
                    // Web Algorithms [JWA], then throw a DataError.
                    let x = jwk.decode_required_string_field(JwkStringField::X)?;
                    let y = jwk.decode_required_string_field(JwkStringField::Y)?;

                    // Step 2.9.4.2. Let key be a new CryptoKey object that represents the Elliptic
                    // Curve public key identified by interpreting jwk according to Section 6.2.1 of
                    // JSON Web Algorithms [JWA].
                    // NOTE: CryptoKey is created in Step 2.12 - 2.15.
                    let handle = match named_curve.as_str() {
                        NAMED_CURVE_P256 => {
                            let sec1_bytes = x_y_to_sec1_bytes(&x, &y);
                            let public_key = PublicKey::<NistP256>::from_sec1_bytes(&sec1_bytes)
                                .map_err(|_| {
                                    Error::Data(Some("Failed to decode P-256 public key".into()))
                                })?;
                            Handle::P256PublicKey(public_key)
                        },
                        NAMED_CURVE_P384 => {
                            let sec1_bytes = x_y_to_sec1_bytes(&x, &y);
                            let public_key = PublicKey::<NistP384>::from_sec1_bytes(&sec1_bytes)
                                .map_err(|_| {
                                    Error::Data(Some("Failed to decode P-384 public key".into()))
                                })?;
                            Handle::P384PublicKey(public_key)
                        },
                        NAMED_CURVE_P521 => {
                            let sec1_bytes = x_y_to_sec1_bytes(&x, &y);
                            let public_key = PublicKey::<NistP521>::from_sec1_bytes(&sec1_bytes)
                                .map_err(|_| {
                                    Error::Data(Some("Failed to decode P-521 public key".into()))
                                })?;
                            Handle::P521PublicKey(public_key)
                        },
                        _ => unreachable!(),
                    };

                    // Step 2.9.4.4. Set the [[type]] internal slot of Key to "public".
                    // NOTE: CryptoKey is created in Step 2.12 - 2.15.
                    let key_type = KeyType::Public;

                    (handle, key_type)
                }
            }
            // Otherwise
            else {
                // Step 2.9.1. Perform any key import steps defined by other applicable
                // specifications, passing format, jwk and obtaining key.
                // Step 2.9.2. If an error occurred or there are no applicable specifications, throw
                // a DataError.
                // NOTE: We currently do not support applicable specifications.
                return Err(Error::NotSupported(Some("Unsupported namedCurve".into())));
            };

            // Step 2.10. If the key value is not a valid point on the Elliptic Curve identified by
            // the namedCurve member of normalizedAlgorithm throw a DataError.
            // NOTE: Done in Step 2.9.

            // Step 2.11. Let algorithm be a new instance of an EcKeyAlgorithm object.
            // Step 2.13. Set the namedCurve attribute of algorithm to namedCurve.
            // Step 2.14. Set the [[algorithm]] internal slot of key to algorithm.
            let algorithm = SubtleEcKeyAlgorithm {
                name: match ec_algorithm {
                    EcAlgorithm::Ecdsa => {
                        // Step 2.12. Set the name attribute of algorithm to "ECDSA".
                        CryptoAlgorithm::Ecdsa
                    },
                    EcAlgorithm::Ecdh => {
                        // Step 2.12. Set the name attribute of algorithm to "ECDH".
                        CryptoAlgorithm::Ecdh
                    },
                },
                named_curve,
            };
            CryptoKey::new(
                cx,
                global,
                key_type,
                extractable,
                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
                usages,
                handle,
            )
        },
        KeyFormat::Raw | KeyFormat::Raw_public => {
            // Step 2.1. If the namedCurve member of normalizedAlgorithm is not a named curve, then
            // throw a DataError.
            if !SUPPORTED_CURVES
                .iter()
                .any(|&supported_curve| supported_curve == normalized_algorithm.named_curve)
            {
                return Err(Error::Data(Some("Unsupported namedCurve".into())));
            }

            match ec_algorithm {
                EcAlgorithm::Ecdsa => {
                    // Step 2.2. If usages contains a value which is not "verify" then throw a
                    // SyntaxError.
                    if usages.iter().any(|usage| *usage != KeyUsage::Verify) {
                        return Err(Error::Syntax(Some(
                            "Usages contains a value which is not \"verify\"".into(),
                        )));
                    }
                },
                EcAlgorithm::Ecdh => {
                    // Step 2.2. If usages is not the empty list, then throw a SyntaxError.
                    if !usages.is_empty() {
                        return Err(Error::Syntax(Some("Usages list is not empty".into())));
                    }
                },
            }

            // Step 2.3.
            // If namedCurve is "P-256", "P-384" or "P-521":
            let handle = if matches!(
                normalized_algorithm.named_curve.as_str(),
                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
            ) {
                // Step 2.3.1. Let Q be the Elliptic Curve public key on the curve identified by
                // the namedCurve member of normalizedAlgorithm identified by performing the
                // conversion steps defined in Section 2.3.4 of [SEC1] to keyData.
                // Step 2.3.1. The uncompressed point format MUST be supported.
                // Step 2.3.1. If the implementation does not support the compressed point format
                // and a compressed point is provided, throw a DataError.
                // Step 2.3.1. If a decode error occurs or an identity point is found, throw a
                // DataError.
                match normalized_algorithm.named_curve.as_str() {
                    NAMED_CURVE_P256 => {
                        let q = PublicKey::<NistP256>::from_sec1_bytes(key_data).map_err(|_| {
                            Error::Data(Some("Failed to decode P-256 public key".into()))
                        })?;
                        Handle::P256PublicKey(q)
                    },
                    NAMED_CURVE_P384 => {
                        let q = PublicKey::<NistP384>::from_sec1_bytes(key_data).map_err(|_| {
                            Error::Data(Some("Failed to decode P-384 public key".into()))
                        })?;
                        Handle::P384PublicKey(q)
                    },
                    NAMED_CURVE_P521 => {
                        let q = PublicKey::<NistP521>::from_sec1_bytes(key_data).map_err(|_| {
                            Error::Data(Some("Failed to decode P-521 public key".into()))
                        })?;
                        Handle::P521PublicKey(q)
                    },
                    _ => unreachable!(),
                }

                // Step 2.3.1. Let key be a new CryptoKey that represents Q.
                // NOTE: CryptoKey is created in Step 2.7 - 2.8.
            }
            // Otherwise:
            else {
                // Step. 2.3.1. Perform any key import steps defined by other applicable
                // specifications, passing format, keyData and obtaining key.
                // Step. 2.3.2. If an error occurred or there are no applicable specifications,
                // throw a DataError.
                // NOTE: We currently do not support applicable specifications.
                return Err(Error::NotSupported(Some("Unsupported namedCurve".into())));
            };

            // Step 2.4. Let algorithm be a new EcKeyAlgorithm object.
            // Step 2.6. Set the namedCurve attribute of algorithm to equal the namedCurve member
            // of normalizedAlgorithm.
            let algorithm = SubtleEcKeyAlgorithm {
                name: match ec_algorithm {
                    EcAlgorithm::Ecdsa => {
                        // Step 2.5. Set the name attribute of algorithm to "ECDSA".
                        CryptoAlgorithm::Ecdsa
                    },
                    EcAlgorithm::Ecdh => {
                        // Step 2.5. Set the name attribute of algorithm to "ECDH".
                        CryptoAlgorithm::Ecdh
                    },
                },
                named_curve: normalized_algorithm.named_curve.clone(),
            };

            // Step 2.7. Set the [[type]] internal slot of key to "public"
            // Step 2.8. Set the [[algorithm]] internal slot of key to algorithm.
            CryptoKey::new(
                cx,
                global,
                KeyType::Public,
                extractable,
                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
                usages,
                handle,
            )
        },
        // Otherwise:
        _ => {
            // throw a NotSupportedError.
            return Err(Error::NotSupported(Some("Unsupported key format".into())));
        },
    };

    // Step 3. Return key.
    Ok(key)
}

/// <https://w3c.github.io/webcrypto/#ecdsa-operations-export-key>
/// <https://w3c.github.io/webcrypto/#ecdh-operations-export-key>
pub(crate) fn export_key(format: KeyFormat, key: &CryptoKey) -> Result<ExportedKey, Error> {
    // Step 1. Let key be the CryptoKey to be exported.

    // Step 2. If the underlying cryptographic key material represented by the [[handle]] internal
    // slot of key cannot be accessed, then throw an OperationError.
    // NOTE: Done in Step 3.

    // Step 3.
    let result = match format {
        // If format is "spki":
        KeyFormat::Spki => {
            // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
            // InvalidAccessError.
            if key.Type() != KeyType::Public {
                return Err(Error::InvalidAccess(Some(
                    "[[type]] internal slot of key is not \"public\"".into(),
                )));
            }

            // Step 3.2.
            // Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in
            // [RFC5280] with the following properties:
            //     * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the
            //       following properties:
            //         * Set the algorithm field to the OID id-ecPublicKey defined in [RFC5480].
            //         * Set the parameters field to an instance of the ECParameters ASN.1 type
            //           defined in [RFC5480] as follows:
            //             If the namedCurve attribute of the [[algorithm]] internal slot of key is
            //             "P-256", "P-384" or "P-521":
            //                 Let keyData be the byte sequence that represents the Elliptic Curve
            //                 public key represented by the [[handle]] internal slot of key
            //                 according to the encoding rules specified in Section 2.2 of
            //                 [RFC5480] and using the uncompressed form. and keyData.
            //                     If the namedCurve attribute of the [[algorithm]] internal slot
            //                     of key is "P-256":
            //                         Set parameters to the namedCurve choice with value equal to
            //                         the object identifier secp256r1 defined in [RFC5480]
            //                     If the namedCurve attribute of the [[algorithm]] internal slot
            //                     of key is "P-384":
            //                         Set parameters to the namedCurve choice with value equal to
            //                         the object identifier secp384r1 defined in [RFC5480]
            //                     If the namedCurve attribute of the [[algorithm]] internal slot
            //                     of key is "P-521":
            //                         Set parameters to the namedCurve choice with value equal to
            //                         the object identifier secp521r1 defined in [RFC5480]
            //             Otherwise:
            //                 1. Perform any key export steps defined by other applicable
            //                    specifications, passing format and the namedCurve attribute of
            //                    the [[algorithm]] internal slot of key and obtaining
            //                    namedCurveOid and keyData.
            //                 2. Set parameters to the namedCurve choice with value equal to the
            //                    object identifier namedCurveOid.
            //     * Set the subjectPublicKey field to keyData.
            // NOTE: We currently do not support other applicable specifications.
            let data = match key.handle() {
                Handle::P256PublicKey(public_key) => public_key.to_public_key_der(),
                Handle::P384PublicKey(public_key) => public_key.to_public_key_der(),
                Handle::P521PublicKey(public_key) => public_key.to_public_key_der(),
                _ => {
                    return Err(Error::Operation(Some(
                        "The key is not an elliptic curve public key".into(),
                    )));
                },
            }
            .map_err(|_| {
                Error::Operation(Some("Failed to export elliptic curve public key".into()))
            })?;

            // Step 3.3. Let result be the result of DER-encoding data.
            ExportedKey::new_bytes(data.to_vec())
        },
        // If format is "pkcs8":
        KeyFormat::Pkcs8 => {
            // Step 3.1. If the [[type]] internal slot of key is not "private", then throw an
            // InvalidAccessError.
            if key.Type() != KeyType::Private {
                return Err(Error::InvalidAccess(Some(
                    "[[type]] internal slot of key is not \"private\"".into(),
                )));
            }

            // Step 3.2.
            // Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208]
            // with the following properties:
            //     * Set the version field to 0.
            //     * Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1
            //       type with the following properties:
            //         * Set the algorithm field to the OID id-ecPublicKey defined in [RFC5480].
            //         * Set the parameters field to an instance of the ECParameters ASN.1 type
            //           defined in [RFC5480] as follows:
            //             If the namedCurve attribute of the [[algorithm]] internal slot of key is
            //             "P-256", "P-384" or "P-521":
            //                 Let keyData be the result of DER-encoding an instance of the
            //                 ECPrivateKey structure defined in Section 3 of [RFC5915] for the
            //                 Elliptic Curve private key represented by the [[handle]] internal
            //                 slot of key and that conforms to the following:
            //                     * The parameters field is present, and is equivalent to the
            //                       parameters field of the privateKeyAlgorithm field of this
            //                       PrivateKeyInfo ASN.1 structure.
            //                     * The publicKey field is present and represents the Elliptic
            //                       Curve public key associated with the Elliptic Curve private key
            //                       represented by the [[handle]] internal slot of key.
            //                     * If the namedCurve attribute of the [[algorithm]] internal slot
            //                       of key is "P-256":
            //                         Set parameters to the namedCurve choice with value equal to
            //                         the object identifier secp256r1 defined in [RFC5480]
            //                     * If the namedCurve attribute of the [[algorithm]] internal slot
            //                       of key is "P-384":
            //                         Set parameters to the namedCurve choice with value equal to
            //                         the object identifier secp384r1 defined in [RFC5480]
            //                     * If the namedCurve attribute of the [[algorithm]] internal slot
            //                       of key is "P-521":
            //                         Set parameters to the namedCurve choice with value equal to
            //                         the object identifier secp521r1 defined in [RFC5480]
            //             Otherwise:
            //                 1. Perform any key export steps defined by other applicable
            //                    specifications, passing format and the namedCurve attribute of
            //                    the [[algorithm]] internal slot of key and obtaining
            //                    namedCurveOid and keyData.
            //                 2. Set parameters to the namedCurve choice with value equal to the
            //                    object identifier namedCurveOid.
            //     * Set the privateKey field to keyData.
            // NOTE: We currently do not support other applicable specifications.
            let data = match key.handle() {
                Handle::P256PrivateKey(private_key) => private_key.to_pkcs8_der(),
                Handle::P384PrivateKey(private_key) => private_key.to_pkcs8_der(),
                Handle::P521PrivateKey(private_key) => private_key.to_pkcs8_der(),
                _ => {
                    return Err(Error::Operation(Some(
                        "The key is not an elliptic curve public key".into(),
                    )));
                },
            }
            .map_err(|_| {
                Error::Operation(Some("Failed to export elliptic curve private key".into()))
            })?;

            // Step 3.3. Let result be the result of DER-encoding data.
            ExportedKey::new_bytes(data.as_bytes().to_vec())
        },
        // If format is "jwk":
        KeyFormat::Jwk => {
            // Step 3.1. Let jwk be a new JsonWebKey dictionary.
            let mut jwk = JsonWebKey::default();

            // Step 3.2. Set the kty attribute of jwk to "EC".
            jwk.kty = Some(DOMString::from("EC"));

            // Step 3.3.
            let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
                return Err(Error::Operation(Some(
                    "The key is not an elliptic curve key".into(),
                )));
            };
            // If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256",
            // "P-384" or "P-521":
            if matches!(
                algorithm.named_curve.as_str(),
                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
            ) {
                // Step 3.3.1.
                // If the namedCurve attribute of the [[algorithm]] internal slot of key is
                // "P-256":
                //     Set the crv attribute of jwk to "P-256"
                // If the namedCurve attribute of the [[algorithm]] internal slot of key is
                // "P-384":
                //     Set the crv attribute of jwk to "P-384"
                // If the namedCurve attribute of the [[algorithm]] internal slot of key is
                // "P-521":
                //     Set the crv attribute of jwk to "P-521"
                jwk.crv = Some(DOMString::from(algorithm.named_curve.as_str()));

                // Step 3.3.2. Set the x attribute of jwk according to the definition in Section
                // 6.2.1.2 of JSON Web Algorithms [JWA].
                // Step 3.3.3. Set the y attribute of jwk according to the definition in Section
                // 6.2.1.3 of JSON Web Algorithms [JWA].
                let extraction_error = || {
                    Error::Operation(Some(
                        "Failed to extract encoded point from elliptic curve key".into(),
                    ))
                };
                let (x, y) = match key.handle() {
                    Handle::P256PublicKey(public_key) => {
                        let encoded_point = public_key.to_sec1_point(false);
                        (
                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
                        )
                    },
                    Handle::P384PublicKey(public_key) => {
                        let encoded_point = public_key.to_sec1_point(false);
                        (
                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
                        )
                    },
                    Handle::P521PublicKey(public_key) => {
                        let encoded_point = public_key.to_sec1_point(false);
                        (
                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
                        )
                    },
                    Handle::P256PrivateKey(private_key) => {
                        let public_key = private_key.public_key();
                        let encoded_point = public_key.to_sec1_point(false);
                        (
                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
                        )
                    },
                    Handle::P384PrivateKey(private_key) => {
                        let public_key = private_key.public_key();
                        let encoded_point = public_key.to_sec1_point(false);
                        (
                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
                        )
                    },
                    Handle::P521PrivateKey(private_key) => {
                        let public_key = private_key.public_key();
                        let encoded_point = public_key.to_sec1_point(false);
                        (
                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
                        )
                    },
                    _ => {
                        return Err(Error::Operation(Some(
                            "The key is not an elliptic curve key".into(),
                        )));
                    },
                };
                jwk.encode_string_field(JwkStringField::X, &x);
                jwk.encode_string_field(JwkStringField::Y, &y);

                // Step 3.3.4.
                // If the [[type]] internal slot of key is "private"
                //     Set the d attribute of jwk according to the definition in Section 6.2.2.1 of
                //     JSON Web Algorithms [JWA].
                if key.Type() == KeyType::Private {
                    let d = match key.handle() {
                        Handle::P256PrivateKey(private_key) => {
                            private_key.to_bytes().as_slice().to_vec()
                        },
                        Handle::P384PrivateKey(private_key) => {
                            private_key.to_bytes().as_slice().to_vec()
                        },
                        Handle::P521PrivateKey(private_key) => {
                            private_key.to_bytes().as_slice().to_vec()
                        },
                        _ => {
                            return Err(Error::Operation(Some(
                                "The key is not an elliptic curve private key".into(),
                            )));
                        },
                    };
                    jwk.encode_string_field(JwkStringField::D, &d);
                }
            }
            // Otherwise:
            else {
                // Step 3.3.1. Perform any key export steps defined by other applicable
                // specifications, passing format and the namedCurve attribute of the [[algorithm]]
                // internal slot of key and obtaining namedCurve and a new value of jwk.
                // Step 3.3.2. Set the crv attribute of jwk to namedCurve.
                // NOTE: We currently do not support other applicable specifications.
                return Err(Error::NotSupported(Some("Unsupported named curve".into())));
            }

            // Step 3.4. Set the key_ops attribute of jwk to the usages attribute of key.
            jwk.set_key_ops(&key.usages());

            // Step 3.4. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
            jwk.ext = Some(key.Extractable());

            // Step 3.4. Let result be jwk.
            ExportedKey::new_jwk(jwk)
        },
        // If format is "raw":
        KeyFormat::Raw | KeyFormat::Raw_public => {
            // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
            // InvalidAccessError.
            if key.Type() != KeyType::Public {
                return Err(Error::InvalidAccess(Some(
                    "[[type]] internal slot of key is not \"public\"".into(),
                )));
            }

            // Step 3.2.
            // If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256",
            // "P-384" or "P-521":
            //     Let data be a byte sequence representing the Elliptic Curve point Q represented
            //     by the [[handle]] internal slot of key according to [SEC1] 2.3.3 using the
            //     uncompressed format.
            // Otherwise:
            //     Perform any key export steps defined by other applicable specifications, passing
            //     format and the namedCurve attribute of the [[algorithm]] internal slot of key
            //     and obtaining namedCurve and data.
            //     NOTE: We currently do not support other applicable specifications.
            let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
                return Err(Error::Operation(Some(
                    "The key is not an elliptic curve key".into(),
                )));
            };
            let data = if matches!(
                algorithm.named_curve.as_str(),
                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
            ) {
                match key.handle() {
                    Handle::P256PublicKey(public_key) => public_key.to_sec1_bytes().to_vec(),
                    Handle::P384PublicKey(public_key) => public_key.to_sec1_bytes().to_vec(),
                    Handle::P521PublicKey(public_key) => public_key.to_sec1_bytes().to_vec(),
                    _ => {
                        return Err(Error::Operation(Some(
                            "The key is not an elliptic curve public key".into(),
                        )));
                    },
                }
            } else {
                return Err(Error::NotSupported(Some("Unsupported named curve".into())));
            };

            // Step 3.3. Let result be data.
            ExportedKey::new_bytes(data)
        },
        // Otherwise:
        _ => {
            // throw a NotSupportedError.
            return Err(Error::NotSupported(Some("Unsupported key format".into())));
        },
    };

    // Step 4. Return result.
    Ok(result)
}

/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
/// Step 9 - 15, for elliptic curve cryptography
pub(crate) fn get_public_key(
    cx: &mut JSContext,
    global: &GlobalScope,
    key: &CryptoKey,
    algorithm: &KeyAlgorithmAndDerivatives,
    usages: Vec<KeyUsage>,
) -> Result<DomRoot<CryptoKey>, Error> {
    // Step 9. If usages contains an entry which is not supported for a public key by the algorithm
    // identified by algorithm, then throw a SyntaxError.
    //
    // NOTE: See "importKey" operation for supported usages
    if usages.iter().any(|usage| *usage != KeyUsage::Verify) {
        return Err(Error::Syntax(Some(
            "Usages contains an entry which is not \"verify\"".to_string(),
        )));
    }

    // Step 10. Let publicKey be a new CryptoKey representing the public key corresponding to the
    // private key represented by the [[handle]] internal slot of key.
    // Step 11. If an error occurred, then throw a OperationError.
    // Step 12. Set the [[type]] internal slot of publicKey to "public".
    // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
    // Step 14. Set the [[extractable]] internal slot of publicKey to true.
    // Step 15. Set the [[usages]] internal slot of publicKey to usages.
    let public_key_handle = match key.handle() {
        Handle::P256PrivateKey(private_key) => Handle::P256PublicKey(private_key.public_key()),
        Handle::P384PrivateKey(private_key) => Handle::P384PublicKey(private_key.public_key()),
        Handle::P521PrivateKey(private_key) => Handle::P521PublicKey(private_key.public_key()),
        _ => {
            return Err(Error::Operation(Some(
                "[[handle]] internal slot of key is not an elliptic curve private key".to_string(),
            )));
        },
    };
    let public_key = CryptoKey::new(
        cx,
        global,
        KeyType::Public,
        true,
        algorithm.clone(),
        usages,
        public_key_handle,
    );

    Ok(public_key)
}

/// Concatenate big endian serialized coordinates of an elliptic curve point, to form an
/// uncompressed SEC1 encoded curve point, with prefix `0x04` indicating it is an uncompressed
/// point.
fn x_y_to_sec1_bytes(x: &[u8], y: &[u8]) -> Vec<u8> {
    let mut sec1_bytes = Vec::with_capacity(1 + x.len() + y.len());
    sec1_bytes.push(4u8);
    sec1_bytes.extend_from_slice(x);
    sec1_bytes.extend_from_slice(y);
    sec1_bytes
}

/// Validate the public key in form of uncompressed SEC1 encoded curve point, against a private key.
fn validate_public_key<C>(private_key: &SecretKey<C>, sec1_bytes: &[u8]) -> ErrorResult
where
    C: Curve + ValidatePublicKey,
    FieldBytesSize<C>: ModulusSize,
{
    let sec1_point = Sec1Point::<C>::from_bytes(sec1_bytes)
        .map_err(|_| Error::Data(Some("Failed to encode curve point".into())))?;
    C::validate_public_key(private_key, &sec1_point)
        .map_err(|_| Error::Data(Some("The public key does not match the private key".into())))
}