Diffinery

homeflare/celldpublic

celld/crates/celld/js/crypto.rs
1890 lines · 81.3 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Web Crypto and node:crypto: the key formats and the primitives.
4//!
5//! The JS layer in `crypto.js` and `node_crypto.js` validates the arguments,
6//! so what arrives here is already well formed. This module holds the key
7//! formats — SPKI, PKCS#8, JWK, raw — and the operations that use them. It
8//! touches V8 only in its ops.
9use super::*;
10
11fn crypto_bytes(value: &serde_json::Value, name: &str) -> Result<Vec<u8>> {
12 serde_json::from_value(value.get(name).cloned().unwrap_or_default())
13 .map_err(|_| anyhow!("invalid {name} bytes"))
14}
15
16fn rsa_jwk_uint(value: &serde_json::Value, name: &str) -> Result<rsa::BigUint> {
17 use base64::Engine;
18 let encoded = value
19 .get(name)
20 .and_then(|value| value.as_str())
21 .ok_or_else(|| anyhow!("RSA JWK missing {name} parameter"))?;
22 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
23 .decode(encoded)
24 .map_err(|_| anyhow!("invalid RSA JWK {name}"))?;
25 Ok(rsa::BigUint::from_bytes_be(&bytes))
26}
27
28fn rsa_jwk_encode(value: &rsa::BigUint) -> String {
29 use base64::Engine;
30 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.to_bytes_be())
31}
32
33fn rsa_oaep_padding(hash: &str, label: Vec<u8>) -> Result<rsa::Oaep> {
34 let label = if label.is_empty() {
35 None
36 } else {
37 Some(
38 String::from_utf8(label)
39 .map_err(|_| anyhow!("RSA-OAEP labels must contain UTF-8 bytes"))?,
40 )
41 };
42 macro_rules! padding {
43 ($digest:ty) => {
44 match label {
45 Some(label) => rsa::Oaep::new_with_label::<$digest, _>(label),
46 None => rsa::Oaep::new::<$digest>(),
47 }
48 };
49 }
50 Ok(match hash {
51 "SHA-1" => padding!(sha1::Sha1),
52 "SHA-256" => padding!(sha2::Sha256),
53 "SHA-384" => padding!(sha2::Sha384),
54 "SHA-512" => padding!(sha2::Sha512),
55 other => return Err(anyhow!("unsupported RSA-OAEP hash {other}")),
56 })
57}
58
59fn digest_bytes(hash: &str, data: &[u8]) -> Result<Vec<u8>> {
60 use sha2::Digest as _;
61 Ok(match hash {
62 "SHA-256" => sha2::Sha256::digest(data).to_vec(),
63 "SHA-384" => sha2::Sha384::digest(data).to_vec(),
64 "SHA-512" => sha2::Sha512::digest(data).to_vec(),
65 other => return Err(anyhow!("unsupported ECDSA hash {other}")),
66 })
67}
68
69/// Algorithm OIDs, so a parsed key can say what it is. Same constants as
70/// Node's, via deno's `ext/node_crypto/keys.rs`.
71const RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
72 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
73const EC_PUBLIC_KEY_OID: rsa::pkcs8::ObjectIdentifier =
74 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
75const SECP256R1_OID: rsa::pkcs8::ObjectIdentifier =
76 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
77const SECP384R1_OID: rsa::pkcs8::ObjectIdentifier =
78 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.132.0.34");
79const SECP521R1_OID: rsa::pkcs8::ObjectIdentifier =
80 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.132.0.35");
81
82/// The NIST curves celld reads, as (OID, Node's `namedCurve`, JWK `crv`).
83const EC_CURVES: &[(rsa::pkcs8::ObjectIdentifier, &str, &str)] = &[
84 (SECP256R1_OID, "prime256v1", "P-256"),
85 (SECP384R1_OID, "secp384r1", "P-384"),
86 (SECP521R1_OID, "secp521r1", "P-521"),
87];
88
89/// Run `$body!(crate)` against whichever curve crate `$crv` names. The three
90/// crates share an API, so this is the alternative to writing every EC arm
91/// out three times.
92macro_rules! ec_curve {
93 ($crv:expr, $body:ident) => {
94 match $crv {
95 "P-256" => $body!(p256),
96 "P-384" => $body!(p384),
97 "P-521" => $body!(p521),
98 other => return Err(anyhow!("unsupported EC curve {other}")),
99 }
100 };
101}
102const ED25519_OID: rsa::pkcs8::ObjectIdentifier =
103 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.101.112");
104const X25519_OID: rsa::pkcs8::ObjectIdentifier =
105 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.101.110");
106const DSA_OID: rsa::pkcs8::ObjectIdentifier =
107 rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10040.4.1");
108
109/// A key normalized to one DER encoding: PKCS#8 for private, SPKI for public.
110/// Every consumer — the sign and verify ops, `toCryptoKey`, export — then
111/// reads one shape rather than five.
112struct ParsedKey {
113 kind: &'static str,
114 der: Vec<u8>,
115 details: serde_json::Value,
116}
117
118/// X25519 has no DER codec in `x25519-dalek`, and both structures are a
119/// fixed shape for a 32-byte key, so they are written out directly. Verified
120/// against the `x25519_private.pem` / `x25519_public.pem` fixtures.
121fn x25519_pkcs8(scalar: &[u8; 32]) -> Vec<u8> {
122 let mut der = vec![
123 0x30, 0x2e, // SEQUENCE, 46 bytes
124 0x02, 0x01, 0x00, // version 0
125 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, // AlgorithmIdentifier, X25519
126 0x04, 0x22, 0x04, 0x20, // OCTET STRING(34) wrapping OCTET STRING(32)
127 ];
128 der.extend_from_slice(scalar);
129 der
130}
131
132fn x25519_spki(point: &[u8; 32]) -> Vec<u8> {
133 let mut der = vec![
134 0x30, 0x2a, // SEQUENCE, 42 bytes
135 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, // AlgorithmIdentifier, X25519
136 0x03, 0x21, 0x00, // BIT STRING(33), no unused bits
137 ];
138 der.extend_from_slice(point);
139 der
140}
141
142/// The JWK `crv` for a parsed EC key, from the `namedCurve` its details
143/// already carry.
144fn ec_jwk_crv(parsed: &ParsedKey) -> Result<&'static str> {
145 let named = parsed.details["namedCurve"]
146 .as_str()
147 .ok_or_else(|| anyhow!("EC key has no named curve"))?;
148 EC_CURVES
149 .iter()
150 .find(|(_, node, _)| *node == named)
151 .map(|(.., crv)| *crv)
152 .ok_or_else(|| anyhow!("unsupported EC curve {named}"))
153}
154
155/// PEM armour: 64-character base64 lines between the labelled delimiters.
156fn pem_wrap(label: &str, bytes: &[u8]) -> String {
157 use base64::Engine;
158 let body = base64::engine::general_purpose::STANDARD.encode(bytes);
159 let mut out = format!("-----BEGIN {label}-----\n");
160 for line in body.as_bytes().chunks(64) {
161 out.push_str(std::str::from_utf8(line).unwrap());
162 out.push('\n');
163 }
164 out.push_str(&format!("-----END {label}-----\n"));
165 out
166}
167
168fn base64url(value: &[u8]) -> String {
169 use base64::Engine;
170 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value)
171}
172
173fn jwk_bytes(value: &serde_json::Value, kty: &str, name: &str) -> Result<Vec<u8>> {
174 use base64::Engine;
175 let encoded = value
176 .get(name)
177 .and_then(serde_json::Value::as_str)
178 .ok_or_else(|| anyhow!("{kty} JWK missing {name} parameter"))?;
179 base64::engine::general_purpose::URL_SAFE_NO_PAD
180 .decode(encoded)
181 .map_err(|_| anyhow!("invalid JWK {name}"))
182}
183
184/// Salt length OpenSSL uses for a PBES2 export, which is what Node inherits.
185const PBES2_SALT_LEN: usize = 8;
186/// PBKDF2 iteration count OpenSSL uses for a PBES2 export. Node inherits it,
187/// so an encrypted key celld writes costs a reader the same as a Node one.
188///
189/// This is far weaker than the scrypt cost `pkcs5` reaches for on its own, and
190/// deliberately so: an encrypted key is only as strong as the reader that has
191/// to open it, and every Node and OpenSSL reader expects these parameters. Do
192/// not raise it to harden the KDF -- that hardens celld's keys against celld
193/// alone and desyncs the format from the one the ecosystem writes.
194const PBES2_ITERATIONS: u32 = 2048;
195
196/// PBES2 parameters for an encrypted PKCS#8 export.
197///
198/// `pkcs8::PrivateKeyInfo::encrypt` picks scrypt at its recommended cost
199/// (2^15 rounds over 32 MiB) and AES-256-CBC, and it ignores the cipher the
200/// caller asked for. Node derives with PBKDF2-HMAC-SHA256 over 2048
201/// iterations and honours the cipher, so celld builds the parameters itself.
202/// The scrypt default also made an export cost seconds, which is why the two
203/// crypto suites were slow.
204///
205/// The cipher name arrives lower-cased from `node_crypto.js`, which is also
206/// where an unwritable cipher is refused. A name that reaches the fallback
207/// arm here is a bug on that side, not caller input.
208fn pbes2_parameters<'a>(
209 cipher: &str,
210 salt: &'a [u8],
211 iv: &'a [u8; 16],
212) -> Result<pkcs8::pkcs5::pbes2::Parameters<'a>> {
213 use pkcs8::pkcs5::pbes2::{EncryptionScheme, Parameters, Pbkdf2Params};
214
215 let encryption = match cipher {
216 "aes-128-cbc" => EncryptionScheme::Aes128Cbc { iv },
217 "aes-192-cbc" => EncryptionScheme::Aes192Cbc { iv },
218 "aes-256-cbc" => EncryptionScheme::Aes256Cbc { iv },
219 other => return Err(anyhow!("unsupported cipher {other}")),
220 };
221 let kdf = Pbkdf2Params::hmac_with_sha256(PBES2_ITERATIONS, salt)
222 .map_err(|_| anyhow!("invalid PBKDF2 parameters"))?;
223 Ok(Parameters {
224 kdf: kdf.into(),
225 encryption,
226 })
227}
228
229/// Identify an already-normalized PKCS#8 or SPKI blob and describe it. Node
230/// reports `asymmetricKeyType` and `asymmetricKeyDetails` from exactly this.
231fn describe_key(der: &[u8], private: bool) -> Result<ParsedKey> {
232 use rsa::pkcs8::der::Decode;
233 use rsa::traits::PublicKeyParts;
234
235 let (algorithm, curve) = if private {
236 let info = rsa::pkcs8::PrivateKeyInfo::from_der(der)
237 .map_err(|_| anyhow!("invalid PKCS#8 private key"))?;
238 (info.algorithm.oid, info.algorithm.parameters_oid().ok())
239 } else {
240 let info = rsa::pkcs8::SubjectPublicKeyInfoRef::from_der(der)
241 .map_err(|_| anyhow!("invalid SPKI public key"))?;
242 (info.algorithm.oid, info.algorithm.parameters_oid().ok())
243 };
244
245 match algorithm {
246 RSA_ENCRYPTION_OID => {
247 // Node reports the modulus length and exponent, so the key has to
248 // be parsed rather than merely recognized.
249 let (modulus, exponent) = if private {
250 use rsa::pkcs8::DecodePrivateKey;
251 let key = rsa::RsaPrivateKey::from_pkcs8_der(der)
252 .map_err(|_| anyhow!("invalid RSA private key"))?;
253 (key.n().bits(), key.e().clone())
254 } else {
255 use rsa::pkcs8::DecodePublicKey;
256 let key = rsa::RsaPublicKey::from_public_key_der(der)
257 .map_err(|_| anyhow!("invalid RSA public key"))?;
258 (key.n().bits(), key.e().clone())
259 };
260 Ok(ParsedKey {
261 kind: "rsa",
262 der: der.to_vec(),
263 details: serde_json::json!({
264 "modulusLength": modulus,
265 "publicExponent": exponent.to_string(),
266 }),
267 })
268 }
269 EC_PUBLIC_KEY_OID => {
270 // Resolve the curve from the key, so every later operation uses
271 // the matching implementation instead of assuming P-256.
272 let curve = curve.ok_or_else(|| anyhow!("EC key has no named curve"))?;
273 let named = EC_CURVES
274 .iter()
275 .find(|(oid, ..)| *oid == curve)
276 .ok_or_else(|| anyhow!("unsupported EC curve {curve}"))?
277 .1;
278 Ok(ParsedKey {
279 kind: "ec",
280 der: der.to_vec(),
281 details: serde_json::json!({ "namedCurve": named }),
282 })
283 }
284 ED25519_OID => Ok(ParsedKey {
285 kind: "ed25519",
286 der: der.to_vec(),
287 details: serde_json::json!({}),
288 }),
289 DSA_OID => {
290 use dsa::pkcs8::DecodePrivateKey;
291 use dsa::pkcs8::DecodePublicKey;
292 use dsa::Components;
293 let sizes = |components: &Components| (components.p().bits(), components.q().bits());
294 let (modulus, divisor) = if private {
295 let key = dsa::SigningKey::from_pkcs8_der(der)
296 .map_err(|_| anyhow!("invalid DSA private key"))?;
297 sizes(key.verifying_key().components())
298 } else {
299 let key = dsa::VerifyingKey::from_public_key_der(der)
300 .map_err(|_| anyhow!("invalid DSA public key"))?;
301 sizes(key.components())
302 };
303 Ok(ParsedKey {
304 kind: "dsa",
305 der: der.to_vec(),
306 details: serde_json::json!({
307 "modulusLength": modulus,
308 "divisorLength": divisor,
309 }),
310 })
311 }
312 X25519_OID => Ok(ParsedKey {
313 kind: "x25519",
314 der: der.to_vec(),
315 details: serde_json::json!({}),
316 }),
317 other => Err(anyhow!(
318 "unsupported key algorithm {other}; celld implements RSA, EC P-256 and Ed25519"
319 )),
320 }
321}
322
323/// PEM label -> the DER structure inside it. Node keys the whole import off
324/// this, because the label is the only self-description a PEM file carries.
325fn pem_structure(label: &str) -> Result<&'static str> {
326 Ok(match label {
327 "PRIVATE KEY" => "pkcs8",
328 "RSA PRIVATE KEY" => "pkcs1",
329 "EC PRIVATE KEY" => "sec1",
330 "DSA PRIVATE KEY" => "dsa-traditional",
331 "PUBLIC KEY" => "spki",
332 "RSA PUBLIC KEY" => "pkcs1-public",
333 // Handled before this point, where the passphrase is in scope.
334 "ENCRYPTED PRIVATE KEY" => "pkcs8",
335 other => return Err(anyhow!("unsupported PEM label \"{other}\"")),
336 })
337}
338
339/// Re-encode any accepted private structure as PKCS#8, and any public one as
340/// SPKI.
341fn normalize_key(der: &[u8], structure: &str) -> Result<(Vec<u8>, bool)> {
342 use rsa::pkcs8::EncodePrivateKey;
343 use rsa::pkcs8::EncodePublicKey;
344 match structure {
345 "pkcs8" => Ok((der.to_vec(), true)),
346 "spki" => Ok((der.to_vec(), false)),
347 "pkcs1" => {
348 use rsa::pkcs1::DecodeRsaPrivateKey;
349 let key = rsa::RsaPrivateKey::from_pkcs1_der(der)
350 .map_err(|_| anyhow!("invalid PKCS#1 RSA private key"))?;
351 Ok((key.to_pkcs8_der()?.as_bytes().to_vec(), true))
352 }
353 "pkcs1-public" => {
354 use rsa::pkcs1::DecodeRsaPublicKey;
355 let key = rsa::RsaPublicKey::from_pkcs1_der(der)
356 .map_err(|_| anyhow!("invalid PKCS#1 RSA public key"))?;
357 Ok((key.to_public_key_der()?.as_bytes().to_vec(), false))
358 }
359 // OpenSSL's traditional DSA key: a bare SEQUENCE of six INTEGERs
360 // with no algorithm identifier, so it has to be read field by field
361 // and rebuilt as PKCS#8. Same shape deno parses.
362 "dsa-traditional" => {
363 use dsa::pkcs8::der::asn1::UintRef;
364 use dsa::pkcs8::der::{Decode, Reader, SliceReader};
365 use dsa::pkcs8::EncodePrivateKey;
366 let mut reader =
367 SliceReader::new(der).map_err(|_| anyhow!("invalid DSA private key"))?;
368 let key = reader
369 .sequence(|seq| {
370 let _version = UintRef::decode(seq)?;
371 let mut field = || -> Result<rsa::BigUint, dsa::pkcs8::der::Error> {
372 Ok(rsa::BigUint::from_bytes_be(
373 UintRef::decode(seq)?.as_bytes(),
374 ))
375 };
376 let (p, q, g, y, x) = (field()?, field()?, field()?, field()?, field()?);
377 let bad = || dsa::pkcs8::der::Tag::Sequence.value_error();
378 let components =
379 dsa::Components::from_components(p, q, g).map_err(|_| bad())?;
380 let verifying =
381 dsa::VerifyingKey::from_components(components, y).map_err(|_| bad())?;
382 dsa::SigningKey::from_components(verifying, x).map_err(|_| bad())
383 })
384 .map_err(|_| anyhow!("invalid DSA private key"))?;
385 Ok((key.to_pkcs8_der()?.as_bytes().to_vec(), true))
386 }
387 "sec1" => {
388 // SEC1 names no algorithm, so P-256 is the only reading celld has.
389 let key = p256::SecretKey::from_sec1_der(der)
390 .map_err(|_| anyhow!("invalid SEC1 EC private key (celld implements P-256)"))?;
391 Ok((
392 p256::pkcs8::EncodePrivateKey::to_pkcs8_der(&key)?
393 .as_bytes()
394 .to_vec(),
395 true,
396 ))
397 }
398 other => Err(anyhow!("unsupported key structure \"{other}\"")),
399 }
400}
401
402/// Node does not trust the caller's `type` for DER input — it sniffs, so the
403/// same PKCS#1 blob imports whether the caller says `pkcs1`, `pkcs8` or
404/// `sec1`. `crypto-keys-test.js` asserts exactly that ("All three of these
405/// variations should work, despite the type being different"), so the stated
406/// structure is only a hint about which decoder to try first.
407fn normalize_key_sniffing(der: &[u8], stated: Option<&str>, want_private: bool) -> Result<Vec<u8>> {
408 // `pkcs8` is exact; every other hint falls back. The suite pins both
409 // halves: a PKCS#8 blob imports whether it is called pkcs1, pkcs8 or
410 // sec1, but a PKCS#1 blob called `pkcs8` must fail -- "just like with
411 // Node.js ... tho oddly sec1 is ok. Silly software."
412 let candidates: &[&str] = match (want_private, stated) {
413 (true, Some("pkcs8")) => &["pkcs8"],
414 (true, _) => &["pkcs8", "pkcs1", "sec1"],
415 (false, _) => &["spki", "pkcs1-public"],
416 };
417 let mut order: Vec<&str> = stated
418 .into_iter()
419 .filter(|s| candidates.contains(s))
420 .collect();
421 order.extend(candidates.iter().filter(|s| Some(**s) != stated));
422
423 let mut last = None;
424 for structure in order {
425 // A structure that decodes but yields the wrong visibility is not a
426 // match either, so validate all the way through identification.
427 if let Ok((der, is_private)) = normalize_key(der, structure) {
428 if is_private == want_private && describe_key(&der, is_private).is_ok() {
429 return Ok(der);
430 }
431 }
432 last = Some(structure);
433 }
434 let _ = last;
435 // Node's wording, which the suite matches on exactly.
436 Err(anyhow!("Failed to parse private key"))
437}
438
439/// A JWK becomes the same normalized DER, so JWK input costs nothing extra
440/// downstream.
441fn key_from_jwk(jwk: &serde_json::Value, want_private: bool) -> Result<Vec<u8>> {
442 use rsa::pkcs8::EncodePrivateKey;
443 use rsa::pkcs8::EncodePublicKey;
444 let kty = jwk
445 .get("kty")
446 .and_then(serde_json::Value::as_str)
447 .unwrap_or("");
448 let curve = jwk.get("crv").and_then(serde_json::Value::as_str);
449 // A curve-bearing kty with no `crv` is a malformed JWK, not an
450 // unsupported one, and Node distinguishes the two by message.
451 if matches!(kty, "EC" | "OKP") && curve.is_none() {
452 return Err(anyhow!("{kty} JWK missing crv parameter"));
453 }
454 match (kty, curve) {
455 ("RSA", _) => {
456 let n = rsa_jwk_uint(jwk, "n")?;
457 let e = rsa_jwk_uint(jwk, "e")?;
458 if want_private {
459 // The CRT primes are required: RSA private operations need
460 // them, and a JWK carrying only `d` cannot be completed here.
461 let d = rsa_jwk_uint(jwk, "d")?;
462 let p = rsa_jwk_uint(jwk, "p")?;
463 let q = rsa_jwk_uint(jwk, "q")?;
464 let mut key = rsa::RsaPrivateKey::from_components(n, e, d, vec![p, q])?;
465 key.precompute()?;
466 Ok(key.to_pkcs8_der()?.as_bytes().to_vec())
467 } else {
468 let key = rsa::RsaPublicKey::new(n, e)?;
469 Ok(key.to_public_key_der()?.as_bytes().to_vec())
470 }
471 }
472 ("EC", Some(crv)) => {
473 // x and y are checked even for a private key, and before d,
474 // because that is the order Node reports missing parameters in.
475 let x = jwk_bytes(jwk, "EC", "x")?;
476 let y = jwk_bytes(jwk, "EC", "y")?;
477 macro_rules! import {
478 ($c:ident) => {{
479 if want_private {
480 let d = jwk_bytes(jwk, "EC", "d")?;
481 let key = $c::SecretKey::from_slice(&d)
482 .map_err(|_| anyhow!("invalid {} JWK private scalar", crv))?;
483 // x and y are not decoration: a JWK whose public
484 // point does not match its scalar describes two
485 // different keys, and signing with it would produce
486 // signatures nobody can verify against the x/y the
487 // caller believes they imported.
488 use $c::elliptic_curve::sec1::ToEncodedPoint;
489 let point = key.public_key().to_encoded_point(false);
490 if point.x().map(|v| v.as_slice()) != Some(x.as_slice())
491 || point.y().map(|v| v.as_slice()) != Some(y.as_slice())
492 {
493 return Err(anyhow!(
494 "{} JWK private key is inconsistent with its public point",
495 crv
496 ));
497 }
498 $c::pkcs8::EncodePrivateKey::to_pkcs8_der(&key)?
499 .as_bytes()
500 .to_vec()
501 } else {
502 let mut sec1 = Vec::with_capacity(1 + x.len() + y.len());
503 sec1.push(0x04); // uncompressed point
504 sec1.extend_from_slice(&x);
505 sec1.extend_from_slice(&y);
506 let key = $c::PublicKey::from_sec1_bytes(&sec1)
507 .map_err(|_| anyhow!("invalid {} JWK public point", crv))?;
508 $c::pkcs8::EncodePublicKey::to_public_key_der(&key)?
509 .as_bytes()
510 .to_vec()
511 }
512 }};
513 }
514 Ok(ec_curve!(crv, import))
515 }
516 ("OKP", Some("X25519")) => {
517 // x25519-dalek has no DER codec, so the 32 raw bytes are wrapped
518 // by hand. Both structures are fixed-shape for this algorithm:
519 // PKCS#8 carries the scalar in an OCTET STRING inside an OCTET
520 // STRING, SPKI the public point as a BIT STRING.
521 let _ = jwk_bytes(jwk, "OKP", "x")?;
522 if want_private {
523 let d = jwk_bytes(jwk, "OKP", "d")?;
524 let seed: [u8; 32] = d
525 .as_slice()
526 .try_into()
527 .map_err(|_| anyhow!("X25519 JWK private key must be 32 bytes"))?;
528 Ok(x25519_pkcs8(&seed))
529 } else {
530 let x = jwk_bytes(jwk, "OKP", "x")?;
531 let point: [u8; 32] = x
532 .as_slice()
533 .try_into()
534 .map_err(|_| anyhow!("X25519 JWK public key must be 32 bytes"))?;
535 Ok(x25519_spki(&point))
536 }
537 }
538 ("OKP", Some("Ed25519")) => {
539 let _ = jwk_bytes(jwk, "OKP", "x")?;
540 if want_private {
541 let d = jwk_bytes(jwk, "OKP", "d")?;
542 let seed: [u8; 32] = d
543 .as_slice()
544 .try_into()
545 .map_err(|_| anyhow!("Ed25519 JWK private key must be 32 bytes"))?;
546 let key = ed25519_dalek::SigningKey::from_bytes(&seed);
547 use ed25519_dalek::pkcs8::EncodePrivateKey;
548 Ok(key.to_pkcs8_der()?.as_bytes().to_vec())
549 } else {
550 let x = jwk_bytes(jwk, "OKP", "x")?;
551 let point: [u8; 32] = x
552 .as_slice()
553 .try_into()
554 .map_err(|_| anyhow!("Ed25519 JWK public key must be 32 bytes"))?;
555 let key = ed25519_dalek::VerifyingKey::from_bytes(&point)
556 .map_err(|_| anyhow!("invalid Ed25519 JWK public key"))?;
557 use ed25519_dalek::pkcs8::EncodePublicKey;
558 Ok(key.to_public_key_der()?.as_bytes().to_vec())
559 }
560 }
561 _ => Err(anyhow!(
562 "JWK {} key import is not implemented for this key type",
563 if want_private { "private" } else { "public" }
564 )),
565 }
566}
567
568fn crypto_operation(operation: &str, args: &serde_json::Value) -> Result<serde_json::Value> {
569 match operation {
570 "hmac-sign" => {
571 use hmac::Mac;
572 let key = crypto_bytes(args, "key")?;
573 let data = crypto_bytes(args, "data")?;
574 let hash = args
575 .get("hash")
576 .and_then(|value| value.as_str())
577 .unwrap_or("SHA-256");
578 if !hash.eq_ignore_ascii_case("SHA-256") && !hash.eq_ignore_ascii_case("SHA256") {
579 return Err(anyhow!("unsupported HMAC hash"));
580 }
581 let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(&key)
582 .map_err(|_| anyhow!("invalid HMAC key"))?;
583 mac.update(&data);
584 Ok(serde_json::json!({ "bytes": mac.finalize().into_bytes().to_vec() }))
585 }
586 // ECDH. Web Crypto's deriveBits returns the raw shared secret -- the
587 // x coordinate of the shared point -- with no KDF applied. Its length
588 // is the curve's field size, which is why a null `length` is
589 // answerable at all.
590 "ecdh-derive" => {
591 let private = crypto_bytes(args, "private")?;
592 let public = crypto_bytes(args, "public")?;
593 let crv = ec_jwk_crv(&describe_key(&private, true)?)?;
594 if crv != ec_jwk_crv(&describe_key(&public, false)?)? {
595 return Err(anyhow!("ECDH keys are on different curves"));
596 }
597 macro_rules! derive {
598 ($c:ident) => {{
599 use $c::pkcs8::DecodePrivateKey;
600 use $c::pkcs8::DecodePublicKey;
601 let secret = $c::SecretKey::from_pkcs8_der(&private)
602 .map_err(|_| anyhow!("invalid ECDH private key"))?;
603 let point = $c::PublicKey::from_public_key_der(&public)
604 .map_err(|_| anyhow!("invalid ECDH public key"))?;
605 $c::elliptic_curve::ecdh::diffie_hellman(
606 secret.to_nonzero_scalar(),
607 point.as_affine(),
608 )
609 .raw_secret_bytes()
610 .to_vec()
611 }};
612 }
613 Ok(serde_json::json!({ "bytes": ec_curve!(crv, derive) }))
614 }
615 "ed25519-sign" => {
616 use ed25519_dalek::pkcs8::DecodePrivateKey;
617 use ed25519_dalek::Signer;
618 let key = crypto_bytes(args, "key")?;
619 let data = crypto_bytes(args, "data")?;
620 let key = ed25519_dalek::SigningKey::from_pkcs8_der(&key)
621 .map_err(|_| anyhow!("invalid Ed25519 PKCS#8 key"))?;
622 Ok(serde_json::json!({ "bytes": key.sign(&data).to_bytes().to_vec() }))
623 }
624 "p256-sign" => {
625 use p256::ecdsa::signature::Signer;
626 use p256::pkcs8::DecodePrivateKey;
627 let key = crypto_bytes(args, "key")?;
628 let data = crypto_bytes(args, "data")?;
629 let key = p256::ecdsa::SigningKey::from_pkcs8_der(&key)
630 .map_err(|_| anyhow!("invalid P-256 PKCS#8 key"))?;
631 let signature: p256::ecdsa::Signature = key.sign(&data);
632 Ok(serde_json::json!({ "bytes": signature.to_bytes().to_vec() }))
633 }
634 // JWT verification is the reason these exist: RS256 and ES256 are what
635 // token issuers sign with (denoland/celld#124). Both take an SPKI
636 // public key, matching `importKey("spki", ...)`.
637 // node:crypto's one-shot sign()/verify(). Web Crypto's ops above take
638 // raw r||s for ECDSA; Node defaults to DER, so these are separate
639 // entry points rather than flags on those.
640 "ed25519-verify" => {
641 use ed25519_dalek::pkcs8::DecodePublicKey;
642 use ed25519_dalek::Verifier;
643 let key = crypto_bytes(args, "key")?;
644 let data = crypto_bytes(args, "data")?;
645 let signature = crypto_bytes(args, "signature")?;
646 let key = ed25519_dalek::VerifyingKey::from_public_key_der(&key)
647 .map_err(|_| anyhow!("invalid Ed25519 SPKI key"))?;
648 let ok = ed25519_dalek::Signature::from_slice(&signature)
649 .map(|signature| key.verify(&data, &signature).is_ok())
650 .unwrap_or(false);
651 Ok(serde_json::json!({ "ok": ok }))
652 }
653 "rsa-pkcs1-sign" => {
654 use rsa::pkcs8::DecodePrivateKey;
655 use rsa::signature::{RandomizedSigner, SignatureEncoding};
656 let key = crypto_bytes(args, "key")?;
657 let data = crypto_bytes(args, "data")?;
658 let hash = args
659 .get("hash")
660 .and_then(serde_json::Value::as_str)
661 .unwrap_or("SHA-256");
662 let key = rsa::RsaPrivateKey::from_pkcs8_der(&key)
663 .map_err(|_| anyhow!("invalid RSA private key"))?;
664 macro_rules! sign {
665 ($hash:ty) => {
666 rsa::pkcs1v15::SigningKey::<$hash>::new(key)
667 // PKCS#1 v1.5 produces the same signature with or
668 // without randomness. The RNG blinds the private-key
669 // operation, so its timing does not expose the key.
670 .try_sign_with_rng(&mut rand::rngs::OsRng, &data)
671 .map_err(|_| anyhow!("RSA signing failed"))?
672 .to_vec()
673 };
674 }
675 let bytes = match hash {
676 "SHA-256" => sign!(sha2::Sha256),
677 "SHA-384" => sign!(sha2::Sha384),
678 "SHA-512" => sign!(sha2::Sha512),
679 other => return Err(anyhow!("unsupported RSA sign hash {other}")),
680 };
681 Ok(serde_json::json!({ "bytes": bytes }))
682 }
683 // Node's ECDSA signatures are DER by default (`dsaEncoding`), where
684 // Web Crypto's are raw r||s.
685 "ec-sign-der" => {
686 let key = crypto_bytes(args, "key")?;
687 let data = crypto_bytes(args, "data")?;
688 let hash = args
689 .get("hash")
690 .and_then(serde_json::Value::as_str)
691 .unwrap_or("SHA-256");
692 let digest = digest_bytes(hash, &data)?;
693 let parsed = describe_key(&key, true)?;
694 let crv = ec_jwk_crv(&parsed)?;
695 macro_rules! sign {
696 ($c:ident) => {{
697 use $c::ecdsa::signature::hazmat::PrehashSigner;
698 use $c::pkcs8::DecodePrivateKey;
699 let secret = $c::SecretKey::from_pkcs8_der(&key)
700 .map_err(|_| anyhow!("invalid {crv} PKCS#8 key"))?;
701 let key = $c::ecdsa::SigningKey::from_slice(secret.to_bytes().as_slice())
702 .map_err(|_| anyhow!("invalid {crv} signing key"))?;
703 let signature: $c::ecdsa::Signature = key
704 .sign_prehash(&digest)
705 .map_err(|_| anyhow!("could not sign with {crv}"))?;
706 signature.to_der().as_bytes().to_vec()
707 }};
708 }
709 Ok(serde_json::json!({ "bytes": ec_curve!(crv, sign) }))
710 }
711 "ec-verify-der" => {
712 let key = crypto_bytes(args, "key")?;
713 let data = crypto_bytes(args, "data")?;
714 let signature = crypto_bytes(args, "signature")?;
715 let hash = args
716 .get("hash")
717 .and_then(serde_json::Value::as_str)
718 .unwrap_or("SHA-256");
719 let digest = digest_bytes(hash, &data)?;
720 let parsed = describe_key(&key, false)?;
721 let crv = ec_jwk_crv(&parsed)?;
722 macro_rules! verify {
723 ($c:ident) => {{
724 use $c::ecdsa::signature::hazmat::PrehashVerifier;
725 use $c::elliptic_curve::sec1::ToEncodedPoint;
726 use $c::pkcs8::DecodePublicKey;
727 let public = $c::PublicKey::from_public_key_der(&key)
728 .map_err(|_| anyhow!("invalid {crv} SPKI key"))?;
729 let point = public.to_encoded_point(false);
730 let key = $c::ecdsa::VerifyingKey::from_sec1_bytes(point.as_bytes())
731 .map_err(|_| anyhow!("invalid {crv} verifying key"))?;
732 $c::ecdsa::DerSignature::try_from(signature.as_slice())
733 .ok()
734 .and_then(|signature| $c::ecdsa::Signature::try_from(signature).ok())
735 .map(|signature| key.verify_prehash(&digest, &signature).is_ok())
736 .unwrap_or(false)
737 }};
738 }
739 let ok = ec_curve!(crv, verify);
740 Ok(serde_json::json!({ "ok": ok }))
741 }
742 "p256-verify" => {
743 use p256::ecdsa::signature::Verifier;
744 use p256::pkcs8::DecodePublicKey;
745 let key = crypto_bytes(args, "key")?;
746 let data = crypto_bytes(args, "data")?;
747 let signature = crypto_bytes(args, "signature")?;
748 let key = p256::ecdsa::VerifyingKey::from_public_key_der(&key)
749 .map_err(|_| anyhow!("invalid P-256 SPKI key"))?;
750 // WebCrypto passes ECDSA signatures as raw r||s, not DER.
751 let ok = p256::ecdsa::Signature::from_slice(&signature)
752 .map(|signature| key.verify(&data, &signature).is_ok())
753 .unwrap_or(false);
754 Ok(serde_json::json!({ "ok": ok }))
755 }
756 "rsa-pkcs1-verify" => {
757 use rsa::pkcs8::DecodePublicKey;
758 use rsa::signature::Verifier;
759 let key = crypto_bytes(args, "key")?;
760 let data = crypto_bytes(args, "data")?;
761 let signature = crypto_bytes(args, "signature")?;
762 let hash = args
763 .get("hash")
764 .and_then(serde_json::Value::as_str)
765 .unwrap_or("SHA-256")
766 .to_string();
767 let key = rsa::RsaPublicKey::from_public_key_der(&key)
768 .map_err(|_| anyhow!("invalid RSA SPKI key"))?;
769 macro_rules! verify {
770 ($hash:ty) => {{
771 let key = rsa::pkcs1v15::VerifyingKey::<$hash>::new(key);
772 rsa::pkcs1v15::Signature::try_from(signature.as_slice())
773 .map(|signature| key.verify(&data, &signature).is_ok())
774 .unwrap_or(false)
775 }};
776 }
777 let ok = match hash.as_str() {
778 "SHA-256" => verify!(sha2::Sha256),
779 "SHA-384" => verify!(sha2::Sha384),
780 "SHA-512" => verify!(sha2::Sha512),
781 other => return Err(anyhow!("unsupported RSA verify hash {other}")),
782 };
783 Ok(serde_json::json!({ "ok": ok }))
784 }
785 // Web Crypto RSA-PSS. Signing takes the caller's salt length —
786 // the spec makes it an explicit parameter — and verification
787 // recovers the salt length from the signature, which accepts
788 // every salt the signer could legally have used.
789 "rsa-pss-sign" => {
790 use rsa::pkcs8::DecodePrivateKey;
791 use rsa::signature::RandomizedSigner;
792 use rsa::signature::SignatureEncoding;
793 let key = crypto_bytes(args, "key")?;
794 let data = crypto_bytes(args, "data")?;
795 let salt_len = args
796 .get("saltLength")
797 .and_then(serde_json::Value::as_u64)
798 .unwrap_or(0) as usize;
799 let hash = args
800 .get("hash")
801 .and_then(serde_json::Value::as_str)
802 .unwrap_or("SHA-256");
803 let key = rsa::RsaPrivateKey::from_pkcs8_der(&key)
804 .map_err(|_| anyhow!("invalid RSA private key"))?;
805 macro_rules! sign {
806 ($hash:ty) => {
807 rsa::pss::SigningKey::<$hash>::new_with_salt_len(key, salt_len)
808 .sign_with_rng(&mut rand::rngs::OsRng, &data)
809 .to_vec()
810 };
811 }
812 let bytes = match hash {
813 "SHA-256" => sign!(sha2::Sha256),
814 "SHA-384" => sign!(sha2::Sha384),
815 "SHA-512" => sign!(sha2::Sha512),
816 other => return Err(anyhow!("unsupported RSA sign hash {other}")),
817 };
818 Ok(serde_json::json!({ "bytes": bytes }))
819 }
820 "rsa-pss-verify" => {
821 use rsa::pkcs8::DecodePublicKey;
822 use rsa::signature::Verifier;
823 let key = crypto_bytes(args, "key")?;
824 let data = crypto_bytes(args, "data")?;
825 let signature = crypto_bytes(args, "signature")?;
826 let hash = args
827 .get("hash")
828 .and_then(serde_json::Value::as_str)
829 .unwrap_or("SHA-256")
830 .to_string();
831 let key = rsa::RsaPublicKey::from_public_key_der(&key)
832 .map_err(|_| anyhow!("invalid RSA SPKI key"))?;
833 macro_rules! verify {
834 ($hash:ty) => {{
835 let key = rsa::pss::VerifyingKey::<$hash>::new(key);
836 rsa::pss::Signature::try_from(signature.as_slice())
837 .map(|signature| key.verify(&data, &signature).is_ok())
838 .unwrap_or(false)
839 }};
840 }
841 let ok = match hash.as_str() {
842 "SHA-256" => verify!(sha2::Sha256),
843 "SHA-384" => verify!(sha2::Sha384),
844 "SHA-512" => verify!(sha2::Sha512),
845 other => return Err(anyhow!("unsupported RSA verify hash {other}")),
846 };
847 Ok(serde_json::json!({ "ok": ok }))
848 }
849 "rsa-oaep-encrypt" => {
850 use rsa::pkcs8::DecodePublicKey;
851 let key = crypto_bytes(args, "key")?;
852 let data = crypto_bytes(args, "data")?;
853 let label = crypto_bytes(args, "label")?;
854 let hash = args
855 .get("hash")
856 .and_then(serde_json::Value::as_str)
857 .unwrap_or("SHA-256");
858 let key = rsa::RsaPublicKey::from_public_key_der(&key)
859 .map_err(|_| anyhow!("invalid RSA public key"))?;
860 let bytes = key.encrypt(
861 &mut rand::rngs::OsRng,
862 rsa_oaep_padding(hash, label)?,
863 &data,
864 )?;
865 Ok(serde_json::json!({ "bytes": bytes }))
866 }
867 "rsa-oaep-decrypt" => {
868 use rsa::pkcs8::DecodePrivateKey;
869 let key = crypto_bytes(args, "key")?;
870 let data = crypto_bytes(args, "data")?;
871 let label = crypto_bytes(args, "label")?;
872 let hash = args
873 .get("hash")
874 .and_then(serde_json::Value::as_str)
875 .unwrap_or("SHA-256");
876 let key = rsa::RsaPrivateKey::from_pkcs8_der(&key)
877 .map_err(|_| anyhow!("invalid RSA private key"))?;
878 // The plain decrypt API omits RSA blinding. Use the randomized
879 // API so repeated attacker-controlled ciphertexts do not expose
880 // the private key through operation timing.
881 let bytes = key.decrypt_blinded(
882 &mut rand::rngs::OsRng,
883 rsa_oaep_padding(hash, label)?,
884 &data,
885 )?;
886 Ok(serde_json::json!({ "bytes": bytes }))
887 }
888 // `createPublicKey` / `createPrivateKey`. Accepts every input shape
889 // Node does — PEM, bare DER with a stated structure, or a JWK — and
890 // answers with one normalized DER plus what Node reports as
891 // `asymmetricKeyType` and `asymmetricKeyDetails`.
892 "asym-key-import" => {
893 let format = args
894 .get("format")
895 .and_then(serde_json::Value::as_str)
896 .unwrap_or("pem");
897 let want_private = args
898 .get("visibility")
899 .and_then(serde_json::Value::as_str)
900 .is_some_and(|visibility| visibility == "private");
901
902 let (der, is_private) = if format == "jwk" {
903 let jwk = args.get("key").ok_or_else(|| anyhow!("missing JWK"))?;
904 (key_from_jwk(jwk, want_private)?, want_private)
905 } else {
906 let key = crypto_bytes(args, "key")?;
907 let stated = args.get("type").and_then(serde_json::Value::as_str);
908 let passphrase = args
909 .get("passphrase")
910 .filter(|value| !value.is_null())
911 .map(|_| crypto_bytes(args, "passphrase"))
912 .transpose()?;
913 if format == "pem" {
914 let text = std::str::from_utf8(&key)
915 .map_err(|_| anyhow!("PEM key is not valid UTF-8"))?;
916 if text.contains("ENCRYPTED PRIVATE KEY") {
917 let passphrase = passphrase
918 .ok_or_else(|| anyhow!("Passphrase required for encrypted key"))?;
919 use pkcs8::DecodePrivateKey as _;
920 let document =
921 pkcs8::SecretDocument::from_pkcs8_encrypted_pem(text, &passphrase)
922 .map_err(|_| anyhow!("Failed to decrypt private key"))?;
923 (document.as_bytes().to_vec(), true)
924 } else {
925 let (label, document) = rsa::pkcs8::Document::from_pem(text)
926 .map_err(|_| anyhow!("invalid PEM key"))?;
927 normalize_key(document.as_bytes(), pem_structure(label)?)?
928 }
929 } else if let Ok(sealed) = pkcs8::EncryptedPrivateKeyInfo::try_from(key.as_slice())
930 {
931 // An encrypted PKCS#8 blob is its own structure, so it is
932 // recognized before the sniffer runs: the sniffer would
933 // read it as an unknown key and report a parse failure
934 // rather than a missing or wrong passphrase.
935 let passphrase = passphrase
936 .ok_or_else(|| anyhow!("Passphrase required for encrypted key"))?;
937 let document = sealed
938 .decrypt(&passphrase)
939 .map_err(|_| anyhow!("Failed to decrypt private key"))?;
940 (document.as_bytes().to_vec(), true)
941 } else {
942 (
943 normalize_key_sniffing(&key, stated, want_private)?,
944 want_private,
945 )
946 }
947 };
948
949 if is_private != want_private {
950 return Err(anyhow!(
951 "expected a {} key, got a {} key",
952 if want_private { "private" } else { "public" },
953 if is_private { "private" } else { "public" }
954 ));
955 }
956 let parsed = describe_key(&der, is_private)?;
957 Ok(serde_json::json!({
958 "keyType": parsed.kind,
959 "der": parsed.der,
960 "details": parsed.details,
961 }))
962 }
963 // `createPublicKey(privateKeyObject)`: derive the public half from an
964 // already-normalized PKCS#8 key, so the caller never re-parses.
965 "asym-key-public-from-private" => {
966 use rsa::pkcs8::EncodePublicKey;
967 let der = crypto_bytes(args, "der")?;
968 let parsed = describe_key(&der, true)?;
969 let public = match parsed.kind {
970 "rsa" => {
971 use rsa::pkcs8::DecodePrivateKey;
972 let key = rsa::RsaPrivateKey::from_pkcs8_der(&der)
973 .map_err(|_| anyhow!("invalid RSA private key"))?;
974 rsa::RsaPublicKey::from(&key)
975 .to_public_key_der()?
976 .as_bytes()
977 .to_vec()
978 }
979 "ec" => {
980 let crv = ec_jwk_crv(&parsed)?;
981 macro_rules! public_from_private {
982 ($c:ident) => {{
983 use $c::pkcs8::DecodePrivateKey;
984 let key = $c::SecretKey::from_pkcs8_der(&der)
985 .map_err(|_| anyhow!("invalid {crv} private key"))?;
986 key.public_key().to_public_key_der()?.as_bytes().to_vec()
987 }};
988 }
989 ec_curve!(crv, public_from_private)
990 }
991 "ed25519" => {
992 use ed25519_dalek::pkcs8::DecodePrivateKey;
993 use ed25519_dalek::pkcs8::EncodePublicKey;
994 let key = ed25519_dalek::SigningKey::from_pkcs8_der(&der)
995 .map_err(|_| anyhow!("invalid Ed25519 private key"))?;
996 key.verifying_key().to_public_key_der()?.as_bytes().to_vec()
997 }
998 "x25519" => {
999 let scalar: [u8; 32] = der[der.len() - 32..]
1000 .try_into()
1001 .expect("X25519 PKCS#8 ends with the 32-byte scalar");
1002 let secret = x25519_dalek::StaticSecret::from(scalar);
1003 x25519_spki(x25519_dalek::PublicKey::from(&secret).as_bytes())
1004 }
1005 other => return Err(anyhow!("cannot derive a public key for {other}")),
1006 };
1007 let parsed = describe_key(&public, false)?;
1008 Ok(serde_json::json!({
1009 "keyType": parsed.kind,
1010 "der": parsed.der,
1011 "details": parsed.details,
1012 }))
1013 }
1014 // `generateKeyPairSync`. Answers in the same normalized encodings as
1015 // import — PKCS#8 and SPKI — so the two paths share everything
1016 // downstream.
1017 "asym-key-generate" => {
1018 use ed25519_dalek::pkcs8::EncodePublicKey as _;
1019 use p256::pkcs8::EncodePrivateKey as _;
1020 let kind = args
1021 .get("type")
1022 .and_then(serde_json::Value::as_str)
1023 .ok_or_else(|| anyhow!("missing key type"))?;
1024 let mut rng = rand::rngs::OsRng;
1025 let (private, public) = match kind {
1026 "rsa" => {
1027 let bits = args
1028 .get("modulusLength")
1029 .and_then(serde_json::Value::as_u64)
1030 .ok_or_else(|| anyhow!("missing modulusLength"))?
1031 as usize;
1032 let mut key = rsa::RsaPrivateKey::new(&mut rng, bits)?;
1033 key.precompute()?;
1034 let public = rsa::RsaPublicKey::from(&key);
1035 (
1036 key.to_pkcs8_der()?.as_bytes().to_vec(),
1037 public.to_public_key_der()?.as_bytes().to_vec(),
1038 )
1039 }
1040 "ec" => {
1041 // The JS layer maps Node's curve aliases and rejects
1042 // anything not in EC_CURVES before reaching here.
1043 let crv = args
1044 .get("namedCurve")
1045 .and_then(serde_json::Value::as_str)
1046 .unwrap_or("P-256");
1047 macro_rules! generate {
1048 ($c:ident) => {{
1049 let key = $c::SecretKey::random(&mut rng);
1050 (
1051 $c::pkcs8::EncodePrivateKey::to_pkcs8_der(&key)?
1052 .as_bytes()
1053 .to_vec(),
1054 $c::pkcs8::EncodePublicKey::to_public_key_der(&key.public_key())?
1055 .as_bytes()
1056 .to_vec(),
1057 )
1058 }};
1059 }
1060 ec_curve!(crv, generate)
1061 }
1062 "ed25519" => {
1063 use ed25519_dalek::pkcs8::EncodePrivateKey as _;
1064 // No `generate` on this build of ed25519-dalek (its
1065 // `rand_core` feature is off); the seed is 32 random
1066 // bytes either way.
1067 let mut seed = [0u8; 32];
1068 rand::RngCore::fill_bytes(&mut rng, &mut seed);
1069 let key = ed25519_dalek::SigningKey::from_bytes(&seed);
1070 (
1071 key.to_pkcs8_der()?.as_bytes().to_vec(),
1072 key.verifying_key().to_public_key_der()?.as_bytes().to_vec(),
1073 )
1074 }
1075 "x25519" => {
1076 let secret = x25519_dalek::StaticSecret::random_from_rng(rng);
1077 let public = x25519_dalek::PublicKey::from(&secret);
1078 (
1079 x25519_pkcs8(&secret.to_bytes()),
1080 x25519_spki(public.as_bytes()),
1081 )
1082 }
1083 other => return Err(anyhow!("cannot generate a {other} key pair")),
1084 };
1085 let described = describe_key(&private, true)?;
1086 Ok(serde_json::json!({
1087 "keyType": described.kind,
1088 "privateDer": private,
1089 "publicDer": public,
1090 "details": described.details,
1091 }))
1092 }
1093 // Re-encode a normalized key into one of Node's export structures.
1094 // Import converts every structure *to* PKCS#8/SPKI; this is the
1095 // inverse, and `generateKeyPairSync`'s encoding options need it.
1096 "asym-key-reencode" => {
1097 use rsa::pkcs1::EncodeRsaPrivateKey as _;
1098 use rsa::pkcs1::EncodeRsaPublicKey as _;
1099 let der = crypto_bytes(args, "der")?;
1100 let private = args
1101 .get("visibility")
1102 .and_then(serde_json::Value::as_str)
1103 .is_some_and(|visibility| visibility == "private");
1104 let structure = args
1105 .get("type")
1106 .and_then(serde_json::Value::as_str)
1107 .unwrap_or(if private { "pkcs8" } else { "spki" });
1108 let described = describe_key(&der, private)?;
1109 // A passphrase turns the export into encrypted PKCS#8, whatever
1110 // structure was asked for -- that is the only structure the
1111 // encryption wrapper defines.
1112 if let Some(passphrase) = args
1113 .get("passphrase")
1114 .filter(|value| !value.is_null())
1115 .map(|_| crypto_bytes(args, "passphrase"))
1116 .transpose()?
1117 {
1118 if !private {
1119 return Err(anyhow!("only a private key can be encrypted"));
1120 }
1121 let info = pkcs8::PrivateKeyInfo::try_from(der.as_slice())
1122 .map_err(|_| anyhow!("invalid PKCS#8 private key"))?;
1123 let cipher = args
1124 .get("cipher")
1125 .and_then(serde_json::Value::as_str)
1126 .ok_or_else(|| anyhow!("an encrypted export needs a cipher"))?;
1127 use rand::RngCore as _;
1128 let mut salt = [0u8; PBES2_SALT_LEN];
1129 let mut iv = [0u8; 16];
1130 rand::rngs::OsRng.fill_bytes(&mut salt);
1131 rand::rngs::OsRng.fill_bytes(&mut iv);
1132 let params = pbes2_parameters(cipher, &salt, &iv)?;
1133 let document = info
1134 .encrypt_with_params(params, &passphrase)
1135 .map_err(|_| anyhow!("could not encrypt the private key"))?;
1136 let pem = args
1137 .get("format")
1138 .and_then(serde_json::Value::as_str)
1139 .is_some_and(|format| format == "pem");
1140 return Ok(if pem {
1141 serde_json::json!({
1142 "pem": pem_wrap("ENCRYPTED PRIVATE KEY", document.as_bytes()),
1143 })
1144 } else {
1145 serde_json::json!({ "der": document.as_bytes() })
1146 });
1147 }
1148 let (label, bytes) = match (structure, described.kind) {
1149 ("pkcs8", _) => ("PRIVATE KEY", der.clone()),
1150 ("spki", _) => ("PUBLIC KEY", der.clone()),
1151 ("pkcs1", "rsa") if private => {
1152 use rsa::pkcs8::DecodePrivateKey;
1153 let key = rsa::RsaPrivateKey::from_pkcs8_der(&der)?;
1154 ("RSA PRIVATE KEY", key.to_pkcs1_der()?.as_bytes().to_vec())
1155 }
1156 ("pkcs1", "rsa") => {
1157 use rsa::pkcs8::DecodePublicKey;
1158 let key = rsa::RsaPublicKey::from_public_key_der(&der)?;
1159 ("RSA PUBLIC KEY", key.to_pkcs1_der()?.as_bytes().to_vec())
1160 }
1161 ("sec1", "ec") if private => {
1162 use p256::elliptic_curve::sec1::ToEncodedPoint;
1163 use p256::pkcs8::DecodePrivateKey;
1164 let key = p256::SecretKey::from_pkcs8_der(&der)?;
1165 let _ = key.public_key().to_encoded_point(false);
1166 ("EC PRIVATE KEY", key.to_sec1_der()?.to_vec())
1167 }
1168 (structure, kind) => {
1169 return Err(anyhow!("cannot export a {kind} key as {structure}"))
1170 }
1171 };
1172 let pem = args
1173 .get("format")
1174 .and_then(serde_json::Value::as_str)
1175 .is_some_and(|format| format == "pem");
1176 if pem {
1177 Ok(serde_json::json!({ "pem": pem_wrap(label, &bytes) }))
1178 } else {
1179 Ok(serde_json::json!({ "der": bytes }))
1180 }
1181 }
1182 // Export a normalized key back out. `jwk` is the shape `toCryptoKey`
1183 // and Node's `export({format:"jwk"})` both want.
1184 "asym-key-export" => {
1185 let der = crypto_bytes(args, "der")?;
1186 let private = args
1187 .get("visibility")
1188 .and_then(serde_json::Value::as_str)
1189 .is_some_and(|visibility| visibility == "private");
1190 let parsed = describe_key(&der, private)?;
1191 let jwk = match (parsed.kind, private) {
1192 ("rsa", false) => {
1193 use rsa::pkcs8::DecodePublicKey;
1194 use rsa::traits::PublicKeyParts;
1195 let key = rsa::RsaPublicKey::from_public_key_der(&der)?;
1196 serde_json::json!({
1197 "kty": "RSA",
1198 "n": rsa_jwk_encode(key.n()),
1199 "e": rsa_jwk_encode(key.e()),
1200 })
1201 }
1202 ("rsa", true) => {
1203 use rsa::pkcs8::DecodePrivateKey;
1204 use rsa::traits::{PrivateKeyParts, PublicKeyParts};
1205 let key = rsa::RsaPrivateKey::from_pkcs8_der(&der)?;
1206 // The CRT parameters are part of the JWK, not an
1207 // optimization detail: Node emits all of dp, dq and qi.
1208 let missing = || anyhow!("RSA key has no CRT parameters");
1209 serde_json::json!({
1210 "kty": "RSA",
1211 "n": rsa_jwk_encode(key.n()),
1212 "e": rsa_jwk_encode(key.e()),
1213 "d": rsa_jwk_encode(key.d()),
1214 "p": rsa_jwk_encode(&key.primes()[0]),
1215 "q": rsa_jwk_encode(&key.primes()[1]),
1216 "dp": rsa_jwk_encode(key.dp().ok_or_else(missing)?),
1217 "dq": rsa_jwk_encode(key.dq().ok_or_else(missing)?),
1218 "qi": rsa_jwk_encode(&key.crt_coefficient().ok_or_else(missing)?),
1219 })
1220 }
1221 ("ec", false) => {
1222 let crv = ec_jwk_crv(&parsed)?;
1223 macro_rules! export {
1224 ($c:ident) => {{
1225 use $c::elliptic_curve::sec1::ToEncodedPoint;
1226 use $c::pkcs8::DecodePublicKey;
1227 let key = $c::PublicKey::from_public_key_der(&der)?;
1228 let point = key.to_encoded_point(false);
1229 serde_json::json!({
1230 "kty": "EC",
1231 "crv": crv,
1232 "x": base64url(point.x().ok_or_else(|| anyhow!("no x"))?),
1233 "y": base64url(point.y().ok_or_else(|| anyhow!("no y"))?),
1234 })
1235 }};
1236 }
1237 ec_curve!(crv, export)
1238 }
1239 ("ec", true) => {
1240 let crv = ec_jwk_crv(&parsed)?;
1241 macro_rules! export {
1242 ($c:ident) => {{
1243 use $c::elliptic_curve::sec1::ToEncodedPoint;
1244 use $c::pkcs8::DecodePrivateKey;
1245 let key = $c::SecretKey::from_pkcs8_der(&der)?;
1246 let point = key.public_key().to_encoded_point(false);
1247 serde_json::json!({
1248 "kty": "EC",
1249 "crv": crv,
1250 "x": base64url(point.x().ok_or_else(|| anyhow!("no x"))?),
1251 "y": base64url(point.y().ok_or_else(|| anyhow!("no y"))?),
1252 "d": base64url(&key.to_bytes()),
1253 })
1254 }};
1255 }
1256 ec_curve!(crv, export)
1257 }
1258 ("x25519", _) => {
1259 let raw = &der[der.len() - 32..];
1260 let mut jwk = serde_json::json!({ "kty": "OKP", "crv": "X25519" });
1261 if private {
1262 let scalar: [u8; 32] = raw.try_into().unwrap();
1263 let secret = x25519_dalek::StaticSecret::from(scalar);
1264 jwk["x"] = serde_json::Value::String(base64url(
1265 x25519_dalek::PublicKey::from(&secret).as_bytes(),
1266 ));
1267 jwk["d"] = serde_json::Value::String(base64url(raw));
1268 } else {
1269 jwk["x"] = serde_json::Value::String(base64url(raw));
1270 }
1271 jwk
1272 }
1273 ("ed25519", false) => {
1274 use ed25519_dalek::pkcs8::DecodePublicKey;
1275 let key = ed25519_dalek::VerifyingKey::from_public_key_der(&der)
1276 .map_err(|_| anyhow!("invalid Ed25519 public key"))?;
1277 serde_json::json!({
1278 "alg": "EdDSA",
1279 "kty": "OKP",
1280 "crv": "Ed25519",
1281 "x": base64url(key.as_bytes()),
1282 })
1283 }
1284 ("ed25519", true) => {
1285 use ed25519_dalek::pkcs8::DecodePrivateKey;
1286 let key = ed25519_dalek::SigningKey::from_pkcs8_der(&der)
1287 .map_err(|_| anyhow!("invalid Ed25519 private key"))?;
1288 serde_json::json!({
1289 "alg": "EdDSA",
1290 "kty": "OKP",
1291 "crv": "Ed25519",
1292 "x": base64url(key.verifying_key().as_bytes()),
1293 "d": base64url(&key.to_bytes()),
1294 })
1295 }
1296 ("dsa", _) => return Err(anyhow!("Key type is invalid for JWK export")),
1297 (other, _) => return Err(anyhow!("cannot export {other} as JWK")),
1298 };
1299 Ok(serde_json::json!({
1300 "keyType": parsed.kind,
1301 "jwk": jwk,
1302 "details": parsed.details,
1303 }))
1304 }
1305 _ => Err(anyhow!("unsupported crypto operation")),
1306 }
1307}
1308
1309pub(super) fn op_crypto_operation(
1310 scope: &mut v8::PinScope,
1311 args: v8::FunctionCallbackArguments,
1312 mut rv: v8::ReturnValue<v8::Value>,
1313) {
1314 let operation = args.get(0).to_rust_string_lossy(scope);
1315 // An undecodable argument used to become `Value::Null`, and the operation
1316 // then ran against it. Every field lookup missed, so the caller was told
1317 // its key bytes were invalid when the real fault was the argument object
1318 // itself. Name the argument instead.
1319 let input: serde_json::Value =
1320 match serde_json::from_str(&args.get(1).to_rust_string_lossy(scope)) {
1321 Ok(input) => input,
1322 Err(error) => {
1323 return loader_throw(
1324 scope,
1325 &format!("crypto: the argument object is not JSON: {error}"),
1326 )
1327 }
1328 };
1329 match crypto_operation(&operation, &input) {
1330 Ok(value) => {
1331 let json = value.to_string();
1332 rv.set(v8::String::new(scope, &json).unwrap().into());
1333 }
1334 Err(error) => {
1335 let message = v8::String::new(scope, &format!("crypto: {error}")).unwrap();
1336 let exception = v8::Exception::error(scope, message);
1337 scope.throw_exception(exception);
1338 }
1339 }
1340}
1341
1342/// Fill an existing integer typed array in-place. JS performs the WebCrypto
1343/// type and 65,536-byte quota checks before entering this host op.
1344pub(super) fn op_webcrypto_random(
1345 scope: &mut v8::PinScope,
1346 args: v8::FunctionCallbackArguments,
1347 _rv: v8::ReturnValue<v8::Value>,
1348) {
1349 let Ok(view) = v8::Local::<v8::ArrayBufferView>::try_from(args.get(0)) else {
1350 return;
1351 };
1352 let Some(buffer) = view.buffer(scope) else {
1353 return;
1354 };
1355 let store = buffer.get_backing_store();
1356 let offset = view.byte_offset();
1357 let len = view.byte_length();
1358 let bytes = unsafe {
1359 std::slice::from_raw_parts_mut(store[offset..offset + len].as_ptr() as *mut u8, len)
1360 };
1361 if getrandom::fill(bytes).is_err() {
1362 let message = v8::String::new(scope, "secure random generation failed").unwrap();
1363 let exception = v8::Exception::error(scope, message);
1364 scope.throw_exception(exception);
1365 }
1366}
1367
1368// `crc::Crc::new` builds a 256-entry lookup table by value — 1 KiB for a
1369// `Crc<u32>`, 2 KiB for a `Crc<u64>`. Constructed inside `op_webcrypto_digest`,
1370// that table is rebuilt for every chunk an S3-uploading Worker checksums
1371// through `DigestStream`. `Crc::new` is a `const fn`, so a `static` initializer
1372// is a const context and the table is built at compile time instead. A
1373// `LazyLock` would also hoist the build out of the call, but it adds an atomic
1374// guard check to every use that a plain `static` does not need.
1375static CRC32: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
1376static CRC32C: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISCSI);
1377static CRC64NVME: crc::Crc<u64> = crc::Crc::<u64>::new(&crc::CRC_64_NVME);
1378
1379/// WebCrypto digest: (algorithm, ArrayBufferView) -> Uint8Array.
1380pub(super) fn op_webcrypto_digest(
1381 scope: &mut v8::PinScope,
1382 args: v8::FunctionCallbackArguments,
1383 rv: v8::ReturnValue<v8::Value>,
1384) {
1385 use sha2::Digest;
1386 let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
1387 let Some(bytes) = view_bytes(args.get(1)) else {
1388 return;
1389 };
1390 let digest = match algorithm.as_str() {
1391 "MD5" => md5::Md5::digest(&bytes).to_vec(),
1392 // Not digests, but DigestStream accepts them: the AWS SDKs and S3
1393 // checksum with these, so a Worker computing an upload checksum
1394 // needs them. Big-endian, as the checksum headers carry them.
1395 "CRC32" => CRC32.checksum(&bytes).to_be_bytes().to_vec(),
1396 "CRC32C" => CRC32C.checksum(&bytes).to_be_bytes().to_vec(),
1397 "CRC64NVME" => CRC64NVME.checksum(&bytes).to_be_bytes().to_vec(),
1398 "SHA-1" => sha1::Sha1::digest(&bytes).to_vec(),
1399 "SHA-224" => sha2::Sha224::digest(&bytes).to_vec(),
1400 "SHA-256" => sha2::Sha256::digest(&bytes).to_vec(),
1401 "SHA-384" => sha2::Sha384::digest(&bytes).to_vec(),
1402 "SHA-512" => sha2::Sha512::digest(&bytes).to_vec(),
1403 _ => return,
1404 };
1405 webcrypto_return_bytes(scope, rv, &digest);
1406}
1407
1408// Signing and verification must accept the same HMAC hashes. Separate match
1409// tables let MD5 and SHA-224 reach signing while verification returned no JS
1410// value, so keep the set in one dispatcher and supply only the operation.
1411macro_rules! dispatch_hmac_digest {
1412 ($name:expr, $operation:ident) => {
1413 match $name {
1414 "MD5" => $operation!(md5::Md5),
1415 "SHA-1" => $operation!(sha1::Sha1),
1416 "SHA-224" => $operation!(sha2::Sha224),
1417 "SHA-256" => $operation!(sha2::Sha256),
1418 "SHA-384" => $operation!(sha2::Sha384),
1419 "SHA-512" => $operation!(sha2::Sha512),
1420 _ => return,
1421 }
1422 };
1423}
1424
1425pub(super) fn op_webcrypto_hmac_sign(
1426 scope: &mut v8::PinScope,
1427 args: v8::FunctionCallbackArguments,
1428 rv: v8::ReturnValue<v8::Value>,
1429) {
1430 use hmac::Mac;
1431 let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
1432 let Some(key) = view_bytes(args.get(1)) else {
1433 return;
1434 };
1435 let Some(data) = view_bytes(args.get(2)) else {
1436 return;
1437 };
1438 macro_rules! sign {
1439 ($digest:ty) => {{
1440 let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
1441 return;
1442 };
1443 mac.update(&data);
1444 mac.finalize().into_bytes().to_vec()
1445 }};
1446 }
1447 let signature = dispatch_hmac_digest!(algorithm.as_str(), sign);
1448 webcrypto_return_bytes(scope, rv, &signature);
1449}
1450
1451/// The digest bound `hmac::Hmac` carries: a digest whose core exposes the
1452/// eager, block-level API. Naming it once keeps the two KDF signatures below
1453/// readable, because `pbkdf2::pbkdf2_hmac` and `hkdf::Hkdf` both spell out the
1454/// same eight lines. Every digest `dispatch_digest!` routes — MD5, SHA-1 and
1455/// the four SHA-2 sizes — satisfies it, and a digest that did not would fail
1456/// to compile at the macro rather than fall back to something slower.
1457///
1458/// `hmac::SimpleHmac` needs only `Digest + BlockSizeUser` and would let this
1459/// bound go away, but it drives the digest through the generic `Digest`
1460/// wrapper instead of the core, which is why it is the slower of the two.
1461/// `op_webcrypto_hmac_sign` and `op_webcrypto_hmac_verify` in this file
1462/// already use `Hmac`.
1463///
1464/// A bare `trait EagerDigest: CoreProxy where Self::Core: ...` does not work:
1465/// a where-clause on a trait definition constrains implementors but is not
1466/// elaborated for callers, so `D: EagerDigest` alone would not discharge the
1467/// bound at the `pbkdf2_hmac` and `Hkdf` call sites. Carrying the two KDF
1468/// entry points as trait methods discharges it inside the impl instead, which
1469/// is the only reason this is a trait with methods rather than an alias.
1470trait EagerDigest {
1471 fn pbkdf2_into(password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]);
1472
1473 /// `None` only when `out` is longer than the 255×hashLen of RFC 5869.
1474 fn hkdf_into(ikm: &[u8], salt: &[u8], info: &[u8], out: &mut [u8]) -> Option<()>;
1475}
1476
1477impl<D> EagerDigest for D
1478where
1479 D: hmac::digest::core_api::CoreProxy + hmac::digest::OutputSizeUser,
1480 D::Core: hmac::digest::HashMarker
1481 + hmac::digest::core_api::UpdateCore
1482 + hmac::digest::core_api::FixedOutputCore
1483 + hmac::digest::core_api::BufferKindUser<BufferKind = hmac::digest::block_buffer::Eager>
1484 + Default
1485 + Clone
1486 + Sync,
1487 <D::Core as hmac::digest::core_api::BlockSizeUser>::BlockSize:
1488 hmac::digest::typenum::IsLess<hmac::digest::typenum::U256>,
1489 hmac::digest::typenum::Le<
1490 <D::Core as hmac::digest::core_api::BlockSizeUser>::BlockSize,
1491 hmac::digest::typenum::U256,
1492 >: hmac::digest::typenum::NonZero,
1493{
1494 fn pbkdf2_into(password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) {
1495 pbkdf2::pbkdf2_hmac::<D>(password, salt, iterations, out);
1496 }
1497
1498 fn hkdf_into(ikm: &[u8], salt: &[u8], info: &[u8], out: &mut [u8]) -> Option<()> {
1499 hkdf::Hkdf::<D>::new(Some(salt), ikm).expand(info, out).ok()
1500 }
1501}
1502
1503/// PBKDF2 (RFC 2898) for node:crypto, over the `pbkdf2` crate.
1504///
1505/// This was a hand-rolled loop, justified in its own comment as avoiding an
1506/// extra dependency. That justification was false: `pbkdf2` already reaches
1507/// this build through `pkcs5`, which this file uses for encrypted PKCS#8, so
1508/// the crate was compiled either way and only the `Cargo.toml` line was
1509/// missing. The loop re-derived the HMAC key schedule from the password and
1510/// allocated a `Vec` on every one of the 100,000-plus iterations a real
1511/// caller asks for; the crate primes one HMAC and clones the primed state per
1512/// iteration, which is about twice as fast.
1513fn pbkdf2_kdf<D: EagerDigest>(
1514 password: &[u8],
1515 salt: &[u8],
1516 iterations: u32,
1517 keylen: usize,
1518) -> Vec<u8> {
1519 let mut out = vec![0u8; keylen];
1520 D::pbkdf2_into(password, salt, iterations, &mut out);
1521 out
1522}
1523
1524/// HKDF (RFC 5869) for node:crypto, over the `hkdf` crate, which reaches this
1525/// build through `elliptic-curve` for the same reason.
1526///
1527/// `None` means the caller asked for more than the 255×hashLen RFC 5869
1528/// defines. The hand-rolled version counted output blocks in a `u8` starting
1529/// at 1 and trusted a comment saying the JS layer capped the length. The cap
1530/// is real — `getHkdf` in `node_crypto.js` throws a `RangeError` above
1531/// 255×hashLen — but it admits exactly 255×hashLen, and the old loop
1532/// incremented the counter once more after emitting block 255. So an ordinary
1533/// `hkdfSync(hash, ikm, salt, info, 255 * hashLen)` overflowed the counter: a
1534/// panic under `debug-assertions`, and a silent wrap without them. Returning
1535/// the length check from the KDF instead of asserting it in a doc comment
1536/// keeps the ops correct whatever JS does, which matters because the ops are
1537/// own properties of the user's `globalThis` and only non-enumerable.
1538fn hkdf_kdf<D: EagerDigest>(
1539 ikm: &[u8],
1540 salt: &[u8],
1541 info: &[u8],
1542 length: usize,
1543) -> Option<Vec<u8>> {
1544 let mut out = vec![0u8; length];
1545 D::hkdf_into(ikm, salt, info, &mut out)?;
1546 Some(out)
1547}
1548
1549/// Routes a digest name to a KDF instantiated over that digest. `None` is an
1550/// unknown name, which leaves the calling op's return value unset. This list
1551/// must stay equal to `getHashes()` in `node_crypto.js`: that function is
1552/// what the JS layer validates a caller's digest name against, so a name it
1553/// advertises but this macro omits becomes an `undefined` return.
1554macro_rules! dispatch_digest {
1555 ($name:expr, $fn:ident, ($($arg:expr),*)) => {
1556 match $name {
1557 "MD5" => Some($fn::<md5::Md5>($($arg),*)),
1558 "SHA-1" => Some($fn::<sha1::Sha1>($($arg),*)),
1559 "SHA-224" => Some($fn::<sha2::Sha224>($($arg),*)),
1560 "SHA-256" => Some($fn::<sha2::Sha256>($($arg),*)),
1561 "SHA-384" => Some($fn::<sha2::Sha384>($($arg),*)),
1562 "SHA-512" => Some($fn::<sha2::Sha512>($($arg),*)),
1563 _ => None,
1564 }
1565 };
1566}
1567
1568/// `$$pbkdf2(algorithm, password, salt, iterations, keylen)` -> Uint8Array
1569pub(super) fn op_node_pbkdf2(
1570 scope: &mut v8::PinScope,
1571 args: v8::FunctionCallbackArguments,
1572 rv: v8::ReturnValue<v8::Value>,
1573) {
1574 let algorithm = args.get(0).to_rust_string_lossy(scope);
1575 let Some(password) = view_bytes(args.get(1)) else {
1576 return;
1577 };
1578 let Some(salt) = view_bytes(args.get(2)) else {
1579 return;
1580 };
1581 let iterations = args.get(3).uint32_value(scope).unwrap_or(0).max(1);
1582 let keylen = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
1583 let out = dispatch_digest!(
1584 algorithm.as_str(),
1585 pbkdf2_kdf,
1586 (&password, &salt, iterations, keylen)
1587 );
1588 if let Some(out) = out {
1589 webcrypto_return_bytes(scope, rv, &out);
1590 }
1591}
1592
1593/// `$$hkdf(algorithm, ikm, salt, info, length)` -> Uint8Array
1594pub(super) fn op_node_hkdf(
1595 scope: &mut v8::PinScope,
1596 args: v8::FunctionCallbackArguments,
1597 rv: v8::ReturnValue<v8::Value>,
1598) {
1599 let algorithm = args.get(0).to_rust_string_lossy(scope);
1600 let Some(ikm) = view_bytes(args.get(1)) else {
1601 return;
1602 };
1603 let Some(salt) = view_bytes(args.get(2)) else {
1604 return;
1605 };
1606 let Some(info) = view_bytes(args.get(3)) else {
1607 return;
1608 };
1609 let length = args.get(4).uint32_value(scope).unwrap_or(0) as usize;
1610 // The outer `Option` is an unknown digest, the inner one is a length above
1611 // 255xhashLen. Both leave the return value unset, which is what every
1612 // other reject in these ops does.
1613 let out = dispatch_digest!(algorithm.as_str(), hkdf_kdf, (&ikm, &salt, &info, length));
1614 if let Some(Some(out)) = out {
1615 webcrypto_return_bytes(scope, rv, &out);
1616 }
1617}
1618
1619/// Constant-time equality for equal-length byte views. The JS surfaces own
1620/// their distinct argument and length errors; one native primitive owns the
1621/// security property both APIs promise.
1622pub(super) fn op_timing_safe_equal(
1623 scope: &mut v8::PinScope,
1624 args: v8::FunctionCallbackArguments,
1625 mut rv: v8::ReturnValue<v8::Value>,
1626) {
1627 use subtle::ConstantTimeEq;
1628 let (Some(left), Some(right)) = (view_bytes(args.get(0)), view_bytes(args.get(1))) else {
1629 return;
1630 };
1631 rv.set(v8::Boolean::new(scope, bool::from(left.ct_eq(&right))).into());
1632}
1633
1634pub(super) fn op_webcrypto_hmac_verify(
1635 scope: &mut v8::PinScope,
1636 args: v8::FunctionCallbackArguments,
1637 mut rv: v8::ReturnValue<v8::Value>,
1638) {
1639 use hmac::Mac;
1640 let algorithm = args.get(0).to_rust_string_lossy(scope).to_ascii_uppercase();
1641 let Some(key) = view_bytes(args.get(1)) else {
1642 return;
1643 };
1644 let Some(signature) = view_bytes(args.get(2)) else {
1645 return;
1646 };
1647 let Some(data) = view_bytes(args.get(3)) else {
1648 return;
1649 };
1650 macro_rules! verify {
1651 ($digest:ty) => {{
1652 let Ok(mut mac) = <hmac::Hmac<$digest> as hmac::Mac>::new_from_slice(&key) else {
1653 return;
1654 };
1655 mac.update(&data);
1656 mac.verify_slice(&signature).is_ok()
1657 }};
1658 }
1659 let valid = dispatch_hmac_digest!(algorithm.as_str(), verify);
1660 rv.set(v8::Boolean::new(scope, valid).into());
1661}
1662
1663/// AES-GCM for the Web Crypto ops. The key, IV, and tag sizes are instantiated
1664/// explicitly because the crate fixes all three in the type.
1665///
1666/// Web Crypto permits any IV length; 96 bits is the recommendation, not the
1667/// rule, so 128-bit IVs are accepted too. For anything but 96 bits the crate
1668/// derives J0 by GHASHing the IV, per NIST SP 800-38D. An empty IV is
1669/// rejected in the JS layer, by name, before reaching here.
1670fn webcrypto_aes_gcm(
1671 key: &[u8],
1672 iv: &[u8],
1673 additional_data: &[u8],
1674 data: &[u8],
1675 tag_size: usize,
1676 encrypting: bool,
1677) -> Option<Vec<u8>> {
1678 use aes_gcm::aead::consts::{U12, U13, U14, U15, U16};
1679 use aes_gcm::aead::{Aead, KeyInit, Payload};
1680 macro_rules! run {
1681 ($aes:ty, $nonce_size:ty, $tag_size:ty) => {{
1682 type Gcm = aes_gcm::AesGcm<$aes, $nonce_size, $tag_size>;
1683 let cipher = <Gcm as KeyInit>::new_from_slice(key).ok()?;
1684 let nonce = aes_gcm::Nonce::<$nonce_size>::from_slice(iv);
1685 let payload = Payload {
1686 msg: data,
1687 aad: additional_data,
1688 };
1689 if encrypting {
1690 cipher.encrypt(nonce, payload)
1691 } else {
1692 cipher.decrypt(nonce, payload)
1693 }
1694 .ok()?
1695 }};
1696 }
1697 macro_rules! by_tag {
1698 ($aes:ty, $nonce_size:ty) => {
1699 match tag_size {
1700 12 => run!($aes, $nonce_size, U12),
1701 13 => run!($aes, $nonce_size, U13),
1702 14 => run!($aes, $nonce_size, U14),
1703 15 => run!($aes, $nonce_size, U15),
1704 16 => run!($aes, $nonce_size, U16),
1705 _ => return None,
1706 }
1707 };
1708 }
1709 macro_rules! by_iv {
1710 ($aes:ty) => {
1711 match iv.len() {
1712 12 => by_tag!($aes, U12),
1713 16 => by_tag!($aes, U16),
1714 _ => return None,
1715 }
1716 };
1717 }
1718 Some(match key.len() {
1719 16 => by_iv!(aes::Aes128),
1720 32 => by_iv!(aes::Aes256),
1721 _ => return None,
1722 })
1723}
1724
1725/// The AES modes the ops accept. The set is closed here, so a mode name is
1726/// checked once on the way in and every later `match` is exhaustive. The
1727/// earlier shape compared the name against a string literal at each branch,
1728/// which let the three places that knew the set drift apart.
1729#[derive(Clone, Copy)]
1730enum AesMode {
1731 Gcm,
1732 /// GCM reports a failure by returning nothing and the block modes report
1733 /// a cause, so the two answer to different callers and cannot share one
1734 /// branch.
1735 Block(AesBlockMode),
1736}
1737
1738#[derive(Clone, Copy)]
1739enum AesBlockMode {
1740 Cbc,
1741 Ctr,
1742}
1743
1744impl AesMode {
1745 fn parse(name: &str) -> Option<Self> {
1746 Some(match name {
1747 "AES-GCM" => Self::Gcm,
1748 "AES-CBC" => Self::Block(AesBlockMode::Cbc),
1749 "AES-CTR" => Self::Block(AesBlockMode::Ctr),
1750 _ => return None,
1751 })
1752 }
1753}
1754
1755/// AES-CBC with PKCS#7 padding, and AES-CTR. Both take 128- or 256-bit keys,
1756/// and CTR is its own inverse, so `encrypting` only matters for CBC.
1757///
1758/// The counter block belongs to the caller, and incrementing it in place is
1759/// an easy and invisible mistake. This function cannot make it: `iv` is a
1760/// copy the op already took out of V8, so the caller's block is not reachable
1761/// from here.
1762///
1763/// `mode` cannot name AES-GCM, because `AesBlockMode` does not hold it. The
1764/// GCM path therefore cannot arrive here by mistake, and this function needs
1765/// no arm to refuse it.
1766fn webcrypto_aes_block_mode(
1767 mode: AesBlockMode,
1768 key: &[u8],
1769 iv: &[u8],
1770 data: &[u8],
1771 encrypting: bool,
1772) -> Result<Vec<u8>> {
1773 if let AesBlockMode::Ctr = mode {
1774 use ctr::cipher::{KeyIvInit, StreamCipher};
1775 if iv.len() != 16 {
1776 return Err(anyhow!("AES-CTR requires a 16-byte counter block"));
1777 }
1778 let mut out = data.to_vec();
1779 macro_rules! run {
1780 ($aes:ty) => {{
1781 let mut cipher = ctr::Ctr128BE::<$aes>::new_from_slices(key, iv)
1782 .map_err(|_| anyhow!("invalid AES-CTR key or counter"))?;
1783 cipher.apply_keystream(&mut out);
1784 }};
1785 }
1786 match key.len() {
1787 16 => run!(aes::Aes128),
1788 32 => run!(aes::Aes256),
1789 other => {
1790 return Err(anyhow!(
1791 "AES-CTR requires a 128- or 256-bit key, got {other} bytes"
1792 ))
1793 }
1794 }
1795 return Ok(out);
1796 }
1797 use cbc::cipher::block_padding::Pkcs7;
1798 use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
1799 if iv.len() != 16 {
1800 return Err(anyhow!("AES-CBC requires a 16-byte IV"));
1801 }
1802 macro_rules! run {
1803 ($aes:ty) => {{
1804 if encrypting {
1805 cbc::Encryptor::<$aes>::new_from_slices(key, iv)
1806 .map_err(|_| anyhow!("invalid AES-CBC key or IV"))?
1807 .encrypt_padded_vec_mut::<Pkcs7>(data)
1808 } else {
1809 cbc::Decryptor::<$aes>::new_from_slices(key, iv)
1810 .map_err(|_| anyhow!("invalid AES-CBC key or IV"))?
1811 .decrypt_padded_vec_mut::<Pkcs7>(data)
1812 .map_err(|_| anyhow!("AES-CBC decryption failed"))?
1813 }
1814 }};
1815 }
1816 match key.len() {
1817 16 => Ok(run!(aes::Aes128)),
1818 32 => Ok(run!(aes::Aes256)),
1819 other => Err(anyhow!(
1820 "AES-CBC requires a 128- or 256-bit key, got {other} bytes"
1821 )),
1822 }
1823}
1824
1825/// `$$aesEncrypt(mode, key, iv, data, additionalData, tagBytes)` and its
1826/// decrypt counterpart return a Uint8Array. The last two arguments apply only
1827/// to AES-GCM, so one typed-array op pair still serves all three AES modes.
1828fn op_webcrypto_aes(
1829 scope: &mut v8::PinScope,
1830 args: v8::FunctionCallbackArguments,
1831 rv: v8::ReturnValue<v8::Value>,
1832 encrypting: bool,
1833) {
1834 let mode = args.get(0).to_rust_string_lossy(scope);
1835 let (Some(key), Some(iv), Some(data), Some(additional_data)) = (
1836 view_bytes(args.get(1)),
1837 view_bytes(args.get(2)),
1838 view_bytes(args.get(3)),
1839 view_bytes(args.get(4)),
1840 ) else {
1841 return;
1842 };
1843 let tag_size = args.get(5).uint32_value(scope).unwrap_or(16) as usize;
1844 let throw = |scope: &mut v8::PinScope, error: anyhow::Error| {
1845 let message = v8::String::new(scope, &format!("crypto: {error}")).unwrap();
1846 let exception = v8::Exception::error(scope, message);
1847 scope.throw_exception(exception);
1848 };
1849 let Some(parsed) = AesMode::parse(&mode) else {
1850 throw(scope, anyhow!("unsupported AES mode: {mode}"));
1851 return;
1852 };
1853 match parsed {
1854 // AES-GCM keeps reporting a failure by returning nothing, because
1855 // `crypto.js` turns that into the `OperationError` the Web Crypto
1856 // specification names. A host `Error` thrown from here would replace a
1857 // specified DOMException with an unspecified one. The block modes have
1858 // no such JS-side error, so they report the cause instead of returning
1859 // `undefined` for the JS layer to misread.
1860 AesMode::Gcm => {
1861 if let Some(out) =
1862 webcrypto_aes_gcm(&key, &iv, &additional_data, &data, tag_size, encrypting)
1863 {
1864 webcrypto_return_bytes(scope, rv, &out);
1865 }
1866 }
1867 AesMode::Block(block) => {
1868 match webcrypto_aes_block_mode(block, &key, &iv, &data, encrypting) {
1869 Ok(out) => webcrypto_return_bytes(scope, rv, &out),
1870 Err(error) => throw(scope, error),
1871 }
1872 }
1873 }
1874}
1875
1876pub(super) fn op_webcrypto_aes_encrypt(
1877 scope: &mut v8::PinScope,
1878 args: v8::FunctionCallbackArguments,
1879 rv: v8::ReturnValue<v8::Value>,
1880) {
1881 op_webcrypto_aes(scope, args, rv, true);
1882}
1883
1884pub(super) fn op_webcrypto_aes_decrypt(
1885 scope: &mut v8::PinScope,
1886 args: v8::FunctionCallbackArguments,
1887 rv: v8::ReturnValue<v8::Value>,
1888) {
1889 op_webcrypto_aes(scope, args, rv, false);
1890}