Skip to main content

script_webcrypto/subtlecrypto/
ecdh_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 elliptic_curve::Curve;
6use elliptic_curve::array::typenum::Unsigned;
7use js::context::JSContext;
8use p256::NistP256;
9use p256::ecdh::diffie_hellman as p256_diffie_hellman;
10use p384::NistP384;
11use p384::ecdh::diffie_hellman as p384_diffie_hellman;
12use p521::NistP521;
13use p521::ecdh::diffie_hellman as p521_diffie_hellman;
14use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
15    CryptoKeyPair, KeyType, KeyUsage,
16};
17use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::KeyFormat;
18use script_bindings::error::Error;
19use script_bindings::root::DomRoot;
20use script_bindings::trace::RootedTraceableBox;
21
22use crate::cryptokey::{CryptoKey, Handle};
23use crate::subtlecrypto::ec_common::EcAlgorithm;
24use crate::subtlecrypto::{
25    EcKeyGenParams, EcKeyImportParams, EcdhKeyDeriveParams, ExportedKey,
26    KeyAlgorithmAndDerivatives, NAMED_CURVE_P256, NAMED_CURVE_P384, NAMED_CURVE_P521, ec_common,
27    truncate_bit_sequence,
28};
29use crate::traits::Equivalence;
30
31/// <https://w3c.github.io/webcrypto/#ecdh-operations-generate-key>
32pub(crate) fn generate_key<D: Equivalence>(
33    cx: &mut JSContext,
34    global: &D::GlobalScope,
35    normalized_algorithm: &EcKeyGenParams,
36    extractable: bool,
37    usages: Vec<KeyUsage>,
38) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
39    ec_common::generate_key(
40        cx,
41        global,
42        EcAlgorithm::Ecdh,
43        normalized_algorithm,
44        extractable,
45        usages,
46    )
47}
48
49/// <https://w3c.github.io/webcrypto/#ecdh-operations-derive-bits>
50pub(crate) fn derive_bits<D: Equivalence>(
51    normalized_algorithm: &EcdhKeyDeriveParams<D>,
52    key: &CryptoKey<D>,
53    length: Option<u32>,
54) -> Result<Vec<u8>, Error> {
55    // Step 1. Let publicKey be the public member of normalizedAlgorithm.
56    let public_key = normalized_algorithm.public.root();
57
58    // Step 2. If the [[type]] internal slot of publicKey is not "public", then throw an
59    // InvalidAccessError.
60    public_key.ensure_type(KeyType::Public)?;
61
62    // Step 3. If the name attribute of the [[algorithm]] internal slot of publicKey is not equal to
63    // the name member of normalizedAlgorithm, then throw an InvalidAccessError.
64    if public_key.algorithm().name() != normalized_algorithm.name {
65        return Err(Error::InvalidAccess(Some(
66            "The name attribute of the [[algorithm]] internal slot of publicKey does not match \
67                the name member of normalizedAlgorithm"
68                .into(),
69        )));
70    }
71
72    // Step 4. Let maximumLength be the length in bits of the output of the field element to octet
73    // string conversion defined in Section 6.2 of [RFC6090] for the EC domain parameters associated
74    // with publicKey.
75    let maximum_length = maximum_length(&public_key)?;
76
77    // Step 5. If length is not null and is greater than maximumLength, then throw an
78    // OperationError.
79    if length.is_some_and(|length| length > maximum_length) {
80        return Err(Error::Operation(Some(
81            "Required length is greater than the maximum length supported by the elliptic curve"
82                .into(),
83        )));
84    }
85
86    // Step 6. If the [[type]] internal slot of key is not "private", then throw an
87    // InvalidAccessError.
88    key.ensure_type(KeyType::Private)?;
89
90    // Step 7. If the name attribute of the [[algorithm]] internal slot of publicKey is not equal
91    // to the name property of the [[algorithm]] internal slot of key, then throw an
92    // InvalidAccessError.
93    if public_key.algorithm().name() != key.algorithm().name() {
94        return Err(Error::InvalidAccess(Some(
95            "public key [[algorithm]] internal slot name does not match that of private key"
96                .to_string(),
97        )));
98    }
99
100    // Step 8. If the namedCurve attribute of the [[algorithm]] internal slot of publicKey is not
101    // equal to the namedCurve property of the [[algorithm]] internal slot of key, then throw an
102    // InvalidAccessError.
103    let (
104        KeyAlgorithmAndDerivatives::EcKeyAlgorithm(public_key_algorithm),
105        KeyAlgorithmAndDerivatives::EcKeyAlgorithm(key_algorithm),
106    ) = (public_key.algorithm(), key.algorithm())
107    else {
108        return Err(Error::Operation(Some(
109            "Public or private key [[algorithm]] internal slot is not an elliptic curve algorithm"
110                .into(),
111        )));
112    };
113    if public_key_algorithm.named_curve != key_algorithm.named_curve {
114        return Err(Error::InvalidAccess(Some(
115            "Public and private keys [[algorithm]] internal slots namedCurves do not match".into(),
116        )));
117    }
118
119    // Step 9.
120    // If the namedCurve property of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
121    //     Step 9.1. Perform the ECDH primitive specified in [RFC6090] Section 4 with key as the EC
122    //     private key d and the EC public key represented by the [[handle]] internal slot of
123    //     publicKey as the EC public key.
124    //
125    //     Step 9.2. Let secret be a byte sequence containing the result of applying the field
126    //     element to octet string conversion defined in Section 6.2 of [RFC6090] to the output of
127    //     the ECDH primitive.
128    //
129    // If the namedCurve property of the [[algorithm]] internal slot of key is a value specified in
130    // an applicable specification that specifies the use of that value with ECDH:
131    //     Perform the ECDH derivation steps specified in that specification, passing in key and
132    //     publicKey and resulting in secret.
133    //
134    // Otherwise:
135    //     throw a NotSupportedError
136    //
137    // Step 10. If performing the operation results in an error, then throw a OperationError.
138    let secret = match key_algorithm.named_curve.as_str() {
139        NAMED_CURVE_P256 => {
140            let Handle::P256PrivateKey(private_key) = key.handle() else {
141                return Err(Error::Operation(Some(
142                    "Private key is not a P-256 private key".to_string(),
143                )));
144            };
145            let Handle::P256PublicKey(public_key) = public_key.handle() else {
146                return Err(Error::Operation(Some(
147                    "Public key is not a P-256 public key".to_string(),
148                )));
149            };
150            p256_diffie_hellman(private_key.to_nonzero_scalar(), public_key.as_affine())
151                .raw_secret_bytes()
152                .to_vec()
153        },
154        NAMED_CURVE_P384 => {
155            let Handle::P384PrivateKey(private_key) = key.handle() else {
156                return Err(Error::Operation(Some(
157                    "Private key is not a P-384 private key".to_string(),
158                )));
159            };
160            let Handle::P384PublicKey(public_key) = public_key.handle() else {
161                return Err(Error::Operation(Some(
162                    "Public key is not a P384 public key".to_string(),
163                )));
164            };
165            p384_diffie_hellman(private_key.to_nonzero_scalar(), public_key.as_affine())
166                .raw_secret_bytes()
167                .to_vec()
168        },
169        NAMED_CURVE_P521 => {
170            let Handle::P521PrivateKey(private_key) = key.handle() else {
171                return Err(Error::Operation(Some(
172                    "Private key is not a P-521 private key".to_string(),
173                )));
174            };
175            let Handle::P521PublicKey(public_key) = public_key.handle() else {
176                return Err(Error::Operation(Some(
177                    "Public key is not a P-521 public key".to_string(),
178                )));
179            };
180            p521_diffie_hellman(private_key.to_nonzero_scalar(), public_key.as_affine())
181                .raw_secret_bytes()
182                .to_vec()
183        },
184        _ => {
185            return Err(Error::NotSupported(Some(format!(
186                "Unsupported namedCurve: {}",
187                key_algorithm.named_curve
188            ))));
189        },
190    };
191
192    // Step 11.
193    // If length is null:
194    //     Return secret
195    // Otherwise:
196    //     If the length in bits of secret is less than length:
197    //         throw an OperationError.
198    //     Otherwise:
199    //         Return a byte sequence containing the first length bits of secret.
200    match length {
201        None => Ok(secret),
202        Some(length) => {
203            if secret.len() * 8 < length as usize {
204                Err(Error::Operation(Some(
205                    "Derived secret is too short".to_string(),
206                )))
207            } else {
208                let mut secret = secret[..length.div_ceil(8) as usize].to_vec();
209                truncate_bit_sequence(&mut secret, length as usize);
210                Ok(secret)
211            }
212        },
213    }
214}
215
216/// <https://w3c.github.io/webcrypto/#ecdh-operations-import-key>
217pub(crate) fn import_key<D: Equivalence>(
218    cx: &mut JSContext,
219    global: &D::GlobalScope,
220    normalized_algorithm: &EcKeyImportParams,
221    format: KeyFormat,
222    key_data: &[u8],
223    extractable: bool,
224    usages: Vec<KeyUsage>,
225) -> Result<DomRoot<CryptoKey<D>>, Error> {
226    ec_common::import_key(
227        cx,
228        global,
229        EcAlgorithm::Ecdh,
230        normalized_algorithm,
231        format,
232        key_data,
233        extractable,
234        usages,
235    )
236}
237
238/// <https://w3c.github.io/webcrypto/#ecdh-operations-export-key>
239pub(crate) fn export_key<D: Equivalence>(
240    format: KeyFormat,
241    key: &CryptoKey<D>,
242) -> Result<ExportedKey, Error> {
243    ec_common::export_key(format, key)
244}
245
246/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
247/// Step 9 - 15, for ECDH
248pub(crate) fn get_public_key<D: Equivalence>(
249    cx: &mut JSContext,
250    global: &D::GlobalScope,
251    key: &CryptoKey<D>,
252    algorithm: &KeyAlgorithmAndDerivatives,
253    usages: Vec<KeyUsage>,
254) -> Result<DomRoot<CryptoKey<D>>, Error> {
255    ec_common::get_public_key(cx, global, EcAlgorithm::Ecdh, key, algorithm, usages)
256}
257
258/// Given an elliptic curve key, returns the length in bits of the output of the field element to
259/// octet string conversion defined in Section 6.2 of [RFC6090] for the EC domain parameters
260/// associated with key.
261pub(crate) fn maximum_length<D: Equivalence>(key: &CryptoKey<D>) -> Result<u32, Error> {
262    let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
263        return Err(Error::Operation(Some(
264            "The key is not an elliptic curve algorithm key".to_string(),
265        )));
266    };
267
268    let maximum_length_in_bytes = match algorithm.named_curve.as_str() {
269        NAMED_CURVE_P256 => <NistP256 as Curve>::FieldBytesSize::to_u32(),
270        NAMED_CURVE_P384 => <NistP384 as Curve>::FieldBytesSize::to_u32(),
271        NAMED_CURVE_P521 => <NistP521 as Curve>::FieldBytesSize::to_u32(),
272        named_curve => {
273            return Err(Error::NotSupported(Some(format!(
274                "Unsupported namedCurve: {}",
275                named_curve
276            ))));
277        },
278    };
279
280    Ok(maximum_length_in_bytes * 8)
281}