Skip to main content

script_webcrypto/subtlecrypto/
ecdsa_operation.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use ecdsa::signature::hazmat::{PrehashVerifier, RandomizedPrehashSigner};
6use ecdsa::{Signature, SigningKey, VerifyingKey};
7use js::context::JSContext;
8use p256::NistP256;
9use p384::NistP384;
10use p521::NistP521;
11use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
12    CryptoKeyPair, KeyType, KeyUsage,
13};
14use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::KeyFormat;
15use script_bindings::error::Error;
16use script_bindings::root::DomRoot;
17use script_bindings::trace::RootedTraceableBox;
18
19use crate::cryptokey::{CryptoKey, Handle};
20use crate::subtlecrypto::ec_common::EcAlgorithm;
21use crate::subtlecrypto::{
22    EcKeyGenParams, EcKeyImportParams, EcdsaParams, ExportedKey, KeyAlgorithmAndDerivatives,
23    NAMED_CURVE_P256, NAMED_CURVE_P384, NAMED_CURVE_P521, ec_common,
24};
25use crate::traits::Equivalence;
26
27/// <https://w3c.github.io/webcrypto/#ecdsa-operations-sign>
28pub(crate) fn sign<D: Equivalence>(
29    normalized_algorithm: &EcdsaParams,
30    key: &CryptoKey<D>,
31    message: &[u8],
32) -> Result<Vec<u8>, Error> {
33    // Step 1. If the [[type]] internal slot of key is not "private", then throw an
34    // InvalidAccessError.
35    key.ensure_type(KeyType::Private)?;
36
37    // Step 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
38    let hash_algorithm = &normalized_algorithm.hash;
39
40    // Step 3. Let M be the result of performing the digest operation specified by hashAlgorithm
41    // using message.
42    let m = hash_algorithm.digest(message)?;
43
44    // Step 4. Let d be the ECDSA private key associated with key.
45    // Step 5. Let params be the EC domain parameters associated with key.
46    // Step 6.
47    // If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or
48    // "P-521":
49    //     1. Perform the ECDSA signing process, as specified in [RFC6090], Section 5.4.2, with M
50    //        as the message, using params as the EC domain parameters, and with d as the private
51    //        key.
52    //     2. Let r and s be the pair of integers resulting from performing the ECDSA signing
53    //        process.
54    //     3. Let result be an empty byte sequence.
55    //     4. Let n be the smallest integer such that n * 8 is greater than the logarithm to base 2
56    //        of the order of the base point of the elliptic curve identified by params.
57    //     5. Convert r to a byte sequence of length n and append it to result.
58    //     6. Convert s to a byte sequence of length n and append it to result.
59    // Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value
60    // specified in an applicable specification:
61    //     Perform the ECDSA signature steps specified in that specification, passing in M, params
62    //     and d and resulting in result.
63    // NOTE: We currently do not support other applicable specifications.
64    let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
65        return Err(Error::Operation(Some(
66            "Key algorithm is not a elliptic curve key algorithm.".into(),
67        )));
68    };
69    let mut rng = rand::rng();
70    let result = match algorithm.named_curve.as_str() {
71        NAMED_CURVE_P256 => {
72            let Handle::P256PrivateKey(d) = key.handle() else {
73                return Err(Error::Operation(Some(
74                    "Key handle is not a P256PrivateKey.".into(),
75                )));
76            };
77            let signing_key = SigningKey::<NistP256>::from(d);
78            let signature: Signature<NistP256> = signing_key
79                .sign_prehash_with_rng(&mut rng, &m)
80                .map_err(|_| Error::Operation(Some("ECDSA signing process failed.".into())))?;
81            signature.to_vec()
82        },
83        NAMED_CURVE_P384 => {
84            let Handle::P384PrivateKey(d) = key.handle() else {
85                return Err(Error::Operation(Some(
86                    "Key handle is not a P384PrivateKey.".into(),
87                )));
88            };
89            let signing_key = SigningKey::<NistP384>::from(d);
90            let signature: Signature<NistP384> = signing_key
91                .sign_prehash_with_rng(&mut rng, &m)
92                .map_err(|_| Error::Operation(Some("ECDSA signing process failed.".into())))?;
93            signature.to_vec()
94        },
95        NAMED_CURVE_P521 => {
96            let Handle::P521PrivateKey(d) = key.handle() else {
97                return Err(Error::Operation(Some(
98                    "Key handle is not a P521PrivateKey.".into(),
99                )));
100            };
101            let signing_key = SigningKey::<NistP521>::from(d);
102            let signature: Signature<NistP521> = signing_key
103                .sign_prehash_with_rng(&mut rng, &m)
104                .map_err(|_| Error::Operation(Some("ECDSA signing process failed.".into())))?;
105            signature.to_vec()
106        },
107        _ => {
108            return Err(Error::NotSupported(Some(
109                "Algorithm's curve is not supported.".into(),
110            )));
111        },
112    };
113
114    // Step 7. Return result.
115    Ok(result)
116}
117
118/// <https://w3c.github.io/webcrypto/#ecdsa-operations-verify>
119pub(crate) fn verify<D: Equivalence>(
120    normalized_algorithm: &EcdsaParams,
121    key: &CryptoKey<D>,
122    message: &[u8],
123    signature: &[u8],
124) -> Result<bool, Error> {
125    // Step 1. If the [[type]] internal slot of key is not "public", then throw an
126    // InvalidAccessError.
127    key.ensure_type(KeyType::Public)?;
128
129    // Step 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
130    let hash_algorithm = &normalized_algorithm.hash;
131
132    // Step 3. Let M be the result of performing the digest operation specified by hashAlgorithm
133    // using message.
134    let m = hash_algorithm.digest(message)?;
135
136    // Step 4. Let Q be the ECDSA public key associated with key.
137    // Step 5. Let params be the EC domain parameters associated with key.
138    // Step 6.
139    // If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or
140    // "P-521":
141    //     1. Let n be the smallest integer such that n * 8 is greater than the logarithm to base 2
142    //        of the order of the base point of the elliptic curve identified by params.
143    //     2. If signature does not have a length of n * 2 bytes, then return false.
144    //     3. Let r be the result of converting the first n bytes of signature to an integer.
145    //     4. Let s be the result of converting the last n bytes of signature to an integer.
146    //     5. Perform the ECDSA verifying process, as specified in [RFC6090], Section 5.4.3, with M
147    //        as the received message, (r, s) as the signature and using params as the EC domain
148    //        parameters, and Q as the public key.
149    // Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value
150    // specified in an applicable specification:
151    //     Perform the ECDSA verification steps specified in that specification passing in M,
152    //     signature, params and Q and resulting in an indication of whether or not the purported
153    //     signature is valid.
154    // Step 7. Let result be a boolean with the value true if the signature is valid and the value
155    // false otherwise.
156    // NOTE: We currently do not support other applicable specifications.
157    let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
158        return Err(Error::Operation(Some(
159            "Key algorithm is not a elliptic curve key algorithm.".into(),
160        )));
161    };
162    let result = match algorithm.named_curve.as_str() {
163        NAMED_CURVE_P256 => {
164            let Handle::P256PublicKey(q) = key.handle() else {
165                return Err(Error::Operation(Some(
166                    "Key handle is not a P256PublicKey.".into(),
167                )));
168            };
169            match Signature::<NistP256>::from_slice(signature) {
170                Ok(signature) => {
171                    let verifying_key = VerifyingKey::<NistP256>::from(q);
172                    verifying_key.verify_prehash(&m, &signature).is_ok()
173                },
174                Err(_) => false,
175            }
176        },
177        NAMED_CURVE_P384 => {
178            let Handle::P384PublicKey(q) = key.handle() else {
179                return Err(Error::Operation(Some(
180                    "Key handle is not a P384PublicKey.".into(),
181                )));
182            };
183            match Signature::<NistP384>::from_slice(signature) {
184                Ok(signature) => {
185                    let verifying_key = VerifyingKey::<NistP384>::from(q);
186                    verifying_key.verify_prehash(&m, &signature).is_ok()
187                },
188                Err(_) => false,
189            }
190        },
191        NAMED_CURVE_P521 => {
192            let Handle::P521PublicKey(q) = key.handle() else {
193                return Err(Error::Operation(Some(
194                    "Key handle is not a P521PublicKey.".into(),
195                )));
196            };
197            match Signature::<NistP521>::from_slice(signature) {
198                Ok(signature) => {
199                    let verifying_key = VerifyingKey::<NistP521>::from(q);
200                    verifying_key.verify_prehash(&m, &signature).is_ok()
201                },
202                Err(_) => false,
203            }
204        },
205        _ => {
206            return Err(Error::NotSupported(Some(
207                "Algorithm's curve is not supported.".into(),
208            )));
209        },
210    };
211
212    // Step 8. Return result.
213    Ok(result)
214}
215
216/// <https://w3c.github.io/webcrypto/#ecdsa-operations-generate-key>
217pub(crate) fn generate_key<D: Equivalence>(
218    cx: &mut JSContext,
219    global: &D::GlobalScope,
220    normalized_algorithm: &EcKeyGenParams,
221    extractable: bool,
222    usages: Vec<KeyUsage>,
223) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
224    ec_common::generate_key(
225        cx,
226        global,
227        EcAlgorithm::Ecdsa,
228        normalized_algorithm,
229        extractable,
230        usages,
231    )
232}
233
234/// <https://w3c.github.io/webcrypto/#ecdsa-operations-import-key>
235pub(crate) fn import_key<D: Equivalence>(
236    cx: &mut JSContext,
237    global: &D::GlobalScope,
238    normalized_algorithm: &EcKeyImportParams,
239    format: KeyFormat,
240    key_data: &[u8],
241    extractable: bool,
242    usages: Vec<KeyUsage>,
243) -> Result<DomRoot<CryptoKey<D>>, Error> {
244    ec_common::import_key(
245        cx,
246        global,
247        EcAlgorithm::Ecdsa,
248        normalized_algorithm,
249        format,
250        key_data,
251        extractable,
252        usages,
253    )
254}
255
256/// <https://w3c.github.io/webcrypto/#ecdsa-operations-export-key>
257pub(crate) fn export_key<D: Equivalence>(
258    format: KeyFormat,
259    key: &CryptoKey<D>,
260) -> Result<ExportedKey, Error> {
261    ec_common::export_key(format, key)
262}
263
264/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
265/// Step 9 - 15, for ECDSA
266pub(crate) fn get_public_key<D: Equivalence>(
267    cx: &mut JSContext,
268    global: &D::GlobalScope,
269    key: &CryptoKey<D>,
270    algorithm: &KeyAlgorithmAndDerivatives,
271    usages: Vec<KeyUsage>,
272) -> Result<DomRoot<CryptoKey<D>>, Error> {
273    ec_common::get_public_key(cx, global, EcAlgorithm::Ecdsa, key, algorithm, usages)
274}