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