Skip to main content

nodejs/stdlib/
crypto.rs

1//! Node `crypto` module.
2//!
3//! * `createHash(algo)` → a `Hash` instance (`update(...).digest(enc)`), backed
4//!   by the `md-5`/`sha1`/`sha2` crates.
5//! * `createHmac(algo, key)` → an `Hmac` instance (`update(...).digest(enc)`),
6//!   backed by the `hmac` crate over the same digests.
7//! * `randomBytes`, `randomUUID`, `randomInt` — CSPRNG output via `getrandom`.
8//!
9//! `Hash`/`Hmac` are plain objects tagged `@@native = "Hash"` / `"Hmac"`
10//! accumulating input in a hidden `@@data` byte array until `digest` finalizes.
11
12use super::{arg_str, to_base64, to_hex};
13use crate::host::{is_callable, with_host, JsObj};
14use cipher::block_padding::Pkcs7;
15use cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit, StreamCipher};
16use fusevm::Value;
17use hkdf::Hkdf;
18use hmac::{Hmac, Mac};
19use indexmap::IndexMap;
20use md5::{Digest as _, Md5};
21use num_bigint::BigUint;
22use p256::elliptic_curve::sec1::ToEncodedPoint;
23use pkcs8::{DecodePrivateKey, EncodePrivateKey, LineEnding};
24use rsa::pkcs1::{DecodeRsaPrivateKey, DecodeRsaPublicKey};
25use sha1::Sha1;
26use sha2::{Sha256, Sha384, Sha512};
27use signature::{SignatureEncoding, Signer, Verifier};
28use spki::{DecodePublicKey, EncodePublicKey};
29use subtle::ConstantTimeEq;
30
31/// Cipher algorithms `createCipheriv`/`createDecipheriv` support (AES CBC/CTR).
32const CIPHERS: &[&str] = &[
33    "aes-128-cbc",
34    "aes-192-cbc",
35    "aes-256-cbc",
36    "aes-128-ctr",
37    "aes-192-ctr",
38    "aes-256-ctr",
39];
40
41/// Digest names `createHash`/`createHmac`/`pbkdf2`/`hkdf` accept.
42const HASHES: &[&str] = &["md5", "sha1", "sha256", "sha512"];
43
44/// Standard EC curve names for `getCurves()`. Key generation over these is not
45/// supported (no EC crate available); the list mirrors the common OpenSSL names
46/// so feature-detection code sees them.
47const CURVES: &[&str] = &[
48    "prime256v1",
49    "secp256k1",
50    "secp384r1",
51    "secp521r1",
52    "secp224r1",
53    "secp192k1",
54    "secp256r1",
55];
56
57pub const METHODS: &[&str] = &[
58    "createHash",
59    "createHmac",
60    "randomBytes",
61    "randomUUID",
62    "randomInt",
63    "pbkdf2Sync",
64    "pbkdf2",
65    "scryptSync",
66    "scrypt",
67    "hkdfSync",
68    "hkdf",
69    "createCipheriv",
70    "createDecipheriv",
71    "randomFillSync",
72    "randomFill",
73    "timingSafeEqual",
74    "getHashes",
75    "getCiphers",
76    "getCurves",
77    "getFips",
78    "pseudoRandomBytes",
79    "prng",
80    "rng",
81    "hash",
82    "randomUUIDv7",
83    "getCipherInfo",
84    // Asymmetric keys & signatures
85    "generateKeyPairSync",
86    "generateKeyPair",
87    "createPrivateKey",
88    "createPublicKey",
89    "createSecretKey",
90    "createSign",
91    "createVerify",
92    "sign",
93    "verify",
94    "publicEncrypt",
95    "privateDecrypt",
96    "privateEncrypt",
97    "publicDecrypt",
98    // Diffie-Hellman / ECDH
99    "createDiffieHellman",
100    "createDiffieHellmanGroup",
101    "getDiffieHellman",
102    "createECDH",
103    "diffieHellman",
104    // Primes
105    "checkPrime",
106    "checkPrimeSync",
107    "generatePrime",
108    "generatePrimeSync",
109    // Misc
110    "argon2",
111    "argon2Sync",
112    "getRandomValues",
113];
114
115/// The `webcrypto` / `globalThis.crypto` members this runtime implements.
116///
117/// `subtle` carries `digest` ONLY. The rest of SubtleCrypto — `encrypt`,
118/// `generateKey`, `importKey`, the key-derivation and key-wrapping methods, and
119/// the `CryptoKey` type they exchange — is not implemented, and is absent rather
120/// than present-and-always-rejecting so that a `typeof subtle.encrypt` feature
121/// probe correctly takes its fallback path.
122pub const WEBCRYPTO_METHODS: &[&str] = &["getRandomValues", "randomUUID"];
123
124/// The implemented half of `crypto.subtle`.
125pub const SUBTLE_METHODS: &[&str] = &["digest"];
126
127/// `crypto.subtle.<method>`.
128pub fn subtle_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
129    match method {
130        // `subtle.digest(algorithm, data)` resolves with an `ArrayBuffer`. The
131        // algorithm is named the WebCrypto way (`"SHA-256"`, or
132        // `{ name: "SHA-256" }`), which is node's `sha256` with the dash
133        // dropped.
134        "digest" => {
135            let spec = args.first().cloned().unwrap_or(Value::Undef);
136            let named = crate::builtins::get_property(&spec, "name").unwrap_or(Value::Undef);
137            let raw = match named {
138                Value::Undef => with_host(|h| h.str_of(&spec)),
139                n => with_host(|h| h.str_of(&n)),
140            };
141            let algo = raw.replace('-', "").to_ascii_lowercase();
142            if !supported(&algo) {
143                return Some(Err(crate::host::dom_error(
144                    "NotSupportedError",
145                    "Unrecognized algorithm name",
146                )));
147            }
148            let data = val_bytes_at(args, 1);
149            let out = digest(&algo, &data);
150            let buf = crate::stdlib::typedarray::new_array_buffer(out.len());
151            crate::stdlib::typedarray::write_buffer_bytes(&buf, &out);
152            Some(crate::builtins::promise_resolve_pub(buf))
153        }
154        _ => None,
155    }
156}
157
158pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
159    Some(match method {
160        "createHash" => {
161            let algo = arg_str(args, 0).to_ascii_lowercase();
162            if !supported(&algo) {
163                // Node names no algorithm here — the reference message is the bare
164                // `Digest method not supported`, and it carries no `code`.
165                return Some(Err("Error: Digest method not supported".into()));
166            }
167            Ok(with_host(|h| {
168                let data = h.new_array(Vec::new());
169                let mut m = IndexMap::new();
170                m.insert("@@native".into(), h.new_str("Hash"));
171                m.insert("@@algo".into(), h.new_str(algo));
172                m.insert("@@data".into(), data);
173                h.new_object(m)
174            }))
175        }
176        "createHmac" => {
177            let algo = arg_str(args, 0).to_ascii_lowercase();
178            if !supported(&algo) {
179                // Node names no algorithm here — the reference message is the bare
180                // `Digest method not supported`, and it carries no `code`.
181                return Some(Err("Error: Digest method not supported".into()));
182            }
183            // Key may be a Buffer (raw bytes) or a string (utf8 by default).
184            let key = key_bytes(args.get(1));
185            Ok(with_host(|h| {
186                let data = h.new_array(Vec::new());
187                let keyv = h.new_array(key.iter().map(|b| Value::Float(*b as f64)).collect());
188                let mut m = IndexMap::new();
189                m.insert("@@native".into(), h.new_str("Hmac"));
190                m.insert("@@algo".into(), h.new_str(algo));
191                m.insert("@@key".into(), keyv);
192                m.insert("@@data".into(), data);
193                h.new_object(m)
194            }))
195        }
196        "randomBytes" => {
197            let n = super::arg_num(args, 0).max(0.0) as usize;
198            let mut buf = vec![0u8; n];
199            if let Err(e) = getrandom::getrandom(&mut buf) {
200                return Some(Err(format!("Error: failed to generate random bytes: {e}")));
201            }
202            // Callback form: randomBytes(n, (err, buf) => ...). Build the Buffer,
203            // release the host borrow, then queue the callback with (null, buf).
204            let cb = args
205                .get(1)
206                .cloned()
207                .filter(|v| with_host(|h| is_callable(h, v)));
208            if let Some(cb) = cb {
209                let bufv = super::buffer::from_bytes(&buf);
210                with_host(|h| {
211                    let nullv = h.null();
212                    h.queue_io_callback(cb, vec![nullv, bufv]);
213                });
214                Ok(Value::Undef)
215            } else {
216                Ok(super::buffer::from_bytes(&buf))
217            }
218        }
219        "randomUUID" => {
220            let mut b = [0u8; 16];
221            if let Err(e) = getrandom::getrandom(&mut b) {
222                return Some(Err(format!("Error: failed to generate random bytes: {e}")));
223            }
224            // RFC 4122 v4: version nibble = 4, variant nibble ∈ [8..b].
225            b[6] = (b[6] & 0x0f) | 0x40;
226            b[8] = (b[8] & 0x3f) | 0x80;
227            let h = to_hex(&b);
228            let uuid = format!(
229                "{}-{}-{}-{}-{}",
230                &h[0..8],
231                &h[8..12],
232                &h[12..16],
233                &h[16..20],
234                &h[20..32],
235            );
236            Ok(with_host(|host| host.new_str(uuid)))
237        }
238        "randomInt" => {
239            // randomInt([min, ]max) — uniform integer in [min, max).
240            let (min, max) = if args.len() >= 2 {
241                (super::arg_num(args, 0), super::arg_num(args, 1))
242            } else {
243                (0.0, super::arg_num(args, 0))
244            };
245            let (min, max) = (min as i64, max as i64);
246            if max <= min {
247                return Some(Err(crate::host::coded_error(
248                    "RangeError",
249                    "ERR_OUT_OF_RANGE",
250                    &format!(
251                        "The value of \"max\" is out of range. It must be greater than \
252                         the value of \"min\" ({min}). Received {max}"
253                    ),
254                )));
255            }
256            let range = (max - min) as u64;
257            match random_below(range) {
258                Ok(r) => Ok(Value::Float((min + r as i64) as f64)),
259                Err(e) => Err(format!("Error: failed to generate random bytes: {e}")),
260            }
261        }
262        // ── Key derivation ──────────────────────────────────────────────
263        "pbkdf2Sync" => pbkdf2(args, None),
264        "pbkdf2" => pbkdf2(args, args.get(5).cloned()),
265        "scryptSync" => scrypt(args, None),
266        "scrypt" => scrypt(args, trailing_cb(args)),
267        "hkdfSync" => hkdf(args, None),
268        "hkdf" => hkdf(args, args.get(5).cloned()),
269        // ── Symmetric ciphers ───────────────────────────────────────────
270        "createCipheriv" => make_cipher("Cipheriv", args),
271        "createDecipheriv" => make_cipher("Decipheriv", args),
272        // ── Random fill ─────────────────────────────────────────────────
273        "randomFillSync" => random_fill(args),
274        // randomFill(buf[, offset[, size]], callback): the callback is the
275        // first function among `offset`/`size`/`callback`, and every argument
276        // error throws SYNCHRONOUSLY — it used to reach the callback as a bare
277        // string, and a callback in the `offset` slot was read as the offset.
278        "randomFill" => random_fill_async(args),
279        // ── Constant-time compare ───────────────────────────────────────
280        "timingSafeEqual" => {
281            let a = val_bytes_at(args, 0);
282            let b = val_bytes_at(args, 1);
283            if a.len() != b.len() {
284                return Some(Err(crate::host::plain_coded_error(
285                    "RangeError",
286                    "ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH",
287                    "Input buffers must have the same byte length",
288                )));
289            }
290            Ok(Value::Bool(a.ct_eq(&b).into()))
291        }
292        // ── Introspection ───────────────────────────────────────────────
293        "getHashes" => Ok(with_host(|h| {
294            let items: Vec<Value> = HASHES.iter().map(|s| h.new_str(*s)).collect();
295            h.new_array(items)
296        })),
297        "getCiphers" => Ok(with_host(|h| {
298            let items: Vec<Value> = CIPHERS.iter().map(|s| h.new_str(*s)).collect();
299            h.new_array(items)
300        })),
301        "getCurves" => Ok(with_host(|h| {
302            let items: Vec<Value> = CURVES.iter().map(|s| h.new_str(*s)).collect();
303            h.new_array(items)
304        })),
305        // node v26 returns the number 0 (not the boolean false) from getFips().
306        "getFips" => Ok(Value::Float(0.0)),
307        "getCipherInfo" => cipher_info(&arg_str(args, 0).to_ascii_lowercase()),
308        // ── randomBytes aliases (all return a Buffer of CSPRNG bytes) ────
309        "pseudoRandomBytes" | "prng" | "rng" => {
310            let n = super::arg_num(args, 0).max(0.0) as usize;
311            let mut buf = vec![0u8; n];
312            if let Err(e) = getrandom::getrandom(&mut buf) {
313                return Some(Err(format!("Error: failed to generate random bytes: {e}")));
314            }
315            let cb = args
316                .get(1)
317                .cloned()
318                .filter(|v| with_host(|h| is_callable(h, v)));
319            if let Some(cb) = cb {
320                let bufv = super::buffer::from_bytes(&buf);
321                with_host(|h| {
322                    let nullv = h.null();
323                    h.queue_io_callback(cb, vec![nullv, bufv]);
324                });
325                Ok(Value::Undef)
326            } else {
327                Ok(super::buffer::from_bytes(&buf))
328            }
329        }
330        // ── One-shot hash (node 21+) ────────────────────────────────────
331        "hash" => {
332            let algo = arg_str(args, 0).to_ascii_lowercase();
333            if !supported(&algo) {
334                // Node names no algorithm here — the reference message is the bare
335                // `Digest method not supported`, and it carries no `code`.
336                return Some(Err("Error: Digest method not supported".into()));
337            }
338            // args[1] is the data (utf8 string or Buffer); there is no input-encoding param.
339            let data = val_bytes_at(args, 1);
340            // args[2] is the output encoding (default "hex"); "buffer" yields a Buffer.
341            let out = digest(&algo, &data);
342            let out_enc = if args.len() > 2 {
343                arg_str(args, 2)
344            } else {
345                "hex".into()
346            };
347            Ok(if out_enc == "buffer" {
348                super::buffer::from_bytes(&out)
349            } else {
350                encode_out(&out, Some(&out_enc))
351            })
352        }
353        // ── time-ordered UUID v7 ────────────────────────────────────────
354        "randomUUIDv7" => uuid_v7(),
355        // ── Asymmetric key generation ───────────────────────────────────
356        "generateKeyPairSync" => {
357            generate_key_pair(&arg_str(args, 0).to_ascii_lowercase(), args.get(1))
358        }
359        "generateKeyPair" => {
360            let cb = trailing_cb(args);
361            let res = generate_key_pair(&arg_str(args, 0).to_ascii_lowercase(), args.get(1));
362            match cb {
363                Some(cb) => {
364                    match res {
365                        Ok(pair) => with_host(|h| {
366                            // Deliver (err=null, publicKey, privateKey).
367                            let nullv = h.null();
368                            let (pubk, prvk) = match h.get(&pair) {
369                                Some(JsObj::Object(p)) => (
370                                    p.get("publicKey").cloned().unwrap_or(Value::Undef),
371                                    p.get("privateKey").cloned().unwrap_or(Value::Undef),
372                                ),
373                                _ => (Value::Undef, Value::Undef),
374                            };
375                            h.queue_io_callback(cb, vec![nullv, pubk, prvk]);
376                        }),
377                        Err(e) => {
378                            let errv = with_host(|h| h.new_str(e));
379                            with_host(|h| h.queue_io_callback(cb, vec![errv]));
380                        }
381                    }
382                    Ok(Value::Undef)
383                }
384                None => res,
385            }
386        }
387        "createPrivateKey" => create_private_key(args.first()),
388        "createPublicKey" => create_public_key(args.first()),
389        "createSecretKey" => Ok(secret_key_object(&val_bytes_at(args, 0))),
390        // ── Sign / Verify (streaming instances) ─────────────────────────
391        "createSign" => Ok(new_sign_verify("Sign", &arg_str(args, 0))),
392        "createVerify" => Ok(new_sign_verify("Verify", &arg_str(args, 0))),
393        // ── Sign / Verify (one-shot) ────────────────────────────────────
394        "sign" => {
395            let algo = arg_str(args, 0);
396            let data = val_bytes_at(args, 1);
397            let key = key_material(args.get(2).unwrap_or(&Value::Undef));
398            match sign_data(&key, &algo, &data) {
399                Ok(sig) => Ok(super::buffer::from_bytes(&sig)),
400                Err(e) => Err(e),
401            }
402        }
403        "verify" => {
404            let algo = arg_str(args, 0);
405            let data = val_bytes_at(args, 1);
406            let key = key_material(args.get(2).unwrap_or(&Value::Undef));
407            let sig = val_bytes_at(args, 3);
408            match verify_data(&key, &algo, &data, &sig) {
409                Ok(ok) => Ok(Value::Bool(ok)),
410                Err(e) => Err(e),
411            }
412        }
413        // ── RSA public/private encryption ───────────────────────────────
414        "publicEncrypt" => rsa_public_op(args, true, true),
415        "privateDecrypt" => rsa_public_op(args, false, false),
416        "privateEncrypt" => rsa_private_encrypt(args),
417        "publicDecrypt" => rsa_public_decrypt(args),
418        // ── Diffie-Hellman ──────────────────────────────────────────────
419        "createDiffieHellman" => create_diffie_hellman(args),
420        "createDiffieHellmanGroup" | "getDiffieHellman" => diffie_hellman_group(&arg_str(args, 0)),
421        "createECDH" => create_ecdh(&arg_str(args, 0)),
422        "diffieHellman" => diffie_hellman_oneshot(args.first()),
423        // ── Primes ──────────────────────────────────────────────────────
424        "checkPrimeSync" => Ok(Value::Bool(check_prime(args.first()))),
425        "checkPrime" => {
426            let ok = check_prime(args.first());
427            let cb = trailing_cb(args);
428            match cb {
429                Some(cb) => {
430                    with_host(|h| {
431                        let nullv = h.null();
432                        h.queue_io_callback(cb, vec![nullv, Value::Bool(ok)]);
433                    });
434                    Ok(Value::Undef)
435                }
436                None => Ok(Value::Bool(ok)),
437            }
438        }
439        "generatePrimeSync" => {
440            generate_prime(super::arg_num(args, 0) as usize, opts_object(args, 1))
441        }
442        "generatePrime" => {
443            let res = generate_prime(super::arg_num(args, 0) as usize, opts_object(args, 1));
444            let cb = trailing_cb(args);
445            match (cb, res) {
446                (Some(cb), Ok(v)) => {
447                    with_host(|h| {
448                        let nullv = h.null();
449                        h.queue_io_callback(cb, vec![nullv, v]);
450                    });
451                    Ok(Value::Undef)
452                }
453                (Some(cb), Err(e)) => {
454                    let errv = with_host(|h| h.new_str(e));
455                    with_host(|h| h.queue_io_callback(cb, vec![errv]));
456                    Ok(Value::Undef)
457                }
458                (None, r) => r,
459            }
460        }
461        // ── argon2 ──────────────────────────────────────────────────────
462        "argon2Sync" => match argon2_hash(&arg_str(args, 0), args.get(1)) {
463            Ok(out) => Ok(super::buffer::from_bytes(&out)),
464            Err(e) => Err(e),
465        },
466        "argon2" => deliver_async(
467            trailing_cb(args),
468            argon2_hash(&arg_str(args, 0), args.get(1)),
469        ),
470        // ── WebCrypto getRandomValues ───────────────────────────────────
471        "getRandomValues" => get_random_values(args.first()),
472        _ => return None,
473    })
474}
475
476/// `Hash` instance methods: `update` (chainable) and `digest`.
477pub fn instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
478    hashlike_call("Hash", recv, method, args)
479}
480
481/// `Hmac` instance methods: `update` (chainable) and `digest`.
482pub fn hmac_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
483    hashlike_call("Hmac", recv, method, args)
484}
485
486/// `Cipheriv`/`Decipheriv` instance methods: `update(data[,inEnc,outEnc])` and
487/// `final([outEnc])`. Input is accumulated in `@@data`; the transform runs at
488/// `final` (CBC needs the full block/padding stream, so `update` returns empty
489/// and `final` returns the whole result — the standard `update()+final()`
490/// concatenation is byte-identical to node).
491pub fn cipher_instance_call(
492    tag: &str,
493    recv: &Value,
494    method: &str,
495    args: &[Value],
496) -> Result<Value, String> {
497    match method {
498        "update" => {
499            // Input after `final` is rejected — this accepted it and answered
500            // with an empty string, so the data silently went nowhere.
501            if finalized(recv) {
502                return Err("Error: Trying to add data in unsupported state".into());
503            }
504            // Shared with `Hash`/`Hmac`: any byte VIEW contributes its bytes,
505            // only a string is decoded, and anything else is rejected. Only a
506            // Buffer was recognised here, so a Uint8Array was stringified.
507            let enc = if args.len() > 1 {
508                arg_str(args, 1)
509            } else {
510                "utf8".into()
511            };
512            let bytes = update_bytes(args, &enc)?;
513            with_host(|h| {
514                if let Some(JsObj::Object(p)) = h.get(recv).cloned() {
515                    if let Some(arr) = p.get("@@data").cloned() {
516                        if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
517                            items.extend(bytes.iter().map(|b| Value::Float(*b as f64)));
518                        }
519                    }
520                }
521            });
522            let out_enc = if args.len() > 2 {
523                Some(arg_str(args, 2))
524            } else {
525                None
526            };
527            Ok(encode_out(&[], out_enc.as_deref()))
528        }
529        "final" => {
530            // A cipher finalizes ONCE. Running the transform again returned a
531            // second, valid-looking ciphertext for input that was already
532            // consumed.
533            if finalized(recv) {
534                return Err(crate::host::coded_error(
535                    "Error",
536                    "ERR_CRYPTO_INVALID_STATE",
537                    "Invalid state",
538                ));
539            }
540            mark_finalized(recv);
541            let (algo, key, iv, data) = with_host(|h| {
542                let (mut algo, mut key, mut iv, mut data) =
543                    (String::new(), Vec::new(), Vec::new(), Vec::new());
544                if let Some(JsObj::Object(p)) = h.get(recv) {
545                    algo = p.get("@@algo").map(|v| h.str_of(v)).unwrap_or_default();
546                    if let Some(JsObj::Array(it)) = p.get("@@key").and_then(|v| h.get(v)) {
547                        key = it.iter().map(|v| h.to_number(v) as u8).collect();
548                    }
549                    if let Some(JsObj::Array(it)) = p.get("@@iv").and_then(|v| h.get(v)) {
550                        iv = it.iter().map(|v| h.to_number(v) as u8).collect();
551                    }
552                    if let Some(JsObj::Array(it)) = p.get("@@data").and_then(|v| h.get(v)) {
553                        data = it.iter().map(|v| h.to_number(v) as u8).collect();
554                    }
555                }
556                (algo, key, iv, data)
557            });
558            let out = cipher_crypt(&algo, &key, &iv, &data, tag == "Cipheriv")?;
559            let out_enc = if args.is_empty() {
560                None
561            } else {
562                Some(arg_str(args, 0))
563            };
564            Ok(encode_out(&out, out_enc.as_deref()))
565        }
566        "setAutoPadding" => Ok(recv.clone()),
567        _ => Err(crate::host::type_error(&format!(
568            "{}.{method} is not a function",
569            tag.to_ascii_lowercase()
570        ))),
571    }
572}
573
574/// Shared `update`/`digest` for `Hash` and `Hmac` (both accumulate into `@@data`;
575/// `digest` finalizes via a plain digest or an HMAC keyed by `@@key`).
576fn hashlike_call(kind: &str, recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
577    match method {
578        "update" => {
579            // A finalized digest cannot take more input. This accepted it
580            // silently and folded it into a hash nobody would read, so the
581            // mistake produced no symptom at all.
582            if finalized(recv) {
583                return Err(hash_finalized());
584            }
585            let enc = if args.len() > 1 {
586                arg_str(args, 1)
587            } else {
588                "utf8".into()
589            };
590            // A byte-like VIEW contributes its bytes; only a string goes
591            // through the encoding. Every input used to be stringified first,
592            // so `hash.update(new TextEncoder().encode(s))` hashed
593            // `"[object Object]"`, and a Buffer only worked because
594            // stringifying it happened to yield its utf8 text — which is wrong
595            // the moment the bytes are not valid utf8.
596            let bytes = update_bytes(args, &enc)?;
597            with_host(|h| {
598                if let Some(JsObj::Object(p)) = h.get(recv).cloned() {
599                    if let Some(arr) = p.get("@@data").cloned() {
600                        if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
601                            items.extend(bytes.iter().map(|b| Value::Float(*b as f64)));
602                        }
603                    }
604                }
605            });
606            Ok(recv.clone())
607        }
608        // `Hash.copy()` forks the running state, so the two go on to hash
609        // different tails. Without it the only way to hash a common prefix twice
610        // was to replay the prefix. An Hmac has no `copy`.
611        "copy" if kind == "Hash" => {
612            if finalized(recv) {
613                return Err(hash_finalized());
614            }
615            let (algo, data) = with_host(|h| {
616                let (mut algo, mut data) = (String::new(), Vec::new());
617                if let Some(JsObj::Object(p)) = h.get(recv) {
618                    algo = p.get("@@algo").map(|v| h.str_of(v)).unwrap_or_default();
619                    if let Some(JsObj::Array(items)) = p.get("@@data").and_then(|v| h.get(v)) {
620                        data = items.clone();
621                    }
622                }
623                (algo, data)
624            });
625            Ok(with_host(|h| {
626                let data = h.new_array(data);
627                let mut m = IndexMap::new();
628                m.insert("@@native".into(), h.new_str("Hash"));
629                m.insert("@@algo".into(), h.new_str(algo));
630                m.insert("@@data".into(), data);
631                h.new_object(m)
632            }))
633        }
634        "digest" => {
635            // A second `digest` on a Hash throws; on an Hmac node answers with
636            // an EMPTY buffer instead. Re-running the digest — what this did —
637            // hands back a value that looks valid and is not what node returns.
638            if finalized(recv) {
639                if kind == "Hash" {
640                    return Err(hash_finalized());
641                }
642                let enc = args.first().map(|_| arg_str(args, 0));
643                return Ok(encode_digest(&[], enc.as_deref()));
644            }
645            mark_finalized(recv);
646            let (algo, key, data) = with_host(|h| {
647                let (mut algo, mut key, mut data) = (String::new(), Vec::new(), Vec::new());
648                if let Some(JsObj::Object(p)) = h.get(recv) {
649                    algo = p.get("@@algo").map(|v| h.str_of(v)).unwrap_or_default();
650                    if let Some(JsObj::Array(items)) = p.get("@@data").and_then(|v| h.get(v)) {
651                        data = items.iter().map(|v| h.to_number(v) as u8).collect();
652                    }
653                    if let Some(JsObj::Array(items)) = p.get("@@key").and_then(|v| h.get(v)) {
654                        key = items.iter().map(|v| h.to_number(v) as u8).collect();
655                    }
656                }
657                (algo, key, data)
658            });
659            let out = if kind == "Hmac" {
660                hmac_digest(&algo, &key, &data)
661            } else {
662                digest(&algo, &data)
663            };
664            let enc = if args.is_empty() {
665                None
666            } else {
667                Some(arg_str(args, 0))
668            };
669            Ok(encode_digest(&out, enc.as_deref()))
670        }
671        _ => Err(crate::host::type_error(&format!(
672            "{}.{method} is not a function",
673            kind.to_ascii_lowercase()
674        ))),
675    }
676}
677
678/// The bytes an `update(data[, encoding])` contributes.
679///
680/// A byte-like VIEW contributes its bytes; only a STRING goes through the
681/// encoding. Anything else is REJECTED rather than stringified: `update(5)`
682/// hashing the text "5" is a silent corruption, since the caller believes a
683/// number went in and gets a digest of something else.
684fn update_bytes(args: &[Value], enc: &str) -> Result<Vec<u8>, String> {
685    let first = args.first().cloned().unwrap_or(Value::Undef);
686    if let Some(b) = super::buffer::view_bytes(&first) {
687        return Ok(b);
688    }
689    if with_host(|h| h.as_str(&first)).is_none() {
690        return Err(crate::host::invalid_arg_type(
691            "data",
692            "argument",
693            "string or an instance of Buffer, TypedArray, or DataView",
694            &first,
695        ));
696    }
697    Ok(decode(&arg_str(args, 0), enc))
698}
699
700/// Render a finished digest in the requested encoding (a Buffer with none).
701fn encode_digest(out: &[u8], enc: Option<&str>) -> Value {
702    match enc {
703        Some("hex") => with_host(|h| h.new_str(to_hex(out))),
704        Some("base64") | Some("base64url") => with_host(|h| h.new_str(to_base64(out))),
705        Some("latin1") | Some("binary") => {
706            with_host(|h| h.new_str(out.iter().map(|b| *b as char).collect::<String>()))
707        }
708        _ => super::buffer::from_bytes(out),
709    }
710}
711
712/// Whether `digest` has already run on this `Hash`/`Hmac`.
713fn finalized(recv: &Value) -> bool {
714    with_host(|h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@done")))
715}
716
717fn mark_finalized(recv: &Value) {
718    with_host(|h| {
719        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
720            p.insert("@@done".into(), Value::Bool(true));
721        }
722    });
723}
724
725fn hash_finalized() -> String {
726    crate::host::coded_error(
727        "Error",
728        "ERR_CRYPTO_HASH_FINALIZED",
729        "Digest already called",
730    )
731}
732
733fn supported(algo: &str) -> bool {
734    matches!(algo, "md5" | "sha1" | "sha256" | "sha512")
735}
736
737fn digest(algo: &str, data: &[u8]) -> Vec<u8> {
738    match algo {
739        "md5" => {
740            let mut h = Md5::new();
741            h.update(data);
742            h.finalize().to_vec()
743        }
744        "sha1" => {
745            let mut h = Sha1::new();
746            h.update(data);
747            h.finalize().to_vec()
748        }
749        "sha512" => {
750            let mut h = Sha512::new();
751            h.update(data);
752            h.finalize().to_vec()
753        }
754        _ => {
755            let mut h = Sha256::new();
756            h.update(data);
757            h.finalize().to_vec()
758        }
759    }
760}
761
762fn hmac_digest(algo: &str, key: &[u8], data: &[u8]) -> Vec<u8> {
763    // HMAC accepts any key length, so `new_from_slice` never fails here.
764    match algo {
765        "md5" => {
766            let mut m = Hmac::<Md5>::new_from_slice(key).expect("HMAC accepts any key length");
767            m.update(data);
768            m.finalize().into_bytes().to_vec()
769        }
770        "sha1" => {
771            let mut m = Hmac::<Sha1>::new_from_slice(key).expect("HMAC accepts any key length");
772            m.update(data);
773            m.finalize().into_bytes().to_vec()
774        }
775        "sha512" => {
776            let mut m = Hmac::<Sha512>::new_from_slice(key).expect("HMAC accepts any key length");
777            m.update(data);
778            m.finalize().into_bytes().to_vec()
779        }
780        _ => {
781            let mut m = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts any key length");
782            m.update(data);
783            m.finalize().into_bytes().to_vec()
784        }
785    }
786}
787
788/// The `createHmac` key argument as raw bytes: a Buffer's bytes, else the value's
789/// utf8 string encoding.
790fn key_bytes(v: Option<&Value>) -> Vec<u8> {
791    v.map(val_bytes).unwrap_or_default()
792}
793
794/// A value's raw bytes: a Buffer/TypedArray's backing bytes, else its utf8
795/// string encoding. Used by pbkdf2/scrypt/hkdf/cipher/timingSafeEqual inputs.
796fn val_bytes(v: &Value) -> Vec<u8> {
797    // Any byte-like VIEW, not just a `Buffer`. Only the Buffer case was
798    // handled, so a `Uint8Array` — what `TextEncoder.encode` returns, and the
799    // form every WebCrypto call takes — fell through to `str_of` and hashed the
800    // string `"[object Object]"` instead of its bytes.
801    if let Some(bytes) = super::buffer::view_bytes(v) {
802        return bytes;
803    }
804    // A `KeyObject` carries its bytes in a hidden slot. Stringifying it yielded
805    // the text of an object, so `hkdf(digest, secretKey, …)` derived from that
806    // text — a plausible key for input the caller never supplied.
807    if is_key_object(v) {
808        return with_host(|h| {
809            match h.get(v) {
810                Some(JsObj::Object(p)) => p.get("@@secret").cloned(),
811                _ => None,
812            }
813            .and_then(|arr| match h.get(&arr) {
814                Some(JsObj::Array(items)) => {
815                    Some(items.iter().map(|b| h.to_number(b) as u8).collect())
816                }
817                _ => None,
818            })
819            .unwrap_or_default()
820        });
821    }
822    with_host(|h| h.str_of(v)).into_bytes()
823}
824
825/// The byte-like argument forms each KDF position accepts, spelled the way node
826/// spells them in its `ERR_INVALID_ARG_TYPE` message. They differ per position,
827/// so the text cannot be shared: `hkdf`'s `ikm` takes a `SecretKeyObject` and
828/// `pbkdf2`'s `password` does not.
829const KDF_BYTES: &str = "string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView";
830const HKDF_IKM: &str =
831    "string or an instance of SecretKeyObject, ArrayBuffer, TypedArray, DataView, or Buffer";
832const HKDF_BYTES: &str = "string or an instance of ArrayBuffer, TypedArray, DataView, or Buffer";
833
834/// `val_bytes_at` that REJECTS a value which is neither a string nor byte-like,
835/// as node does. `pbkdf2Sync(5, …)` deriving a key from the text "5" is the
836/// worst kind of silent pass-through: the result is a plausible key for the
837/// wrong input.
838fn bytes_arg(args: &[Value], i: usize, name: &str, expected: &str) -> Result<Vec<u8>, String> {
839    let v = args.get(i).cloned().unwrap_or(Value::Undef);
840    if super::buffer::view_bytes(&v).is_none()
841        && with_host(|h| h.as_str(&v)).is_none()
842        && !(expected == HKDF_IKM && is_key_object(&v))
843    {
844        return Err(crate::host::invalid_arg_type(
845            name, "argument", expected, &v,
846        ));
847    }
848    Ok(val_bytes_at(args, i))
849}
850
851/// `val_bytes` for the arg at index `i` (`Value::Undef` → empty).
852fn val_bytes_at(args: &[Value], i: usize) -> Vec<u8> {
853    args.get(i).map(val_bytes).unwrap_or_default()
854}
855
856/// The trailing argument if it is a callback (async form detection).
857fn trailing_cb(args: &[Value]) -> Option<Value> {
858    args.last()
859        .cloned()
860        .filter(|v| with_host(|h| is_callable(h, v)))
861}
862
863/// The arg at index `i` if it is a plain (non-callable) options object.
864fn opts_object(args: &[Value], i: usize) -> Option<Value> {
865    let v = args.get(i)?.clone();
866    let is_obj = with_host(|h| matches!(h.get(&v), Some(JsObj::Object(_))) && !is_callable(h, &v));
867    is_obj.then_some(v)
868}
869
870/// Queue a derived-key result to an async callback as `(null, buf)` / `(err)`;
871/// if there is no callback, return the value/error synchronously.
872fn deliver_async(cb: Option<Value>, res: Result<Vec<u8>, String>) -> Result<Value, String> {
873    // A KDF's arguments are validated SYNCHRONOUSLY, so a bad digest or bad
874    // scrypt parameter throws out of the call in BOTH forms. This queued the
875    // failure as a callback argument instead — and as a bare string, so the
876    // handler's `err.code` was undefined and `err instanceof Error` false.
877    let out = res?;
878    match cb.filter(|v| with_host(|h| is_callable(h, v))) {
879        Some(cb) => {
880            let bufv = super::buffer::from_bytes(&out);
881            with_host(|h| {
882                let nullv = h.null();
883                h.queue_io_callback(cb, vec![nullv, bufv]);
884            });
885            Ok(Value::Undef)
886        }
887        None => Ok(super::buffer::from_bytes(&out)),
888    }
889}
890
891/// `pbkdf2Sync(password, salt, iterations, keylen, digest)` and its callback
892/// form, which differ only in how the finished bytes are delivered.
893fn pbkdf2(args: &[Value], cb: Option<Value>) -> Result<Value, String> {
894    let digest = arg_str(args, 4).to_ascii_lowercase();
895    let res = pbkdf2_derive(
896        &digest,
897        &bytes_arg(args, 0, "password", KDF_BYTES)?,
898        &bytes_arg(args, 1, "salt", KDF_BYTES)?,
899        super::arg_num(args, 2) as u32,
900        super::arg_num(args, 3).max(0.0) as usize,
901    );
902    deliver_async(cb, res)
903}
904
905/// `scryptSync(password, salt, keylen[, options])` and its callback form.
906fn scrypt(args: &[Value], cb: Option<Value>) -> Result<Value, String> {
907    let keylen = super::arg_num(args, 2).max(0.0) as usize;
908    let res = scrypt_derive(
909        &bytes_arg(args, 0, "password", KDF_BYTES)?,
910        &bytes_arg(args, 1, "salt", KDF_BYTES)?,
911        keylen,
912        opts_object(args, 3),
913    );
914    deliver_async(cb, res)
915}
916
917/// `hkdfSync(digest, ikm, salt, info, keylen)` and its callback form.
918fn hkdf(args: &[Value], cb: Option<Value>) -> Result<Value, String> {
919    let digest = arg_str(args, 0).to_ascii_lowercase();
920    let res = hkdf_derive(
921        &digest,
922        &bytes_arg(args, 1, "ikm", HKDF_IKM)?,
923        &bytes_arg(args, 2, "salt", HKDF_BYTES)?,
924        &bytes_arg(args, 3, "info", HKDF_BYTES)?,
925        super::arg_num(args, 4).max(0.0) as usize,
926    );
927    deliver_async(cb, res)
928}
929
930/// PBKDF2-HMAC derivation over a supported digest.
931fn pbkdf2_derive(
932    digest: &str,
933    pass: &[u8],
934    salt: &[u8],
935    iters: u32,
936    keylen: usize,
937) -> Result<Vec<u8>, String> {
938    let mut out = vec![0u8; keylen];
939    match digest {
940        "sha1" => pbkdf2::pbkdf2_hmac::<Sha1>(pass, salt, iters, &mut out),
941        "sha256" => pbkdf2::pbkdf2_hmac::<Sha256>(pass, salt, iters, &mut out),
942        "sha512" => pbkdf2::pbkdf2_hmac::<Sha512>(pass, salt, iters, &mut out),
943        "md5" => pbkdf2::pbkdf2_hmac::<Md5>(pass, salt, iters, &mut out),
944        _ => {
945            return Err(crate::host::coded_error(
946                "TypeError",
947                "ERR_CRYPTO_INVALID_DIGEST",
948                &format!("Invalid digest: {digest}"),
949            ))
950        }
951    }
952    Ok(out)
953}
954
955/// scrypt derivation. Reads node's `N`/`cost`, `r`/`blockSize`, `p`/
956/// `parallelization` options (defaults 16384/8/1).
957fn scrypt_derive(
958    pass: &[u8],
959    salt: &[u8],
960    keylen: usize,
961    opts: Option<Value>,
962) -> Result<Vec<u8>, String> {
963    let (mut n, mut r, mut p) = (16384.0f64, 8.0f64, 1.0f64);
964    if let Some(o) = opts {
965        n = opt_num(&o, &["N", "cost"], n);
966        r = opt_num(&o, &["r", "blockSize"], r);
967        p = opt_num(&o, &["p", "parallelization"], p);
968    }
969    let n = n as u64;
970    if n < 2 || (n & (n - 1)) != 0 {
971        // Node names no parameter and the class is a RangeError.
972        return Err(crate::host::coded_error(
973            "RangeError",
974            "ERR_CRYPTO_INVALID_SCRYPT_PARAMS",
975            "Invalid scrypt params",
976        ));
977    }
978    let params = scrypt::Params::new(n.trailing_zeros() as u8, r as u32, p as u32, keylen)
979        .map_err(|e| format!("Error: {e}"))?;
980    let mut out = vec![0u8; keylen];
981    scrypt::scrypt(pass, salt, &params, &mut out).map_err(|e| format!("Error: {e}"))?;
982    Ok(out)
983}
984
985/// HKDF (extract + expand) over a supported digest.
986fn hkdf_derive(
987    digest: &str,
988    ikm: &[u8],
989    salt: &[u8],
990    info: &[u8],
991    keylen: usize,
992) -> Result<Vec<u8>, String> {
993    let mut out = vec![0u8; keylen];
994    let ok = match digest {
995        "sha1" => Hkdf::<Sha1>::new(Some(salt), ikm).expand(info, &mut out),
996        "sha256" => Hkdf::<Sha256>::new(Some(salt), ikm).expand(info, &mut out),
997        "sha512" => Hkdf::<Sha512>::new(Some(salt), ikm).expand(info, &mut out),
998        "md5" => Hkdf::<Md5>::new(Some(salt), ikm).expand(info, &mut out),
999        _ => {
1000            return Err(crate::host::coded_error(
1001                "TypeError",
1002                "ERR_CRYPTO_INVALID_DIGEST",
1003                &format!("Invalid digest: {digest}"),
1004            ))
1005        }
1006    };
1007    ok.map_err(|_| "Error: Invalid key length".to_string())?;
1008    Ok(out)
1009}
1010
1011/// Read the first present, finite numeric property among `keys` from an options
1012/// object, else `default`.
1013fn opt_num(obj: &Value, keys: &[&str], default: f64) -> f64 {
1014    with_host(|h| {
1015        if let Some(JsObj::Object(p)) = h.get(obj) {
1016            for k in keys {
1017                if let Some(v) = p.get(*k) {
1018                    let n = h.to_number(v);
1019                    if !n.is_nan() {
1020                        return n;
1021                    }
1022                }
1023            }
1024        }
1025        default
1026    })
1027}
1028
1029/// Build a `Cipheriv`/`Decipheriv` instance object from `(algo, key, iv)`.
1030fn make_cipher(tag: &str, args: &[Value]) -> Result<Value, String> {
1031    let algo = arg_str(args, 0).to_ascii_lowercase();
1032    if !CIPHERS.contains(&algo.as_str()) {
1033        // Node names no algorithm here and the code is what callers branch on.
1034        // This appended the name and carried no code at all.
1035        return Err(crate::host::coded_error(
1036            "Error",
1037            "ERR_CRYPTO_UNKNOWN_CIPHER",
1038            "Unknown cipher",
1039        ));
1040    }
1041    let key = val_bytes_at(args, 1);
1042    let iv = val_bytes_at(args, 2);
1043    let want_key = key_len(&algo);
1044    // A wrong key length is a RangeError and a wrong IV a TypeError — the class
1045    // is part of what `catch` dispatches on, and both were plain `Error`s.
1046    if key.len() != want_key {
1047        return Err(crate::host::coded_error(
1048            "RangeError",
1049            "ERR_CRYPTO_INVALID_KEYLEN",
1050            "Invalid key length",
1051        ));
1052    }
1053    if iv.len() != 16 {
1054        return Err(crate::host::coded_error(
1055            "TypeError",
1056            "ERR_CRYPTO_INVALID_IV",
1057            "Invalid initialization vector",
1058        ));
1059    }
1060    Ok(with_host(|h| {
1061        let keyv = h.new_array(key.iter().map(|b| Value::Float(*b as f64)).collect());
1062        let ivv = h.new_array(iv.iter().map(|b| Value::Float(*b as f64)).collect());
1063        let data = h.new_array(Vec::new());
1064        let mut m = IndexMap::new();
1065        m.insert("@@native".into(), h.new_str(tag));
1066        m.insert("@@algo".into(), h.new_str(algo));
1067        m.insert("@@key".into(), keyv);
1068        m.insert("@@iv".into(), ivv);
1069        m.insert("@@data".into(), data);
1070        h.new_object(m)
1071    }))
1072}
1073
1074/// Cipher `update` input: a Buffer's bytes, else the string decoded by the input
1075/// encoding (arg 1, default utf8).
1076/// AES-CBC (Pkcs7) / AES-CTR transform. `encrypt` selects direction (CTR is
1077/// symmetric so the flag is unused there).
1078fn cipher_crypt(
1079    algo: &str,
1080    key: &[u8],
1081    iv: &[u8],
1082    data: &[u8],
1083    encrypt: bool,
1084) -> Result<Vec<u8>, String> {
1085    let keyerr = || {
1086        crate::host::coded_error(
1087            "RangeError",
1088            "ERR_CRYPTO_INVALID_KEYLEN",
1089            "Invalid key length",
1090        )
1091    };
1092    // OpenSSL's own message, under the code node reports for it.
1093    let decerr = || {
1094        crate::host::coded_error(
1095            "Error",
1096            "ERR_OSSL_BAD_DECRYPT",
1097            "error:1C800064:Provider routines::bad decrypt",
1098        )
1099    };
1100    match (algo, encrypt) {
1101        ("aes-128-cbc", true) => Ok(cbc::Encryptor::<aes::Aes128>::new_from_slices(key, iv)
1102            .map_err(|_| keyerr())?
1103            .encrypt_padded_vec_mut::<Pkcs7>(data)),
1104        ("aes-192-cbc", true) => Ok(cbc::Encryptor::<aes::Aes192>::new_from_slices(key, iv)
1105            .map_err(|_| keyerr())?
1106            .encrypt_padded_vec_mut::<Pkcs7>(data)),
1107        ("aes-256-cbc", true) => Ok(cbc::Encryptor::<aes::Aes256>::new_from_slices(key, iv)
1108            .map_err(|_| keyerr())?
1109            .encrypt_padded_vec_mut::<Pkcs7>(data)),
1110        ("aes-128-cbc", false) => cbc::Decryptor::<aes::Aes128>::new_from_slices(key, iv)
1111            .map_err(|_| keyerr())?
1112            .decrypt_padded_vec_mut::<Pkcs7>(data)
1113            .map_err(|_| decerr()),
1114        ("aes-192-cbc", false) => cbc::Decryptor::<aes::Aes192>::new_from_slices(key, iv)
1115            .map_err(|_| keyerr())?
1116            .decrypt_padded_vec_mut::<Pkcs7>(data)
1117            .map_err(|_| decerr()),
1118        ("aes-256-cbc", false) => cbc::Decryptor::<aes::Aes256>::new_from_slices(key, iv)
1119            .map_err(|_| keyerr())?
1120            .decrypt_padded_vec_mut::<Pkcs7>(data)
1121            .map_err(|_| decerr()),
1122        ("aes-128-ctr", _) => {
1123            let mut buf = data.to_vec();
1124            ctr::Ctr128BE::<aes::Aes128>::new_from_slices(key, iv)
1125                .map_err(|_| keyerr())?
1126                .apply_keystream(&mut buf);
1127            Ok(buf)
1128        }
1129        ("aes-192-ctr", _) => {
1130            let mut buf = data.to_vec();
1131            ctr::Ctr128BE::<aes::Aes192>::new_from_slices(key, iv)
1132                .map_err(|_| keyerr())?
1133                .apply_keystream(&mut buf);
1134            Ok(buf)
1135        }
1136        ("aes-256-ctr", _) => {
1137            let mut buf = data.to_vec();
1138            ctr::Ctr128BE::<aes::Aes256>::new_from_slices(key, iv)
1139                .map_err(|_| keyerr())?
1140                .apply_keystream(&mut buf);
1141            Ok(buf)
1142        }
1143        _ => Err(format!("Error: Unsupported cipher: {algo}")),
1144    }
1145}
1146
1147/// Required key length in bytes for a supported cipher name.
1148fn key_len(algo: &str) -> usize {
1149    if algo.starts_with("aes-128") {
1150        16
1151    } else if algo.starts_with("aes-192") {
1152        24
1153    } else {
1154        32
1155    }
1156}
1157
1158/// Encode bytes for a cipher `update`/`final` (or one-shot `hash`) output.
1159fn encode_out(bytes: &[u8], enc: Option<&str>) -> Value {
1160    match enc {
1161        Some("hex") => with_host(|h| h.new_str(to_hex(bytes))),
1162        Some("base64") | Some("base64url") => with_host(|h| h.new_str(to_base64(bytes))),
1163        Some("latin1") | Some("binary") => {
1164            with_host(|h| h.new_str(bytes.iter().map(|b| *b as char).collect::<String>()))
1165        }
1166        Some("utf8") | Some("utf-8") => {
1167            with_host(|h| h.new_str(String::from_utf8_lossy(bytes).into_owned()))
1168        }
1169        _ => super::buffer::from_bytes(bytes),
1170    }
1171}
1172
1173/// `getCipherInfo(name)` → `{ name, nid, blockSize, ivLength, mode, keyLength }`.
1174fn cipher_info(algo: &str) -> Result<Value, String> {
1175    if !CIPHERS.contains(&algo) {
1176        return Ok(Value::Undef);
1177    }
1178    let nid = match algo {
1179        "aes-128-cbc" => 419,
1180        "aes-192-cbc" => 423,
1181        "aes-256-cbc" => 427,
1182        "aes-128-ctr" => 904,
1183        "aes-192-ctr" => 905,
1184        _ => 906,
1185    };
1186    let (mode, block) = if algo.ends_with("ctr") {
1187        ("ctr", 1)
1188    } else {
1189        ("cbc", 16)
1190    };
1191    Ok(with_host(|h| {
1192        let mut m = IndexMap::new();
1193        m.insert("mode".into(), h.new_str(mode));
1194        m.insert("name".into(), h.new_str(algo));
1195        m.insert("nid".into(), Value::Float(nid as f64));
1196        m.insert("keyLength".into(), Value::Float(key_len(algo) as f64));
1197        m.insert("blockSize".into(), Value::Float(block as f64));
1198        m.insert("ivLength".into(), Value::Float(16.0));
1199        h.new_object(m)
1200    }))
1201}
1202
1203/// `randomFill`: [`random_fill`], then the callback with `(null, buf)`.
1204fn random_fill_async(args: &[Value]) -> Result<Value, String> {
1205    let buf = args.first().cloned().unwrap_or(Value::Undef);
1206    fill_element_size(&buf)?;
1207    let callable = |i: usize| {
1208        args.get(i)
1209            .filter(|v| with_host(|h| is_callable(h, v)))
1210            .cloned()
1211    };
1212    let (cb, n) = match (callable(1), callable(2)) {
1213        (Some(cb), _) => (cb, 1),
1214        (None, Some(cb)) => (cb, 2),
1215        (None, None) => {
1216            let cb = args.get(3).cloned().unwrap_or(Value::Undef);
1217            if !with_host(|h| is_callable(h, &cb)) {
1218                return Err(crate::host::invalid_arg_type(
1219                    "callback", "argument", "function", &cb,
1220                ));
1221            }
1222            (cb, 3)
1223        }
1224    };
1225    let filled = random_fill(&args[..n])?;
1226    with_host(|h| {
1227        let nullv = h.null();
1228        h.queue_io_callback(cb, vec![nullv, filled]);
1229    });
1230    Ok(Value::Undef)
1231}
1232
1233/// The `BYTES_PER_ELEMENT` `randomFill`'s `offset`/`size` are scaled by — 1 for
1234/// a Buffer, `DataView` or `ArrayBuffer` — or `ERR_INVALID_ARG_TYPE` when `buf`
1235/// is not a buffer at all.
1236fn fill_element_size(buf: &Value) -> Result<usize, String> {
1237    match super::native_tag(buf).as_deref() {
1238        Some("TypedArray") => Ok(super::util_types::ta_kind(buf)
1239            .map(|k| crate::stdlib::typedarray::bytes_per_element(&k))
1240            .unwrap_or(1)),
1241        Some("Buffer" | "DataView" | "ArrayBuffer") => Ok(1),
1242        _ => Err(crate::host::coded_error(
1243            "TypeError",
1244            "ERR_INVALID_ARG_TYPE",
1245            &format!(
1246                "The \"buf\" argument must be an instance of ArrayBuffer or ArrayBufferView. Received {}",
1247                super::received_desc(buf)
1248            ),
1249        )),
1250    }
1251}
1252
1253/// `randomFillSync`/`randomFill` core, a port of `lib/internal/crypto/random.js`:
1254/// `buf` is any `ArrayBuffer` or view, and `offset`/`size` count ELEMENTS of
1255/// it (scaled by `BYTES_PER_ELEMENT`, so a `Uint32Array`'s `offset` of 1 is
1256/// byte 4). The bytes are written through the view, so the memory it aliases
1257/// sees them. Only a Buffer was accepted before, and the bounds were clamped
1258/// instead of validated.
1259fn random_fill(args: &[Value]) -> Result<Value, String> {
1260    let buf = args.first().cloned().unwrap_or(Value::Undef);
1261    let elem = fill_element_size(&buf)?;
1262    let mut out = super::buffer::view_bytes(&buf).unwrap_or_default();
1263    let len = out.len() as f64;
1264    // `validateNumber` then the scaled range check, as `assertOffset` /
1265    // `assertSize` do; the rejection reports the SCALED value.
1266    let scaled = |i: usize, name: &str| -> Result<Option<f64>, String> {
1267        match args.get(i) {
1268            None | Some(Value::Undef) => Ok(None),
1269            Some(v) if with_host(|h| h.type_of(v)) != "number" => {
1270                Err(crate::host::invalid_arg_type(name, "argument", "number", v))
1271            }
1272            Some(v) => Ok(Some(with_host(|h| h.to_number(v)) * elem as f64)),
1273        }
1274    };
1275    let out_of_range = |name: &str, must: String, n: f64| {
1276        crate::host::coded_error(
1277            "RangeError",
1278            "ERR_OUT_OF_RANGE",
1279            &format!(
1280                "The value of \"{name}\" is out of range. It must be {must}. Received {}",
1281                crate::host::fmt_number(n)
1282            ),
1283        )
1284    };
1285    let offset = scaled(1, "offset")?.unwrap_or(0.0);
1286    if offset.is_nan() || !(0.0..=len).contains(&offset) {
1287        return Err(out_of_range("offset", format!(">= 0 && <= {len}"), offset));
1288    }
1289    let offset = offset.trunc();
1290    let size = match scaled(2, "size")? {
1291        None => len - offset,
1292        Some(size) => {
1293            const MAX_POSSIBLE_LENGTH: f64 = 2_147_483_647.0;
1294            if size.is_nan() || !(0.0..=MAX_POSSIBLE_LENGTH).contains(&size) {
1295                return Err(out_of_range(
1296                    "size",
1297                    format!(
1298                        ">= 0 && <= {}",
1299                        crate::host::fmt_number(MAX_POSSIBLE_LENGTH)
1300                    ),
1301                    size,
1302                ));
1303            }
1304            if size + offset > len {
1305                return Err(out_of_range(
1306                    "size + offset",
1307                    format!("<= {len}"),
1308                    size + offset,
1309                ));
1310            }
1311            size.trunc()
1312        }
1313    };
1314    let (start, end) = (offset as usize, (offset + size) as usize);
1315    if let Err(e) = getrandom::getrandom(&mut out[start..end]) {
1316        return Err(format!("Error: failed to generate random bytes: {e}"));
1317    }
1318    super::buffer::write_view(&buf, &out);
1319    Ok(buf)
1320}
1321
1322/// `randomUUIDv7()` — RFC 9562 v7: 48-bit unix-ms timestamp prefix, version 7,
1323/// variant, and CSPRNG tail.
1324fn uuid_v7() -> Result<Value, String> {
1325    let ms = std::time::SystemTime::now()
1326        .duration_since(std::time::UNIX_EPOCH)
1327        .map(|d| d.as_millis() as u64)
1328        .unwrap_or(0);
1329    let mut b = [0u8; 16];
1330    if let Err(e) = getrandom::getrandom(&mut b) {
1331        return Err(format!("Error: failed to generate random bytes: {e}"));
1332    }
1333    b[0..6].copy_from_slice(&ms.to_be_bytes()[2..8]);
1334    b[6] = (b[6] & 0x0f) | 0x70;
1335    b[8] = (b[8] & 0x3f) | 0x80;
1336    let h = to_hex(&b);
1337    let uuid = format!(
1338        "{}-{}-{}-{}-{}",
1339        &h[0..8],
1340        &h[8..12],
1341        &h[12..16],
1342        &h[16..20],
1343        &h[20..32]
1344    );
1345    Ok(with_host(|host| host.new_str(uuid)))
1346}
1347
1348/// A uniform random `u64` in `[0, range)` via rejection sampling over 8 CSPRNG
1349/// bytes (discards the biased tail so the distribution stays exactly uniform).
1350fn random_below(range: u64) -> Result<u64, getrandom::Error> {
1351    // Largest multiple of `range` that fits in u64; values at/above it are biased.
1352    let limit = u64::MAX - (u64::MAX % range);
1353    loop {
1354        let mut b = [0u8; 8];
1355        getrandom::getrandom(&mut b)?;
1356        let n = u64::from_le_bytes(b);
1357        if n < limit {
1358            return Ok(n % range);
1359        }
1360    }
1361}
1362
1363fn decode(s: &str, enc: &str) -> Vec<u8> {
1364    match enc.to_ascii_lowercase().as_str() {
1365        "hex" => super::from_hex(s),
1366        "base64" | "base64url" => super::from_base64(s),
1367        "ascii" | "latin1" | "binary" => s.chars().map(|c| c as u8).collect(),
1368        _ => s.as_bytes().to_vec(),
1369    }
1370}
1371
1372// ════════════════════════════════════════════════════════════════════════
1373//  Asymmetric cryptography: key generation, KeyObjects, sign/verify, RSA
1374//  encryption, Diffie-Hellman / ECDH, primes, argon2, X.509.
1375// ════════════════════════════════════════════════════════════════════════
1376
1377/// A key object for an asymmetric key: carries `type` (`private`/`public`),
1378/// `asymmetricKeyType`, and the PEM material in the hidden `@@pem`.
1379///
1380/// The class is the LEAF one node hands back — `PublicKeyObject` or
1381/// `PrivateKeyObject` — so the chain reaches `asymmetricKeyType` where node
1382/// keeps it. Both values are read through prototype getters, which is why they
1383/// live in hidden slots rather than as own enumerable properties.
1384fn key_object(kind: &str, asym: &str, pem: &str) -> Value {
1385    let class = if kind == "private" {
1386        "PrivateKeyObject"
1387    } else {
1388        "PublicKeyObject"
1389    };
1390    with_host(|h| {
1391        let mut m = IndexMap::new();
1392        m.insert("@@native".into(), h.new_str(class));
1393        m.insert("@@type".into(), h.new_str(kind));
1394        m.insert("@@asymmetricKeyType".into(), h.new_str(asym));
1395        m.insert("@@pem".into(), h.new_str(pem));
1396        h.new_object(m)
1397    })
1398}
1399
1400/// Whether `v` is any of the key-object classes.
1401fn is_key_object(v: &Value) -> bool {
1402    matches!(
1403        super::native_tag(v).as_deref(),
1404        Some("KeyObject" | "SecretKeyObject" | "PublicKeyObject" | "PrivateKeyObject")
1405    )
1406}
1407
1408/// A secret (symmetric) `KeyObject` wrapping raw bytes.
1409fn secret_key_object(bytes: &[u8]) -> Value {
1410    with_host(|h| {
1411        let arr = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
1412        let mut m = IndexMap::new();
1413        m.insert("@@native".into(), h.new_str("SecretKeyObject"));
1414        m.insert("@@type".into(), h.new_str("secret"));
1415        m.insert("@@secret".into(), arr);
1416        h.new_object(m)
1417    })
1418}
1419
1420/// Wrap DER bytes as a PEM block with the given label (64-char lines, LF).
1421fn pem_wrap(label: &str, der: &[u8]) -> String {
1422    let b64 = to_base64(der);
1423    let mut s = format!("-----BEGIN {label}-----\n");
1424    for chunk in b64.as_bytes().chunks(64) {
1425        s.push_str(std::str::from_utf8(chunk).unwrap_or_default());
1426        s.push('\n');
1427    }
1428    s.push_str(&format!("-----END {label}-----\n"));
1429    s
1430}
1431
1432/// Extract the DER bytes from a single PEM block (any label).
1433fn pem_body(pem: &str) -> Vec<u8> {
1434    let body: String = pem.lines().filter(|l| !l.starts_with("-----")).collect();
1435    super::from_base64(&body)
1436}
1437
1438/// PKCS#8 PEM for a raw X25519 private key (OID 1.3.101.110).
1439fn x25519_private_pem(raw: &[u8]) -> String {
1440    let mut der = vec![
1441        0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04,
1442        0x20,
1443    ];
1444    der.extend_from_slice(raw);
1445    pem_wrap("PRIVATE KEY", &der)
1446}
1447
1448/// SPKI PEM for a raw X25519 public key.
1449fn x25519_public_pem(raw: &[u8]) -> String {
1450    let mut der = vec![
1451        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x03, 0x21, 0x00,
1452    ];
1453    der.extend_from_slice(raw);
1454    pem_wrap("PUBLIC KEY", &der)
1455}
1456
1457/// The trailing 32 raw bytes of an X25519 PKCS#8/SPKI PEM.
1458fn x25519_raw(pem: &str) -> Option<[u8; 32]> {
1459    let der = pem_body(pem);
1460    if der.len() < 32 {
1461        return None;
1462    }
1463    let mut out = [0u8; 32];
1464    out.copy_from_slice(&der[der.len() - 32..]);
1465    Some(out)
1466}
1467
1468/// The options object at `args[1]` for key generation.
1469fn keygen_encoding(opts: Option<&Value>, priv_side: bool) -> Option<String> {
1470    let o = opts?;
1471    let field = if priv_side {
1472        "privateKeyEncoding"
1473    } else {
1474        "publicKeyEncoding"
1475    };
1476    with_host(|h| {
1477        let JsObj::Object(p) = h.get(o)? else {
1478            return None;
1479        };
1480        let enc = p.get(field)?;
1481        let JsObj::Object(e) = h.get(enc)? else {
1482            return None;
1483        };
1484        e.get("format").map(|v| h.str_of(v))
1485    })
1486}
1487
1488/// `generateKeyPairSync(type, opts)`: RSA / EC (P-256, P-384) / Ed25519 / X25519.
1489/// Returns `{ publicKey, privateKey }` — PEM strings when the matching
1490/// `*KeyEncoding.format` is `'pem'`, else `KeyObject`s.
1491fn generate_key_pair(kind: &str, opts: Option<&Value>) -> Result<Value, String> {
1492    let mut rng = rand_core::OsRng;
1493    let (asym, priv_pem, pub_pem) = match kind {
1494        "rsa" => {
1495            let bits = opt_num(opts.unwrap_or(&Value::Undef), &["modulusLength"], 2048.0) as usize;
1496            let sk = rsa::RsaPrivateKey::new(&mut rng, bits).map_err(|e| format!("Error: {e}"))?;
1497            let pk = rsa::RsaPublicKey::from(&sk);
1498            let priv_pem = sk
1499                .to_pkcs8_pem(LineEnding::LF)
1500                .map_err(|e| format!("Error: {e}"))?
1501                .to_string();
1502            let pub_pem = pk
1503                .to_public_key_pem(LineEnding::LF)
1504                .map_err(|e| format!("Error: {e}"))?;
1505            ("rsa", priv_pem, pub_pem)
1506        }
1507        "ec" => {
1508            let curve = opt_str(opts.unwrap_or(&Value::Undef), "namedCurve");
1509            match ec_curve_id(&curve) {
1510                Some("p256") => {
1511                    let sk = p256::SecretKey::random(&mut rng);
1512                    let priv_pem = sk
1513                        .to_pkcs8_pem(LineEnding::LF)
1514                        .map_err(|e| format!("Error: {e}"))?
1515                        .to_string();
1516                    let pub_pem = sk
1517                        .public_key()
1518                        .to_public_key_pem(LineEnding::LF)
1519                        .map_err(|e| format!("Error: {e}"))?;
1520                    ("ec", priv_pem, pub_pem)
1521                }
1522                Some("p384") => {
1523                    let sk = p384::SecretKey::random(&mut rng);
1524                    let priv_pem = sk
1525                        .to_pkcs8_pem(LineEnding::LF)
1526                        .map_err(|e| format!("Error: {e}"))?
1527                        .to_string();
1528                    let pub_pem = sk
1529                        .public_key()
1530                        .to_public_key_pem(LineEnding::LF)
1531                        .map_err(|e| format!("Error: {e}"))?;
1532                    ("ec", priv_pem, pub_pem)
1533                }
1534                _ => return Err(format!("Error: Unsupported EC curve: {curve}")),
1535            }
1536        }
1537        "ed25519" => {
1538            let sk = ed25519_dalek::SigningKey::generate(&mut rng);
1539            let priv_pem = sk
1540                .to_pkcs8_pem(LineEnding::LF)
1541                .map_err(|e| format!("Error: {e}"))?
1542                .to_string();
1543            let pub_pem = sk
1544                .verifying_key()
1545                .to_public_key_pem(LineEnding::LF)
1546                .map_err(|e| format!("Error: {e}"))?;
1547            ("ed25519", priv_pem, pub_pem)
1548        }
1549        "x25519" => {
1550            let sk = x25519_dalek::StaticSecret::random_from_rng(rng);
1551            let pk = x25519_dalek::PublicKey::from(&sk);
1552            (
1553                "x25519",
1554                x25519_private_pem(&sk.to_bytes()),
1555                x25519_public_pem(pk.as_bytes()),
1556            )
1557        }
1558        _ => return Err(format!("Error: Unsupported key type: {kind}")),
1559    };
1560    let pub_is_pem = keygen_encoding(opts, false).as_deref() == Some("pem");
1561    let priv_is_pem = keygen_encoding(opts, true).as_deref() == Some("pem");
1562    let publik = if pub_is_pem {
1563        with_host(|h| h.new_str(pub_pem.clone()))
1564    } else {
1565        key_object("public", asym, &pub_pem)
1566    };
1567    let privat = if priv_is_pem {
1568        with_host(|h| h.new_str(priv_pem.clone()))
1569    } else {
1570        key_object("private", asym, &priv_pem)
1571    };
1572    Ok(with_host(|h| {
1573        let mut m = IndexMap::new();
1574        m.insert("publicKey".into(), publik);
1575        m.insert("privateKey".into(), privat);
1576        h.new_object(m)
1577    }))
1578}
1579
1580/// Map a Node EC curve name to an internal id.
1581fn ec_curve_id(name: &str) -> Option<&'static str> {
1582    match name {
1583        "P-256" | "prime256v1" | "secp256r1" => Some("p256"),
1584        "P-384" | "secp384r1" => Some("p384"),
1585        _ => None,
1586    }
1587}
1588
1589/// A string option on an options object (empty if absent).
1590fn opt_str(obj: &Value, key: &str) -> String {
1591    with_host(|h| match h.get(obj) {
1592        Some(JsObj::Object(p)) => p.get(key).map(|v| h.str_of(v)).unwrap_or_default(),
1593        _ => String::new(),
1594    })
1595}
1596
1597/// Detect the asymmetric type of a private-key PEM/DER by trial parsing.
1598fn detect_private(bytes: &[u8]) -> Option<&'static str> {
1599    let pem = std::str::from_utf8(bytes).ok();
1600    if pem
1601        .map(|p| {
1602            rsa::RsaPrivateKey::from_pkcs8_pem(p).is_ok()
1603                || rsa::RsaPrivateKey::from_pkcs1_pem(p).is_ok()
1604        })
1605        .unwrap_or(false)
1606        || rsa::RsaPrivateKey::from_pkcs8_der(bytes).is_ok()
1607    {
1608        return Some("rsa");
1609    }
1610    if pem
1611        .map(|p| p256::SecretKey::from_pkcs8_pem(p).is_ok())
1612        .unwrap_or(false)
1613    {
1614        return Some("ec");
1615    }
1616    if pem
1617        .map(|p| p384::SecretKey::from_pkcs8_pem(p).is_ok())
1618        .unwrap_or(false)
1619    {
1620        return Some("ec");
1621    }
1622    if pem
1623        .map(|p| ed25519_dalek::SigningKey::from_pkcs8_pem(p).is_ok())
1624        .unwrap_or(false)
1625    {
1626        return Some("ed25519");
1627    }
1628    if pem.map(|p| p.contains("PRIVATE KEY")).unwrap_or(false)
1629        && x25519_raw(pem.unwrap_or("")).is_some()
1630    {
1631        // X25519 PKCS#8 is a fixed 48-byte structure; distinguish by OID byte.
1632        let der = pem_body(pem.unwrap_or(""));
1633        if der.len() == 48 && der[9..12] == [0x2b, 0x65, 0x6e] {
1634            return Some("x25519");
1635        }
1636    }
1637    None
1638}
1639
1640/// Detect the asymmetric type of a public-key PEM/DER by trial parsing.
1641fn detect_public(bytes: &[u8]) -> Option<&'static str> {
1642    let pem = std::str::from_utf8(bytes).ok();
1643    if pem
1644        .map(|p| rsa::RsaPublicKey::from_public_key_pem(p).is_ok())
1645        .unwrap_or(false)
1646    {
1647        return Some("rsa");
1648    }
1649    if pem
1650        .map(|p| p256::PublicKey::from_public_key_pem(p).is_ok())
1651        .unwrap_or(false)
1652    {
1653        return Some("ec");
1654    }
1655    if pem
1656        .map(|p| p384::PublicKey::from_public_key_pem(p).is_ok())
1657        .unwrap_or(false)
1658    {
1659        return Some("ec");
1660    }
1661    if pem
1662        .map(|p| ed25519_dalek::VerifyingKey::from_public_key_pem(p).is_ok())
1663        .unwrap_or(false)
1664    {
1665        return Some("ed25519");
1666    }
1667    if let Some(p) = pem {
1668        let der = pem_body(p);
1669        if der.len() == 44 && der[6..9] == [0x2b, 0x65, 0x6e] {
1670            return Some("x25519");
1671        }
1672    }
1673    None
1674}
1675
1676/// `createPrivateKey(input)` → a private `KeyObject`.
1677fn create_private_key(input: Option<&Value>) -> Result<Value, String> {
1678    let bytes = input.map(key_material).unwrap_or_default();
1679    let asym = detect_private(&bytes).ok_or("Error: Failed to read private key")?;
1680    let pem = String::from_utf8_lossy(&bytes).into_owned();
1681    Ok(key_object("private", asym, &pem))
1682}
1683
1684/// `createPublicKey(input)` → a public `KeyObject`. Accepts a public key, a
1685/// private key/`KeyObject` (derives the public half), or a PEM/DER buffer.
1686fn create_public_key(input: Option<&Value>) -> Result<Value, String> {
1687    let bytes = input.map(key_material).unwrap_or_default();
1688    if let Some(asym) = detect_public(&bytes) {
1689        let pem = String::from_utf8_lossy(&bytes).into_owned();
1690        return Ok(key_object("public", asym, &pem));
1691    }
1692    // Derive the public key from a private key.
1693    if let Some(asym) = detect_private(&bytes) {
1694        let pem = public_pem_from_private(&bytes, asym)?;
1695        return Ok(key_object("public", asym, &pem));
1696    }
1697    Err("Error: Failed to read public key".into())
1698}
1699
1700/// The SPKI public PEM derived from a private-key PEM/DER of a known type.
1701fn public_pem_from_private(bytes: &[u8], asym: &str) -> Result<String, String> {
1702    let pem = std::str::from_utf8(bytes).ok();
1703    let err = || "Error: Failed to derive public key".to_string();
1704    match asym {
1705        "rsa" => {
1706            let sk = pem
1707                .and_then(|p| rsa::RsaPrivateKey::from_pkcs8_pem(p).ok())
1708                .or_else(|| rsa::RsaPrivateKey::from_pkcs8_der(bytes).ok())
1709                .ok_or_else(err)?;
1710            rsa::RsaPublicKey::from(&sk)
1711                .to_public_key_pem(LineEnding::LF)
1712                .map_err(|e| format!("Error: {e}"))
1713        }
1714        "ec" => {
1715            if let Some(sk) = pem.and_then(|p| p256::SecretKey::from_pkcs8_pem(p).ok()) {
1716                return sk
1717                    .public_key()
1718                    .to_public_key_pem(LineEnding::LF)
1719                    .map_err(|e| format!("Error: {e}"));
1720            }
1721            let sk = pem
1722                .and_then(|p| p384::SecretKey::from_pkcs8_pem(p).ok())
1723                .ok_or_else(err)?;
1724            sk.public_key()
1725                .to_public_key_pem(LineEnding::LF)
1726                .map_err(|e| format!("Error: {e}"))
1727        }
1728        "ed25519" => {
1729            let sk = pem
1730                .and_then(|p| ed25519_dalek::SigningKey::from_pkcs8_pem(p).ok())
1731                .ok_or_else(err)?;
1732            sk.verifying_key()
1733                .to_public_key_pem(LineEnding::LF)
1734                .map_err(|e| format!("Error: {e}"))
1735        }
1736        "x25519" => {
1737            let raw = pem.and_then(x25519_raw).ok_or_else(err)?;
1738            let sk = x25519_dalek::StaticSecret::from(raw);
1739            Ok(x25519_public_pem(
1740                x25519_dalek::PublicKey::from(&sk).as_bytes(),
1741            ))
1742        }
1743        _ => Err(err()),
1744    }
1745}
1746
1747/// Raw key material of a key argument: a `KeyObject`'s stored PEM, a `{ key }`
1748/// wrapper's inner key, a Buffer's bytes, or a PEM/DER string's bytes.
1749fn key_material(v: &Value) -> Vec<u8> {
1750    if is_key_object(v) {
1751        return with_host(|h| match h.get(v) {
1752            Some(JsObj::Object(p)) => p.get("@@pem").map(|s| h.str_of(s)).unwrap_or_default(),
1753            _ => String::new(),
1754        })
1755        .into_bytes();
1756    }
1757    if super::native_tag(v).as_deref() != Some("Buffer") {
1758        let inner = with_host(|h| match h.get(v) {
1759            Some(JsObj::Object(p)) => p.get("key").cloned(),
1760            _ => None,
1761        });
1762        if let Some(k) = inner {
1763            return key_material(&k);
1764        }
1765    }
1766    val_bytes(v)
1767}
1768
1769/// A `Sign`/`Verify` streaming instance (`update(...).sign(key)` /
1770/// `update(...).verify(key, sig)`).
1771fn new_sign_verify(tag: &str, algo: &str) -> Value {
1772    with_host(|h| {
1773        let data = h.new_array(Vec::new());
1774        let mut m = IndexMap::new();
1775        m.insert("@@native".into(), h.new_str(tag));
1776        m.insert("@@algo".into(), h.new_str(algo.to_ascii_lowercase()));
1777        m.insert("@@data".into(), data);
1778        h.new_object(m)
1779    })
1780}
1781
1782/// Normalize a Node signature-algorithm name to a bare digest (`sha256`).
1783fn digest_of(algo: &str) -> String {
1784    let a = algo.to_ascii_lowercase();
1785    let a = a.strip_prefix("rsa-").unwrap_or(&a);
1786    a.replace('-', "")
1787}
1788
1789/// One-shot asymmetric sign over `data` with a private key (auto key-type).
1790fn sign_data(key: &[u8], algo: &str, data: &[u8]) -> Result<Vec<u8>, String> {
1791    let pem = std::str::from_utf8(key).ok();
1792    let d = digest_of(algo);
1793    if let Some(sk) = pem
1794        .and_then(|p| rsa::RsaPrivateKey::from_pkcs8_pem(p).ok())
1795        .or_else(|| pem.and_then(|p| rsa::RsaPrivateKey::from_pkcs1_pem(p).ok()))
1796        .or_else(|| rsa::RsaPrivateKey::from_pkcs8_der(key).ok())
1797    {
1798        return rsa_sign(&sk, &d, data);
1799    }
1800    if let Some(sk) = pem.and_then(|p| p256::ecdsa::SigningKey::from_pkcs8_pem(p).ok()) {
1801        let sig: p256::ecdsa::Signature = sk.try_sign(data).map_err(|e| format!("Error: {e}"))?;
1802        return Ok(sig.to_der().as_bytes().to_vec());
1803    }
1804    if let Some(sk) = pem.and_then(|p| p384::ecdsa::SigningKey::from_pkcs8_pem(p).ok()) {
1805        let sig: p384::ecdsa::Signature = sk.try_sign(data).map_err(|e| format!("Error: {e}"))?;
1806        return Ok(sig.to_der().as_bytes().to_vec());
1807    }
1808    if let Some(sk) = pem.and_then(|p| ed25519_dalek::SigningKey::from_pkcs8_pem(p).ok()) {
1809        return Ok(sk.sign(data).to_bytes().to_vec());
1810    }
1811    Err("Error: Invalid or unsupported private key for signing".into())
1812}
1813
1814/// RSA PKCS#1 v1.5 signature over `data` for the selected digest.
1815fn rsa_sign(sk: &rsa::RsaPrivateKey, digest: &str, data: &[u8]) -> Result<Vec<u8>, String> {
1816    let sig = match digest {
1817        "sha256" => rsa::pkcs1v15::SigningKey::<Sha256>::new(sk.clone())
1818            .sign(data)
1819            .to_vec(),
1820        "sha384" => rsa::pkcs1v15::SigningKey::<Sha384>::new(sk.clone())
1821            .sign(data)
1822            .to_vec(),
1823        "sha512" => rsa::pkcs1v15::SigningKey::<Sha512>::new(sk.clone())
1824            .sign(data)
1825            .to_vec(),
1826        _ => {
1827            return Err(format!(
1828                "Error: Unsupported digest for RSA signing: {digest}"
1829            ))
1830        }
1831    };
1832    Ok(sig)
1833}
1834
1835/// One-shot asymmetric verify (auto key-type). ECDSA signatures are DER.
1836fn verify_data(key: &[u8], algo: &str, data: &[u8], sig: &[u8]) -> Result<bool, String> {
1837    let pem = std::str::from_utf8(key).ok();
1838    let d = digest_of(algo);
1839    if let Some(pk) = pem
1840        .and_then(|p| rsa::RsaPublicKey::from_public_key_pem(p).ok())
1841        .or_else(|| pem.and_then(|p| rsa::RsaPublicKey::from_pkcs1_pem(p).ok()))
1842        .or_else(|| {
1843            pem.and_then(|p| rsa::RsaPrivateKey::from_pkcs8_pem(p).ok())
1844                .map(|s| rsa::RsaPublicKey::from(&s))
1845        })
1846    {
1847        return rsa_verify(&pk, &d, data, sig);
1848    }
1849    if let Some(vk) = pem
1850        .and_then(|p| p256::ecdsa::VerifyingKey::from_public_key_pem(p).ok())
1851        .or_else(|| {
1852            pem.and_then(|p| p256::ecdsa::SigningKey::from_pkcs8_pem(p).ok())
1853                .map(|s| *s.verifying_key())
1854        })
1855    {
1856        let s = p256::ecdsa::Signature::from_der(sig).map_err(|e| format!("Error: {e}"))?;
1857        return Ok(vk.verify(data, &s).is_ok());
1858    }
1859    if let Some(vk) = pem
1860        .and_then(|p| p384::ecdsa::VerifyingKey::from_public_key_pem(p).ok())
1861        .or_else(|| {
1862            pem.and_then(|p| p384::ecdsa::SigningKey::from_pkcs8_pem(p).ok())
1863                .map(|s| *s.verifying_key())
1864        })
1865    {
1866        let s = p384::ecdsa::Signature::from_der(sig).map_err(|e| format!("Error: {e}"))?;
1867        return Ok(vk.verify(data, &s).is_ok());
1868    }
1869    if let Some(vk) = pem
1870        .and_then(|p| ed25519_dalek::VerifyingKey::from_public_key_pem(p).ok())
1871        .or_else(|| {
1872            pem.and_then(|p| ed25519_dalek::SigningKey::from_pkcs8_pem(p).ok())
1873                .map(|s| s.verifying_key())
1874        })
1875    {
1876        let s = ed25519_dalek::Signature::from_slice(sig).map_err(|e| format!("Error: {e}"))?;
1877        return Ok(vk.verify(data, &s).is_ok());
1878    }
1879    Err("Error: Invalid or unsupported public key for verifying".into())
1880}
1881
1882/// RSA PKCS#1 v1.5 verify for the selected digest.
1883fn rsa_verify(
1884    pk: &rsa::RsaPublicKey,
1885    digest: &str,
1886    data: &[u8],
1887    sig: &[u8],
1888) -> Result<bool, String> {
1889    let signature = match rsa::pkcs1v15::Signature::try_from(sig) {
1890        Ok(s) => s,
1891        Err(_) => return Ok(false),
1892    };
1893    let ok = match digest {
1894        "sha256" => rsa::pkcs1v15::VerifyingKey::<Sha256>::new(pk.clone())
1895            .verify(data, &signature)
1896            .is_ok(),
1897        "sha384" => rsa::pkcs1v15::VerifyingKey::<Sha384>::new(pk.clone())
1898            .verify(data, &signature)
1899            .is_ok(),
1900        "sha512" => rsa::pkcs1v15::VerifyingKey::<Sha512>::new(pk.clone())
1901            .verify(data, &signature)
1902            .is_ok(),
1903        _ => {
1904            return Err(format!(
1905                "Error: Unsupported digest for RSA verifying: {digest}"
1906            ))
1907        }
1908    };
1909    Ok(ok)
1910}
1911
1912/// `Sign`/`Verify` instance dispatch.
1913pub fn sign_verify_instance_call(
1914    tag: &str,
1915    recv: &Value,
1916    method: &str,
1917    args: &[Value],
1918) -> Result<Value, String> {
1919    match method {
1920        "update" => {
1921            let enc = if args.len() > 1 {
1922                arg_str(args, 1)
1923            } else {
1924                "utf8".into()
1925            };
1926            // Any byte-like VIEW is taken as bytes; only a STRING goes through
1927            // the encoding. The Buffer case alone was handled, so
1928            // `hash.update(new TextEncoder().encode(s))` — the standard way to
1929            // hash bytes — stringified the view and hashed
1930            // `"[object Object]"`.
1931            let bytes = update_bytes(args, &enc)?;
1932            with_host(|h| {
1933                if let Some(JsObj::Object(p)) = h.get(recv).cloned() {
1934                    if let Some(arr) = p.get("@@data").cloned() {
1935                        if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
1936                            items.extend(bytes.iter().map(|b| Value::Float(*b as f64)));
1937                        }
1938                    }
1939                }
1940            });
1941            Ok(recv.clone())
1942        }
1943        "sign" => {
1944            let (algo, data) = sign_verify_state(recv);
1945            let key = key_material(args.first().unwrap_or(&Value::Undef));
1946            let sig = sign_data(&key, &algo, &data)?;
1947            let out_enc = if args.len() > 1 {
1948                Some(arg_str(args, 1))
1949            } else {
1950                None
1951            };
1952            Ok(encode_out(&sig, out_enc.as_deref()))
1953        }
1954        "verify" => {
1955            let (algo, data) = sign_verify_state(recv);
1956            let key = key_material(args.first().unwrap_or(&Value::Undef));
1957            let sig = if args.len() > 2 {
1958                decode(&arg_str(args, 1), &arg_str(args, 2))
1959            } else {
1960                val_bytes_at(args, 1)
1961            };
1962            Ok(Value::Bool(verify_data(&key, &algo, &data, &sig)?))
1963        }
1964        _ => Err(crate::host::type_error(&format!(
1965            "{}.{method} is not a function",
1966            tag.to_ascii_lowercase()
1967        ))),
1968    }
1969}
1970
1971/// Read the `@@algo`/`@@data` of a `Sign`/`Verify` instance.
1972fn sign_verify_state(recv: &Value) -> (String, Vec<u8>) {
1973    with_host(|h| {
1974        let (mut algo, mut data) = (String::new(), Vec::new());
1975        if let Some(JsObj::Object(p)) = h.get(recv) {
1976            algo = p.get("@@algo").map(|v| h.str_of(v)).unwrap_or_default();
1977            if let Some(JsObj::Array(items)) = p.get("@@data").and_then(|v| h.get(v)) {
1978                data = items.iter().map(|v| h.to_number(v) as u8).collect();
1979            }
1980        }
1981        (algo, data)
1982    })
1983}
1984
1985/// Read the numeric `padding`/oaepHash options from a key argument object.
1986fn rsa_padding(v: &Value) -> (i64, String) {
1987    let padding = opt_num(v, &["padding"], 4.0) as i64; // RSA_PKCS1_OAEP_PADDING
1988    let oaep = {
1989        let h = opt_str(v, "oaepHash");
1990        if h.is_empty() {
1991            "sha1".to_string()
1992        } else {
1993            h.to_ascii_lowercase()
1994        }
1995    };
1996    (padding, oaep)
1997}
1998
1999/// Parse an RSA public key from PEM/DER (or derive from a private key).
2000fn parse_rsa_public(key: &[u8]) -> Result<rsa::RsaPublicKey, String> {
2001    let pem = std::str::from_utf8(key).ok();
2002    pem.and_then(|p| rsa::RsaPublicKey::from_public_key_pem(p).ok())
2003        .or_else(|| pem.and_then(|p| rsa::RsaPublicKey::from_pkcs1_pem(p).ok()))
2004        .or_else(|| rsa::RsaPublicKey::from_public_key_der(key).ok())
2005        .or_else(|| {
2006            pem.and_then(|p| rsa::RsaPrivateKey::from_pkcs8_pem(p).ok())
2007                .map(|s| rsa::RsaPublicKey::from(&s))
2008        })
2009        .ok_or_else(|| "Error: Failed to parse RSA public key".into())
2010}
2011
2012/// Parse an RSA private key from PEM/DER.
2013fn parse_rsa_private(key: &[u8]) -> Result<rsa::RsaPrivateKey, String> {
2014    let pem = std::str::from_utf8(key).ok();
2015    pem.and_then(|p| rsa::RsaPrivateKey::from_pkcs8_pem(p).ok())
2016        .or_else(|| pem.and_then(|p| rsa::RsaPrivateKey::from_pkcs1_pem(p).ok()))
2017        .or_else(|| rsa::RsaPrivateKey::from_pkcs8_der(key).ok())
2018        .ok_or_else(|| "Error: Failed to parse RSA private key".into())
2019}
2020
2021/// `publicEncrypt` / `privateDecrypt`: OAEP by default, PKCS#1 v1.5 when
2022/// `padding == RSA_PKCS1_PADDING (1)`.
2023fn rsa_public_op(args: &[Value], _public: bool, encrypt: bool) -> Result<Value, String> {
2024    let key_arg = args.first().cloned().unwrap_or(Value::Undef);
2025    let key = key_material(&key_arg);
2026    let (padding, oaep) = rsa_padding(&key_arg);
2027    let data = val_bytes_at(args, 1);
2028    let out = if encrypt {
2029        let pk = parse_rsa_public(&key)?;
2030        let mut rng = rand_core::OsRng;
2031        if padding == 1 {
2032            pk.encrypt(&mut rng, rsa::Pkcs1v15Encrypt, &data)
2033        } else if oaep == "sha256" {
2034            pk.encrypt(&mut rng, rsa::Oaep::new::<Sha256>(), &data)
2035        } else {
2036            pk.encrypt(&mut rng, rsa::Oaep::new::<Sha1>(), &data)
2037        }
2038        .map_err(|e| format!("Error: {e}"))?
2039    } else {
2040        let sk = parse_rsa_private(&key)?;
2041        if padding == 1 {
2042            sk.decrypt(rsa::Pkcs1v15Encrypt, &data)
2043        } else if oaep == "sha256" {
2044            sk.decrypt(rsa::Oaep::new::<Sha256>(), &data)
2045        } else {
2046            sk.decrypt(rsa::Oaep::new::<Sha1>(), &data)
2047        }
2048        .map_err(|e| format!("Error: {e}"))?
2049    };
2050    Ok(super::buffer::from_bytes(&out))
2051}
2052
2053/// `privateEncrypt`: raw RSA PKCS#1 v1.5 (type 1) block signed with the
2054/// private key.
2055fn rsa_private_encrypt(args: &[Value]) -> Result<Value, String> {
2056    let key = key_material(args.first().unwrap_or(&Value::Undef));
2057    let data = val_bytes_at(args, 1);
2058    let sk = parse_rsa_private(&key)?;
2059    let out = sk
2060        .sign(rsa::Pkcs1v15Sign::new_unprefixed(), &data)
2061        .map_err(|e| format!("Error: {e}"))?;
2062    Ok(super::buffer::from_bytes(&out))
2063}
2064
2065/// `publicDecrypt`: recover a `privateEncrypt` block via raw modular
2066/// exponentiation `s^e mod n`, then strip PKCS#1 type-1 padding.
2067fn rsa_public_decrypt(args: &[Value]) -> Result<Value, String> {
2068    use rsa::traits::PublicKeyParts;
2069    let key = key_material(args.first().unwrap_or(&Value::Undef));
2070    let ct = val_bytes_at(args, 1);
2071    let pk = parse_rsa_public(&key)?;
2072    let n = BigUint::from_bytes_be(&pk.n().to_bytes_be());
2073    let e = BigUint::from_bytes_be(&pk.e().to_bytes_be());
2074    let k = pk.n().to_bytes_be().len();
2075    let s = BigUint::from_bytes_be(&ct);
2076    let m = s.modpow(&e, &n);
2077    let mut em = m.to_bytes_be();
2078    while em.len() < k {
2079        em.insert(0, 0);
2080    }
2081    // EM = 0x00 0x01 0xFF..0xFF 0x00 || message
2082    if em.len() < 11 || em[0] != 0x00 || em[1] != 0x01 {
2083        return Err("Error: error:0200006E:rsa routines::padding check failed".into());
2084    }
2085    let sep = em[2..].iter().position(|&b| b == 0x00).map(|i| i + 2);
2086    match sep {
2087        Some(i) => Ok(super::buffer::from_bytes(&em[i + 1..])),
2088        None => Err("Error: error:0200006E:rsa routines::padding check failed".into()),
2089    }
2090}
2091
2092// ── Diffie-Hellman (finite-field) ───────────────────────────────────────
2093
2094/// RFC 2409/3526 MODP group primes (hex), generator 2.
2095const MODP_GROUPS: &[(&str, &str)] = &[
2096    ("modp1", MODP1),
2097    ("modp2", MODP2),
2098    ("modp5", MODP5),
2099    ("modp14", MODP14),
2100    ("modp15", MODP15),
2101    ("modp16", MODP16),
2102    ("modp17", MODP17),
2103    ("modp18", MODP18),
2104];
2105
2106/// Byte-array property of an object as raw bytes.
2107fn obj_bytes(recv: &Value, key: &str) -> Vec<u8> {
2108    with_host(|h| {
2109        if let Some(JsObj::Object(p)) = h.get(recv) {
2110            if let Some(JsObj::Array(it)) = p.get(key).and_then(|v| h.get(v)) {
2111                return it.iter().map(|v| h.to_number(v) as u8).collect();
2112            }
2113        }
2114        Vec::new()
2115    })
2116}
2117
2118/// Store raw bytes as a hidden byte-array property.
2119fn set_obj_bytes(recv: &Value, key: &str, bytes: &[u8]) {
2120    with_host(|h| {
2121        let arr = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
2122        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2123            p.insert(key.to_string(), arr);
2124        }
2125    });
2126}
2127
2128/// Build a `DiffieHellman` instance from a prime + generator.
2129fn dh_object(prime: &[u8], gen: &[u8]) -> Value {
2130    with_host(|h| {
2131        let pv = h.new_array(prime.iter().map(|b| Value::Float(*b as f64)).collect());
2132        let gv = h.new_array(gen.iter().map(|b| Value::Float(*b as f64)).collect());
2133        let mut m = IndexMap::new();
2134        m.insert("@@native".into(), h.new_str("DiffieHellman"));
2135        m.insert("@@prime".into(), pv);
2136        m.insert("@@gen".into(), gv);
2137        h.new_object(m)
2138    })
2139}
2140
2141/// `createDiffieHellman(primeLength)` or `createDiffieHellman(prime[, generator])`.
2142fn create_diffie_hellman(args: &[Value]) -> Result<Value, String> {
2143    // Numeric first arg → generate a prime of that bit length; generator 2.
2144    let first = args.first().cloned().unwrap_or(Value::Undef);
2145    if matches!(first, Value::Int(_) | Value::Float(_)) {
2146        let bits = super::arg_num(args, 0) as usize;
2147        let prime = gen_prime(bits)?;
2148        return Ok(dh_object(&prime.to_bytes_be(), &[2]));
2149    }
2150    let prime = val_bytes_at(args, 0);
2151    let gen = if args.len() > 1 {
2152        match args.get(1) {
2153            Some(Value::Int(_)) | Some(Value::Float(_)) => {
2154                let g = super::arg_num(args, 1) as u64;
2155                BigUint::from(g).to_bytes_be()
2156            }
2157            _ => val_bytes_at(args, 1),
2158        }
2159    } else {
2160        vec![2]
2161    };
2162    Ok(dh_object(&prime, &gen))
2163}
2164
2165/// `getDiffieHellman(group)` / `createDiffieHellmanGroup(group)`.
2166fn diffie_hellman_group(name: &str) -> Result<Value, String> {
2167    let hex = MODP_GROUPS
2168        .iter()
2169        .find(|(n, _)| *n == name)
2170        .map(|(_, h)| *h)
2171        .ok_or_else(|| format!("Error: Unknown group: {name}"))?;
2172    Ok(dh_object(&super::from_hex(hex), &[2]))
2173}
2174
2175/// `DiffieHellman` instance dispatch.
2176pub fn dh_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
2177    let enc = |args: &[Value], i: usize| -> Option<String> {
2178        if args.len() > i {
2179            let s = arg_str(args, i);
2180            if s.is_empty() {
2181                None
2182            } else {
2183                Some(s)
2184            }
2185        } else {
2186            None
2187        }
2188    };
2189    match method {
2190        "generateKeys" => {
2191            let p = BigUint::from_bytes_be(&obj_bytes(recv, "@@prime"));
2192            let g = BigUint::from_bytes_be(&obj_bytes(recv, "@@gen"));
2193            let priv_key = dh_random_priv(&p)?;
2194            let pub_key = g.modpow(&priv_key, &p);
2195            set_obj_bytes(recv, "@@priv", &priv_key.to_bytes_be());
2196            set_obj_bytes(recv, "@@pub", &pub_key.to_bytes_be());
2197            Ok(encode_out(&pub_key.to_bytes_be(), enc(args, 0).as_deref()))
2198        }
2199        "computeSecret" => {
2200            let other = if args.len() > 1
2201                && !arg_str(args, 1).is_empty()
2202                && !matches!(args.first(), Some(v) if super::native_tag(v).as_deref() == Some("Buffer"))
2203            {
2204                decode(&arg_str(args, 0), &arg_str(args, 1))
2205            } else {
2206                val_bytes_at(args, 0)
2207            };
2208            let p = BigUint::from_bytes_be(&obj_bytes(recv, "@@prime"));
2209            let priv_key = BigUint::from_bytes_be(&obj_bytes(recv, "@@priv"));
2210            let their_pub = BigUint::from_bytes_be(&other);
2211            let secret = their_pub.modpow(&priv_key, &p);
2212            let out_enc = if args.len() > 2 { enc(args, 2) } else { None };
2213            Ok(encode_out(&secret.to_bytes_be(), out_enc.as_deref()))
2214        }
2215        "getPrime" => Ok(encode_out(
2216            &obj_bytes(recv, "@@prime"),
2217            enc(args, 0).as_deref(),
2218        )),
2219        "getGenerator" => Ok(encode_out(
2220            &obj_bytes(recv, "@@gen"),
2221            enc(args, 0).as_deref(),
2222        )),
2223        "getPublicKey" => Ok(encode_out(
2224            &obj_bytes(recv, "@@pub"),
2225            enc(args, 0).as_deref(),
2226        )),
2227        "getPrivateKey" => Ok(encode_out(
2228            &obj_bytes(recv, "@@priv"),
2229            enc(args, 0).as_deref(),
2230        )),
2231        "setPublicKey" => {
2232            set_obj_bytes(recv, "@@pub", &val_bytes_at(args, 0));
2233            Ok(recv.clone())
2234        }
2235        "setPrivateKey" => {
2236            set_obj_bytes(recv, "@@priv", &val_bytes_at(args, 0));
2237            Ok(recv.clone())
2238        }
2239        _ => Err(crate::host::type_error(&format!(
2240            "dh.{method} is not a function"
2241        ))),
2242    }
2243}
2244
2245/// A random DH private exponent in `[2, p-2]`.
2246fn dh_random_priv(p: &BigUint) -> Result<BigUint, String> {
2247    let nbytes = p.to_bytes_be().len();
2248    let mut buf = vec![0u8; nbytes];
2249    getrandom::getrandom(&mut buf).map_err(|e| format!("Error: {e}"))?;
2250    let two = BigUint::from(2u32);
2251    let modulus = p - &two; // p-2 range size
2252    let x = BigUint::from_bytes_be(&buf) % &modulus;
2253    Ok(x + &two)
2254}
2255
2256// ── ECDH ────────────────────────────────────────────────────────────────
2257
2258/// `createECDH(curve)` — P-256 / P-384.
2259fn create_ecdh(curve: &str) -> Result<Value, String> {
2260    let id = ec_curve_id(curve).ok_or_else(|| format!("Error: Unsupported curve: {curve}"))?;
2261    Ok(with_host(|h| {
2262        let mut m = IndexMap::new();
2263        m.insert("@@native".into(), h.new_str("ECDH"));
2264        m.insert("@@curve".into(), h.new_str(id));
2265        h.new_object(m)
2266    }))
2267}
2268
2269/// `ECDH` instance dispatch.
2270pub fn ecdh_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
2271    let curve = obj_str(recv, "@@curve");
2272    match method {
2273        "generateKeys" => {
2274            let (priv_b, pub_b) = ecdh_generate(&curve)?;
2275            set_obj_bytes(recv, "@@priv", &priv_b);
2276            set_obj_bytes(recv, "@@pub", &pub_b);
2277            let out_enc = if args.len() > 1 {
2278                Some(arg_str(args, 1))
2279            } else {
2280                None
2281            };
2282            Ok(encode_out(&pub_b, out_enc.as_deref()))
2283        }
2284        "computeSecret" => {
2285            let other = if args.len() > 1
2286                && !arg_str(args, 1).is_empty()
2287                && super::native_tag(args.first().unwrap_or(&Value::Undef)).as_deref()
2288                    != Some("Buffer")
2289            {
2290                decode(&arg_str(args, 0), &arg_str(args, 1))
2291            } else {
2292                val_bytes_at(args, 0)
2293            };
2294            let secret = ecdh_compute(&curve, &obj_bytes(recv, "@@priv"), &other)?;
2295            let out_enc = if args.len() > 2 {
2296                Some(arg_str(args, 2))
2297            } else {
2298                None
2299            };
2300            Ok(encode_out(&secret, out_enc.as_deref()))
2301        }
2302        "getPublicKey" => {
2303            let out_enc = if args.len() > 1 {
2304                Some(arg_str(args, 1))
2305            } else {
2306                None
2307            };
2308            Ok(encode_out(&obj_bytes(recv, "@@pub"), out_enc.as_deref()))
2309        }
2310        "getPrivateKey" => {
2311            let out_enc = if !args.is_empty() {
2312                Some(arg_str(args, 0))
2313            } else {
2314                None
2315            };
2316            Ok(encode_out(&obj_bytes(recv, "@@priv"), out_enc.as_deref()))
2317        }
2318        "setPrivateKey" => {
2319            let priv_b = val_bytes_at(args, 0);
2320            let pub_b = ecdh_public_from_private(&curve, &priv_b)?;
2321            set_obj_bytes(recv, "@@priv", &priv_b);
2322            set_obj_bytes(recv, "@@pub", &pub_b);
2323            Ok(recv.clone())
2324        }
2325        _ => Err(crate::host::type_error(&format!(
2326            "ecdh.{method} is not a function"
2327        ))),
2328    }
2329}
2330
2331/// Generate an ECDH keypair; public key is the uncompressed SEC1 point.
2332fn ecdh_generate(curve: &str) -> Result<(Vec<u8>, Vec<u8>), String> {
2333    let mut rng = rand_core::OsRng;
2334    match curve {
2335        "p256" => {
2336            let sk = p256::SecretKey::random(&mut rng);
2337            let pubk = sk.public_key().to_encoded_point(false).as_bytes().to_vec();
2338            Ok((sk.to_bytes().to_vec(), pubk))
2339        }
2340        "p384" => {
2341            let sk = p384::SecretKey::random(&mut rng);
2342            let pubk = sk.public_key().to_encoded_point(false).as_bytes().to_vec();
2343            Ok((sk.to_bytes().to_vec(), pubk))
2344        }
2345        _ => Err(format!("Error: Unsupported curve: {curve}")),
2346    }
2347}
2348
2349/// The uncompressed SEC1 public point for a raw ECDH private scalar.
2350fn ecdh_public_from_private(curve: &str, priv_b: &[u8]) -> Result<Vec<u8>, String> {
2351    match curve {
2352        "p256" => {
2353            let sk = p256::SecretKey::from_slice(priv_b).map_err(|e| format!("Error: {e}"))?;
2354            Ok(sk.public_key().to_encoded_point(false).as_bytes().to_vec())
2355        }
2356        "p384" => {
2357            let sk = p384::SecretKey::from_slice(priv_b).map_err(|e| format!("Error: {e}"))?;
2358            Ok(sk.public_key().to_encoded_point(false).as_bytes().to_vec())
2359        }
2360        _ => Err(format!("Error: Unsupported curve: {curve}")),
2361    }
2362}
2363
2364/// ECDH shared secret (raw X coordinate) from a private scalar + peer point.
2365fn ecdh_compute(curve: &str, priv_b: &[u8], pub_b: &[u8]) -> Result<Vec<u8>, String> {
2366    match curve {
2367        "p256" => {
2368            let sk = p256::SecretKey::from_slice(priv_b).map_err(|e| format!("Error: {e}"))?;
2369            let pk = p256::PublicKey::from_sec1_bytes(pub_b).map_err(|e| format!("Error: {e}"))?;
2370            let shared = p256::ecdh::diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
2371            Ok(shared.raw_secret_bytes().to_vec())
2372        }
2373        "p384" => {
2374            let sk = p384::SecretKey::from_slice(priv_b).map_err(|e| format!("Error: {e}"))?;
2375            let pk = p384::PublicKey::from_sec1_bytes(pub_b).map_err(|e| format!("Error: {e}"))?;
2376            let shared = p384::ecdh::diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
2377            Ok(shared.raw_secret_bytes().to_vec())
2378        }
2379        _ => Err(format!("Error: Unsupported curve: {curve}")),
2380    }
2381}
2382
2383/// String property helper.
2384fn obj_str(recv: &Value, key: &str) -> String {
2385    with_host(|h| match h.get(recv) {
2386        Some(JsObj::Object(p)) => p.get(key).map(|v| h.str_of(v)).unwrap_or_default(),
2387        _ => String::new(),
2388    })
2389}
2390
2391/// `crypto.diffieHellman({ privateKey, publicKey })` one-shot (EC / X25519).
2392fn diffie_hellman_oneshot(opts: Option<&Value>) -> Result<Value, String> {
2393    let o = opts.ok_or("Error: options object required")?;
2394    let priv_v = with_host(|h| match h.get(o) {
2395        Some(JsObj::Object(p)) => p.get("privateKey").cloned(),
2396        _ => None,
2397    })
2398    .ok_or("Error: privateKey required")?;
2399    let pub_v = with_host(|h| match h.get(o) {
2400        Some(JsObj::Object(p)) => p.get("publicKey").cloned(),
2401        _ => None,
2402    })
2403    .ok_or("Error: publicKey required")?;
2404    let priv_bytes = key_material(&priv_v);
2405    let pub_bytes = key_material(&pub_v);
2406    let asym = detect_private(&priv_bytes).ok_or("Error: unsupported private key")?;
2407    let priv_pem = std::str::from_utf8(&priv_bytes).ok();
2408    let pub_pem = std::str::from_utf8(&pub_bytes).ok();
2409    let secret = match asym {
2410        "ec" => {
2411            if let Some(sk) = priv_pem.and_then(|p| p256::SecretKey::from_pkcs8_pem(p).ok()) {
2412                let pk = pub_pem
2413                    .and_then(|p| p256::PublicKey::from_public_key_pem(p).ok())
2414                    .ok_or("Error: bad public key")?;
2415                p256::ecdh::diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine())
2416                    .raw_secret_bytes()
2417                    .to_vec()
2418            } else {
2419                let sk = priv_pem
2420                    .and_then(|p| p384::SecretKey::from_pkcs8_pem(p).ok())
2421                    .ok_or("Error: bad private key")?;
2422                let pk = pub_pem
2423                    .and_then(|p| p384::PublicKey::from_public_key_pem(p).ok())
2424                    .ok_or("Error: bad public key")?;
2425                p384::ecdh::diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine())
2426                    .raw_secret_bytes()
2427                    .to_vec()
2428            }
2429        }
2430        "x25519" => {
2431            let sraw = priv_pem
2432                .and_then(x25519_raw)
2433                .ok_or("Error: bad private key")?;
2434            let praw = pub_pem
2435                .and_then(x25519_raw)
2436                .ok_or("Error: bad public key")?;
2437            let sk = x25519_dalek::StaticSecret::from(sraw);
2438            let pk = x25519_dalek::PublicKey::from(praw);
2439            sk.diffie_hellman(&pk).as_bytes().to_vec()
2440        }
2441        _ => return Err("Error: diffieHellman requires EC or X25519 keys".into()),
2442    };
2443    Ok(super::buffer::from_bytes(&secret))
2444}
2445
2446// ── Primes ──────────────────────────────────────────────────────────────
2447
2448/// A key/number argument as a `BigUint` (BigInt, Buffer big-endian, or number).
2449fn arg_biguint(v: Option<&Value>) -> BigUint {
2450    let Some(v) = v else {
2451        return BigUint::from(0u32);
2452    };
2453    if let Some(b) = with_host(|h| match h.get(v) {
2454        Some(JsObj::BigInt(b)) => b.to_biguint(),
2455        _ => None,
2456    }) {
2457        return b;
2458    }
2459    if super::native_tag(v).as_deref() == Some("Buffer") {
2460        return BigUint::from_bytes_be(&val_bytes(v));
2461    }
2462    let n = with_host(|h| h.to_number(v));
2463    BigUint::from(n.max(0.0) as u64)
2464}
2465
2466/// `checkPrimeSync(candidate)` — probabilistic primality.
2467fn check_prime(v: Option<&Value>) -> bool {
2468    let n = arg_biguint(v);
2469    num_prime::nt_funcs::is_prime(&n, None).probably()
2470}
2471
2472/// `generatePrimeSync(size[, {bigint}])` — a random prime of `size` bits.
2473fn generate_prime(bits: usize, opts: Option<Value>) -> Result<Value, String> {
2474    let p = gen_prime(bits)?;
2475    let want_bigint = opts
2476        .map(|o| with_host(|h| matches!(h.get(&o), Some(JsObj::Object(m)) if m.get("bigint").map(|v| h.truthy(v)).unwrap_or(false))))
2477        .unwrap_or(false);
2478    if want_bigint {
2479        Ok(with_host(|h| {
2480            h.alloc(JsObj::BigInt(num_bigint::BigInt::from(p)))
2481        }))
2482    } else {
2483        // Node returns an ArrayBuffer; this runtime's ArrayBuffer carries no
2484        // backing bytes, so a Buffer (also a byte view) is returned instead.
2485        Ok(super::buffer::from_bytes(&p.to_bytes_be()))
2486    }
2487}
2488
2489/// A random probable prime of `bits` bits (top bit set, odd, then next_prime).
2490fn gen_prime(bits: usize) -> Result<BigUint, String> {
2491    if bits < 2 {
2492        return Err("Error: size must be >= 2".into());
2493    }
2494    let nbytes = bits.div_ceil(8);
2495    let mut buf = vec![0u8; nbytes];
2496    getrandom::getrandom(&mut buf).map_err(|e| format!("Error: {e}"))?;
2497    let excess = nbytes * 8 - bits;
2498    buf[0] &= 0xffu8 >> excess;
2499    buf[0] |= 0x80u8 >> excess;
2500    let last = nbytes - 1;
2501    buf[last] |= 1;
2502    let start = BigUint::from_bytes_be(&buf);
2503    num_prime::nt_funcs::next_prime(&start, None)
2504        .ok_or_else(|| "Error: prime generation failed".into())
2505}
2506
2507// ── argon2 ──────────────────────────────────────────────────────────────
2508
2509/// `argon2Sync(algorithm, options)` → raw tag bytes.
2510fn argon2_hash(algo: &str, opts: Option<&Value>) -> Result<Vec<u8>, String> {
2511    let o = opts.cloned().ok_or("Error: argon2 options required")?;
2512    let msg = prop_bytes(&o, "message");
2513    let salt = prop_bytes(&o, "nonce");
2514    let secret = prop_bytes(&o, "secret");
2515    let taglen = opt_num(&o, &["tagLength"], 32.0).max(4.0) as usize;
2516    let mem = opt_num(&o, &["memory"], 65536.0) as u32;
2517    let passes = opt_num(&o, &["passes"], 3.0) as u32;
2518    let par = opt_num(&o, &["parallelism"], 4.0) as u32;
2519    let algorithm = match algo.to_ascii_lowercase().as_str() {
2520        "argon2d" => argon2::Algorithm::Argon2d,
2521        "argon2i" => argon2::Algorithm::Argon2i,
2522        _ => argon2::Algorithm::Argon2id,
2523    };
2524    let params =
2525        argon2::Params::new(mem, passes, par, Some(taglen)).map_err(|e| format!("Error: {e}"))?;
2526    let ctx = if secret.is_empty() {
2527        argon2::Argon2::new(algorithm, argon2::Version::V0x13, params)
2528    } else {
2529        argon2::Argon2::new_with_secret(&secret, algorithm, argon2::Version::V0x13, params)
2530            .map_err(|e| format!("Error: {e}"))?
2531    };
2532    let mut out = vec![0u8; taglen];
2533    ctx.hash_password_into(&msg, &salt, &mut out)
2534        .map_err(|e| format!("Error: {e}"))?;
2535    Ok(out)
2536}
2537
2538/// The bytes of a Buffer/typed-array/string property of an object.
2539fn prop_bytes(obj: &Value, key: &str) -> Vec<u8> {
2540    let v = with_host(|h| match h.get(obj) {
2541        Some(JsObj::Object(p)) => p.get(key).cloned(),
2542        _ => None,
2543    });
2544    v.map(|x| val_bytes(&x)).unwrap_or_default()
2545}
2546
2547// ── WebCrypto getRandomValues ───────────────────────────────────────────
2548
2549/// `getRandomValues(typedArray)` — fill in place with CSPRNG bytes, return it.
2550fn get_random_values(v: Option<&Value>) -> Result<Value, String> {
2551    let ta = v
2552        .cloned()
2553        .ok_or("Error: argument must be an integer-type TypedArray")?;
2554    let tag = super::native_tag(&ta);
2555    if tag.as_deref() == Some("Buffer") {
2556        let len = val_bytes(&ta).len();
2557        let mut rnd = vec![0u8; len];
2558        getrandom::getrandom(&mut rnd).map_err(|e| format!("Error: {e}"))?;
2559        super::buffer::write_view(&ta, &rnd);
2560        return Ok(ta);
2561    }
2562    if tag.as_deref() != Some("TypedArray") {
2563        return Err("Error: argument must be an integer-type TypedArray".into());
2564    }
2565    let kind = obj_str(&ta, "@@kind");
2566    if kind.starts_with("Float") {
2567        return Err("Error: The provided ArrayBufferView is of type 'Float', which is not an integer array type".into());
2568    }
2569    let len = crate::stdlib::typedarray::index_len(&ta).unwrap_or(0);
2570    let bpe = match kind.as_str() {
2571        "Int16Array" | "Uint16Array" => 2,
2572        "Int32Array" | "Uint32Array" => 4,
2573        _ => 1,
2574    };
2575    let mut raw = vec![0u8; len * bpe];
2576    getrandom::getrandom(&mut raw).map_err(|e| format!("Error: {e}"))?;
2577    let elems: Vec<Value> = (0..len)
2578        .map(|i| {
2579            let mut acc: u64 = 0;
2580            for j in 0..bpe {
2581                acc |= (raw[i * bpe + j] as u64) << (8 * j);
2582            }
2583            Value::Float(ta_coerce(&kind, acc))
2584        })
2585        .collect();
2586    // Written through the view, so the bytes land in the backing ArrayBuffer
2587    // and every other view over it sees them.
2588    for (i, e) in elems.iter().enumerate() {
2589        crate::stdlib::typedarray::elem_set(&ta, &i.to_string(), e)?;
2590    }
2591    Ok(ta)
2592}
2593
2594/// Coerce a raw little-endian integer into a typed-array element value.
2595fn ta_coerce(kind: &str, raw: u64) -> f64 {
2596    match kind {
2597        "Int8Array" => (raw as i8) as f64,
2598        "Int16Array" => (raw as i16) as f64,
2599        "Int32Array" => (raw as i32) as f64,
2600        "Uint16Array" => (raw as u16) as f64,
2601        "Uint32Array" => (raw as u32) as f64,
2602        _ => (raw as u8) as f64, // Uint8Array / Uint8ClampedArray
2603    }
2604}
2605
2606// ── KeyObject instance methods ──────────────────────────────────────────
2607
2608/// `KeyObject` instance dispatch (`export({type,format})`, `equals`).
2609pub fn key_object_instance_call(
2610    recv: &Value,
2611    method: &str,
2612    args: &[Value],
2613) -> Result<Value, String> {
2614    match method {
2615        "export" => {
2616            // Secret key: raw bytes (Buffer) unless format 'jwk' (unsupported).
2617            let secret = obj_bytes(recv, "@@secret");
2618            if !secret.is_empty() {
2619                return Ok(super::buffer::from_bytes(&secret));
2620            }
2621            let pem = obj_str(recv, "@@pem");
2622            let format = args
2623                .first()
2624                .map(|o| opt_str(o, "format"))
2625                .filter(|s| !s.is_empty())
2626                .unwrap_or_else(|| "pem".into());
2627            if format == "der" {
2628                Ok(super::buffer::from_bytes(&pem_body(&pem)))
2629            } else {
2630                Ok(with_host(|h| h.new_str(pem)))
2631            }
2632        }
2633        "equals" => {
2634            let Some(other) = args.first() else {
2635                return Ok(Value::Bool(false));
2636            };
2637            // A SECRET key has no PEM, so comparing `@@pem` compared two empty
2638            // strings and every pair of secret keys was equal — including keys
2639            // built from different bytes. The comparison has to be over the same
2640            // material the key actually holds, and a key never equals one of a
2641            // different `type`.
2642            let kind = |v: &Value| obj_str(v, "@@type");
2643            if kind(recv) != kind(other) {
2644                return Ok(Value::Bool(false));
2645            }
2646            let mine = obj_bytes(recv, "@@secret");
2647            if !mine.is_empty() {
2648                return Ok(Value::Bool(mine == obj_bytes(other, "@@secret")));
2649            }
2650            Ok(Value::Bool(
2651                obj_str(recv, "@@pem") == obj_str(other, "@@pem"),
2652            ))
2653        }
2654        // `symmetricKeySize` is the secret's length in BYTES, and `undefined`
2655        // for an asymmetric key rather than zero.
2656        "@get@symmetricKeySize" => {
2657            let secret = obj_bytes(recv, "@@secret");
2658            Ok(if obj_str(recv, "@@type") == "secret" {
2659                Value::Float(secret.len() as f64)
2660            } else {
2661                Value::Undef
2662            })
2663        }
2664        _ => Err(crate::host::type_error(&format!(
2665            "keyObject.{method} is not a function"
2666        ))),
2667    }
2668}
2669
2670// ── X.509 certificates ──────────────────────────────────────────────────
2671
2672/// `new X509Certificate(pemOrDer)` → an `X509Certificate` instance.
2673pub fn construct_x509(args: &[Value]) -> Result<Value, String> {
2674    use x509_cert::der::{Decode, DecodePem, Encode};
2675    let bytes = val_bytes_at(args, 0);
2676    let is_pem = bytes.starts_with(b"-----BEGIN");
2677    let cert = if is_pem {
2678        x509_cert::Certificate::from_pem(&bytes).map_err(|e| format!("Error: {e}"))?
2679    } else {
2680        x509_cert::Certificate::from_der(&bytes).map_err(|e| format!("Error: {e}"))?
2681    };
2682    // The canonical DER (for fingerprint + raw).
2683    let der = cert.to_der().map_err(|e| format!("Error: {e}"))?;
2684    let fp = {
2685        let d = digest("sha1", &der);
2686        d.iter()
2687            .map(|b| format!("{b:02X}"))
2688            .collect::<Vec<_>>()
2689            .join(":")
2690    };
2691    let subject = x509_name_node(&cert.tbs_certificate.subject.to_string());
2692    let issuer = x509_name_node(&cert.tbs_certificate.issuer.to_string());
2693    let not_before = x509_time(&cert.tbs_certificate.validity.not_before);
2694    let not_after = x509_time(&cert.tbs_certificate.validity.not_after);
2695    let serial = cert
2696        .tbs_certificate
2697        .serial_number
2698        .as_bytes()
2699        .iter()
2700        .map(|b| format!("{b:02X}"))
2701        .collect::<String>();
2702    let spki_der = cert
2703        .tbs_certificate
2704        .subject_public_key_info
2705        .to_der()
2706        .map_err(|e| format!("Error: {e}"))?;
2707    let pub_pem = pem_wrap("PUBLIC KEY", &spki_der);
2708    let pub_key =
2709        create_public_key(Some(&with_host(|h| h.new_str(pub_pem)))).unwrap_or(Value::Undef);
2710    let cert_pem = pem_wrap("CERTIFICATE", &der);
2711    let raw = super::buffer::from_bytes(&der);
2712    Ok(with_host(|h| {
2713        let mut m = IndexMap::new();
2714        m.insert("@@native".into(), h.new_str("X509Certificate"));
2715        m.insert("subject".into(), h.new_str(subject));
2716        m.insert("issuer".into(), h.new_str(issuer));
2717        m.insert("validFrom".into(), h.new_str(not_before));
2718        m.insert("validTo".into(), h.new_str(not_after));
2719        m.insert("serialNumber".into(), h.new_str(serial));
2720        m.insert("fingerprint".into(), h.new_str(fp));
2721        m.insert("publicKey".into(), pub_key);
2722        m.insert("raw".into(), raw);
2723        m.insert("@@pem".into(), h.new_str(cert_pem));
2724        h.new_object(m)
2725    }))
2726}
2727
2728/// `X509Certificate` instance dispatch (`toString`, `toLegacyObject`).
2729pub fn x509_instance_call(recv: &Value, method: &str, _args: &[Value]) -> Result<Value, String> {
2730    match method {
2731        // Same nested-borrow hazard as `events::getEventListeners`: `obj_str`
2732        // takes the host, so reading it inside `with_host` aborts the process.
2733        "toString" => {
2734            let pem = obj_str(recv, "@@pem");
2735            Ok(with_host(|h| h.new_str(pem)))
2736        }
2737        _ => Err(crate::host::type_error(&format!(
2738            "x509Certificate.{method} is not a function"
2739        ))),
2740    }
2741}
2742
2743/// Convert an RFC 4514 name string ("O=Org,CN=Name") to Node's newline,
2744/// most-significant-last form ("CN=Name\nO=Org").
2745fn x509_name_node(rfc4514: &str) -> String {
2746    rfc4514
2747        .split(',')
2748        .map(|s| s.trim())
2749        .rev()
2750        .collect::<Vec<_>>()
2751        .join("\n")
2752}
2753
2754/// Render an X.509 time in OpenSSL's `%b %e %H:%M:%S %Y GMT` form.
2755fn x509_time(t: &x509_cert::time::Time) -> String {
2756    const MON: [&str; 12] = [
2757        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2758    ];
2759    let dt = t.to_date_time();
2760    let mon = MON
2761        .get(dt.month().saturating_sub(1) as usize)
2762        .copied()
2763        .unwrap_or("Jan");
2764    format!(
2765        "{} {:2} {:02}:{:02}:{:02} {} GMT",
2766        mon,
2767        dt.day(),
2768        dt.hour(),
2769        dt.minutes(),
2770        dt.seconds(),
2771        dt.year()
2772    )
2773}
2774
2775// RFC 2409/3526 MODP group primes (generator 2).
2776const MODP1: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF";
2777const MODP2: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF";
2778const MODP5: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF";
2779const MODP14: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF";
2780const MODP15: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
2781const MODP16: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF";
2782const MODP17: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF";
2783const MODP18: &str = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF";