script_webcrypto/subtlecrypto/
ecdh_operation.rs1use 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
31pub(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
49pub(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 let public_key = normalized_algorithm.public.root();
57
58 public_key.ensure_type(KeyType::Public)?;
61
62 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 let maximum_length = maximum_length(&public_key)?;
76
77 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 key.ensure_type(KeyType::Private)?;
89
90 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 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 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 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
216pub(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
238pub(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
246pub(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
258pub(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}