micro509 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +130 -1
  2. package/dist/index.d.ts +2 -2
  3. package/dist/index.js +3 -3
  4. package/dist/internal/jose/base64url.js +40 -0
  5. package/dist/internal/jose/base64url.js.map +1 -0
  6. package/dist/internal/jose/strict-json.d.ts +9 -0
  7. package/dist/internal/jose/strict-json.js +155 -0
  8. package/dist/internal/jose/strict-json.js.map +1 -0
  9. package/dist/internal/verify/spki-distrust.js +23 -0
  10. package/dist/internal/verify/spki-distrust.js.map +1 -0
  11. package/dist/internal/verify/verify-path.js +77 -60
  12. package/dist/internal/verify/verify-path.js.map +1 -1
  13. package/dist/jose/errors.d.ts +44 -0
  14. package/dist/jose/errors.js +11 -0
  15. package/dist/jose/errors.js.map +1 -0
  16. package/dist/jose/jwks.d.ts +93 -0
  17. package/dist/jose/jwks.js +193 -0
  18. package/dist/jose/jwks.js.map +1 -0
  19. package/dist/jose/jws.d.ts +158 -0
  20. package/dist/jose/jws.js +362 -0
  21. package/dist/jose/jws.js.map +1 -0
  22. package/dist/jose/jwt.d.ts +91 -0
  23. package/dist/jose/jwt.js +187 -0
  24. package/dist/jose/jwt.js.map +1 -0
  25. package/dist/jose/remote-jwks.d.ts +95 -0
  26. package/dist/jose/remote-jwks.js +298 -0
  27. package/dist/jose/remote-jwks.js.map +1 -0
  28. package/dist/jose.d.ts +7 -0
  29. package/dist/jose.js +5 -0
  30. package/dist/kdf/argon2.d.ts +78 -0
  31. package/dist/kdf/argon2.js +167 -0
  32. package/dist/kdf/argon2.js.map +1 -0
  33. package/dist/kdf.d.ts +2 -0
  34. package/dist/kdf.js +1 -0
  35. package/dist/keys/keys.d.ts +11 -8
  36. package/dist/keys/keys.js.map +1 -1
  37. package/dist/revocation/crl.js +2 -7
  38. package/dist/revocation/crl.js.map +1 -1
  39. package/dist/ssh/ssh.d.ts +200 -0
  40. package/dist/ssh/ssh.js +648 -0
  41. package/dist/ssh/ssh.js.map +1 -0
  42. package/dist/ssh/wire.d.ts +3 -0
  43. package/dist/ssh/wire.js +105 -0
  44. package/dist/ssh/wire.js.map +1 -0
  45. package/dist/ssh.d.ts +3 -0
  46. package/dist/ssh.js +1 -0
  47. package/dist/verify/verify.d.ts +32 -1
  48. package/dist/verify/verify.js +100 -58
  49. package/dist/verify/verify.js.map +1 -1
  50. package/dist/x509/fingerprint.d.ts +11 -0
  51. package/dist/x509/fingerprint.js +19 -1
  52. package/dist/x509/fingerprint.js.map +1 -1
  53. package/dist/x509.d.ts +2 -2
  54. package/dist/x509.js +3 -3
  55. package/package.json +20 -6
@@ -1 +1 @@
1
- {"version":3,"file":"keys.js","names":["_exhaustive","subtle","getCrypto","usages","algorithm","generated","publicKey","pemEncode","privateKey","pkcs8","encryption","encryptPbes2","options","sequence","octetString","parsed","OIDS","usage","privateJwk","key","base64Encode","parsedSpki","der","importInput","successResult","run","error","rethrowIfInvariant","decodeFailureResult","DECODE_LIMIT_CODES","isWrongPasswordError","failureResult","isKdfIterationLimitError","pemDecodeOrThrow","pem","decoded","base64Decode","base64","parsedPrivateKey","rethrowDecodeRefusal","declaredPublicKey","spki","subjectPublicKey","readSequenceChildren","derived","declared","byte","index","password","createKdfBudget","envelope","decrypted","decryptPbes2","budget","children","algorithmIdentifier","encryptedData","parsePbes2AlgorithmIdentifier","parsedSec1","jwk","keyProblem","toArrayBuffer","plaintext","ciphertext","wrongPasswordError","message","version","child","versionValue","otherPrimeInfos","element","otherPrimeInfosDer","source","infos","info","fields","field","algorithmDer","algorithmChildren","algorithmOid","parameters","oid","decodeObjectIdentifier","CURVE_PRIVATE_KEY_ALGORITHM_OIDS","integer","readRootElement","content","seenAttributes","seenUnknown","tail","contextNumber","attributes","tlv","attribute","type","values","value","third","fourth","ecParameters","sec1Der","curveOid","explicitContext","objectIdentifier","nullValue","curve","publicJwk","EC_CURVE_OIDS","name","scheme","operation","iv","cipher","encrypted","body","label","toHex","parseTraditionalPemOrThrow","expectedLabel","dekInfo","procType","ivHex","trimLwsp","hexToBytes","keyLength","keyBytes","salt","passwordBytes","chunks","previous","total","length","input","md5","out","offset","chunk","slice","unsupportedMessage","alg"],"sources":["../../src/keys/keys.ts"],"sourcesContent":["/**\n * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.\n *\n * Supports RSA (PKCS#1v1.5, PSS, and OAEP), ECDSA (P-256, P-384, P-521), and Ed25519 keys.\n * All functions use the WebCrypto API and return extractable keys.\n *\n * @example\n * ```ts\n * import { unwrap } from 'micro509';\n * import { generateKeyPair, exportSpkiPem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const publicPem = await exportSpkiPem(keys.publicKey);\n *\n * // Import — Result-returning; unwrap() throws on failure\n * const publicKey = unwrap(await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' }));\n * ```\n *\n * @module\n */\n\nimport {\n\tdecodeObjectIdentifier,\n\textractBitStringValue,\n\thexToBytes,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_LIMIT_CODES,\n\tdecodeFailureResult,\n\trethrowDecodeRefusal,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\texplicitContext,\n\tinteger,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { md5 } from '#micro509/internal/crypto/hash';\nimport type { KdfBudget, KdfLimitOptions, Pbes2Parameters } from '#micro509/internal/crypto/pbes2';\nimport {\n\tcreateKdfBudget,\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisKdfIterationLimitError,\n\tisWrongPasswordError,\n\tparsePbes2AlgorithmIdentifier,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport {\n\tparseTraditionalPemOrThrow,\n\tpemDecodeOrThrow,\n\tpemEncode,\n\ttrimLwsp,\n} from '#micro509/pem/pem';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\nexport type {\n\tKdfLimitOptions,\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Parameters,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2';\nexport { parsePbes2AlgorithmIdentifier } from '#micro509/internal/crypto/pbes2';\n\n/** Hash algorithm paired with an RSA key. */\nexport type RsaHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** RSA signature padding scheme. */\nexport type RsaSignatureScheme = 'pkcs1-v1_5' | 'pss';\n\n/**\n * RSA padding scheme: a signature scheme, or `'oaep'` for RSA-OAEP encryption\n * keys (usable with {@linkcode encryptRsaOaep} / {@linkcode decryptRsaOaep}).\n */\nexport type RsaScheme = RsaSignatureScheme | 'oaep';\n\n/** NIST elliptic curve for ECDSA keys. */\nexport type EcNamedCurve = 'P-256' | 'P-384' | 'P-521';\n\n/** RSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface RsaKeyAlgorithmInput {\n\t/** Discriminant selecting RSA key generation. */\n\treadonly kind: 'rsa';\n\t/** RSA modulus size in bits. Defaults to `2048`. */\n\treadonly modulusLength?: 2048 | 3072 | 4096;\n\t/** Hash algorithm for the key. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/**\n\t * Padding scheme. Defaults to `'pkcs1-v1_5'`. Pass `'oaep'` to generate an\n\t * RSA-OAEP encryption pair (`encrypt`/`decrypt` usages instead of `sign`/`verify`).\n\t */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface EcKeyAlgorithmInput {\n\t/** Discriminant selecting ECDSA key generation. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve. Defaults to `'P-256'`. */\n\treadonly curve?: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode KeyAlgorithmInput}. */\nexport interface Ed25519KeyAlgorithmInput {\n\t/** Discriminant selecting Ed25519 key generation. */\n\treadonly kind: 'ed25519';\n}\n\n/** Input for {@linkcode generateKeyPair}. Selects algorithm family and parameters. */\nexport type KeyAlgorithmInput =\n\t| RsaKeyAlgorithmInput\n\t| EcKeyAlgorithmInput\n\t| Ed25519KeyAlgorithmInput;\n\n/** Key pair with convenience export helpers. Returned by {@linkcode generateKeyPair}. */\nexport interface KeyPairMaterial {\n\t/** The WebCrypto public key (extractable, `verify` usage; `encrypt` for RSA-OAEP). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage; `decrypt` for RSA-OAEP). */\n\treadonly privateKey: CryptoKey;\n\t/** Export the public key as DER-encoded SubjectPublicKeyInfo. */\n\texportSpkiDer(): Promise<Uint8Array>;\n\t/** Export the public key as PEM-encoded SubjectPublicKeyInfo. */\n\texportSpkiPem(): Promise<string>;\n\t/** Export the private key as DER-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Der(): Promise<Uint8Array>;\n\t/** Export the private key as PEM-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Pem(): Promise<string>;\n\t/** Export the public key as a JSON Web Key. */\n\texportPublicJwk(): Promise<JsonWebKey>;\n\t/** Export the private key as a JSON Web Key. */\n\texportPrivateJwk(): Promise<JsonWebKey>;\n}\n\n/** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportRsaKeyInput {\n\t/** Discriminant selecting RSA import. */\n\treadonly kind: 'rsa';\n\t/** Hash algorithm. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/**\n\t * Padding scheme. Defaults to `'pkcs1-v1_5'`. Pass `'oaep'` to import an\n\t * RSA-OAEP encryption key (`encrypt`/`decrypt` usage instead of `verify`/`sign`).\n\t */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEcKeyInput {\n\t/** Discriminant selecting ECDSA import. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve the key belongs to. Required for EC import. */\n\treadonly curve: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEd25519KeyInput {\n\t/** Discriminant selecting Ed25519 import. */\n\treadonly kind: 'ed25519';\n}\n\n/** Algorithm descriptor for public key import functions. */\nexport type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\n/** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */\nexport type PrivateKeyImportInput = PublicKeyImportInput;\n\n/** PBES2 encryption options for the encrypted PKCS#8 export/import functions. */\nexport interface EncryptedPkcs8Options {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\t/** PBKDF2 pseudo-random function. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: 'HMAC-SHA-1' | 'HMAC-SHA-256';\n}\n\n/** Options for OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM encryption (PKCS#1/SEC1). */\nexport interface LegacyPemEncryptionOptions {\n\t/** Passphrase used to derive the encryption key. */\n\treadonly password: string;\n\t/** 16-byte initialization vector. Random when omitted. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Defaults to `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n}\n\n/**\n * Machine-readable failure reason for the `import*` key functions.\n *\n * `limit_exceeded` is an implementation limit: an OBJECT IDENTIFIER\n * sub-identifier encoded in more than 64 octets, a tag number of 2^53 or more,\n * or DER nested deeper than 64 levels.\n */\nexport type ImportKeyErrorCode = Exclude<DecodeFailureCode, 'unsupported'>;\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `import*` key functions.\n *\n * On failure, `code` is `'malformed'` for structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures alike (see the\n * throwing `*OrThrow` variants for raw error messages), and `'limit_exceeded'`\n * for an implementation limit.\n */\nexport type ImportKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>;\n\n/**\n * Machine-readable failure reason for the `importEncrypted*` key functions.\n *\n * Distinguishes a wrong decryption password (`'invalid_password'`) from\n * structurally invalid input or algorithm mismatches (`'malformed'`), from an\n * encoded KDF iteration count above the caller's limit\n * (`'kdf_iterations_exceeded'`), and from a decoding limit of micro509's own\n * (`'limit_exceeded'`, see {@linkcode ImportKeyErrorCode}).\n */\nexport type ImportEncryptedKeyErrorCode =\n\t| ImportKeyErrorCode\n\t| 'invalid_password'\n\t| 'kdf_iterations_exceeded';\n\n/** Options for the encrypted PKCS#8 import functions. */\nexport type ImportEncryptedKeyOptions = KdfLimitOptions;\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `importEncrypted*` key functions.\n *\n * On failure, `code` is `'invalid_password'` when decryption failed (wrong\n * password or corrupted ciphertext) and `'malformed'` for everything else.\n */\nexport type ImportEncryptedKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportEncryptedKeyErrorCode, Record<never, never>, ImportEncryptedKeyFailure>;\n\n/** Options shared by {@linkcode encryptRsaOaep} and {@linkcode decryptRsaOaep}. */\nexport interface RsaOaepOptions {\n\t/**\n\t * Optional OAEP label bound to the ciphertext. Not encrypted, but decryption\n\t * fails unless the exact same label is presented. Default: empty.\n\t */\n\treadonly label?: Uint8Array;\n}\n\n/**\n * Machine-readable failure reason for {@linkcode encryptRsaOaep}.\n *\n * `'invalid_key'` when the key is not an RSA-OAEP public key with `encrypt`\n * usage; `'message_too_long'` when the plaintext exceeds the OAEP capacity of\n * the key (modulus bytes − 2 × hash bytes − 2).\n */\nexport type EncryptRsaOaepErrorCode = 'invalid_key' | 'message_too_long';\n\n/** Structured failure payload for {@linkcode encryptRsaOaep}. */\nexport interface EncryptRsaOaepFailure extends Micro509Error<EncryptRsaOaepErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result returned by {@linkcode encryptRsaOaep}. */\nexport type EncryptRsaOaepResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<EncryptRsaOaepErrorCode, Record<never, never>, EncryptRsaOaepFailure>;\n\n/**\n * Machine-readable failure reason for {@linkcode decryptRsaOaep}.\n *\n * `'invalid_key'` when the key is not an RSA-OAEP private key with `decrypt`\n * usage; `'decryption_failed'` for every ciphertext-level failure (wrong key,\n * wrong label, tampered or truncated ciphertext) — OAEP deliberately does not\n * reveal which.\n */\nexport type DecryptRsaOaepErrorCode = 'invalid_key' | 'decryption_failed';\n\n/** Structured failure payload for {@linkcode decryptRsaOaep}. */\nexport interface DecryptRsaOaepFailure extends Micro509Error<DecryptRsaOaepErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result returned by {@linkcode decryptRsaOaep}. */\nexport type DecryptRsaOaepResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<DecryptRsaOaepErrorCode, Record<never, never>, DecryptRsaOaepFailure>;\n\n/**\n * Generate an asymmetric key pair for signing and verification, or — with\n * `{ kind: 'rsa', scheme: 'oaep' }` — for RSA-OAEP encryption and decryption.\n *\n * @example\n * ```ts\n * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });\n * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });\n * const edKeys = await generateKeyPair({ kind: 'ed25519' });\n * const oaepKeys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });\n *\n * // Default: ECDSA P-256\n * const keys = await generateKeyPair();\n * const pem = await keys.exportPkcs8Pem();\n * ```\n */\nexport async function generateKeyPair(\n\talgorithm: KeyAlgorithmInput = { kind: 'ecdsa', curve: 'P-256' },\n): Promise<KeyPairMaterial> {\n\tconst subtle = getCrypto().subtle;\n\tconst usages: KeyUsage[] = isRsaOaepInput(algorithm)\n\t\t? ['encrypt', 'decrypt']\n\t\t: ['sign', 'verify'];\n\tconst generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, usages);\n\n\tif (!('publicKey' in generated) || !('privateKey' in generated)) {\n\t\tthrow new Error('Expected an asymmetric key pair');\n\t}\n\n\treturn wrapKeyPair(generated.publicKey, generated.privateKey);\n}\n\nfunction wrapKeyPair(publicKey: CryptoKey, privateKey: CryptoKey): KeyPairMaterial {\n\treturn {\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tasync exportSpkiDer() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n\t\t},\n\t\tasync exportSpkiPem() {\n\t\t\treturn pemEncode('PUBLIC KEY', await this.exportSpkiDer());\n\t\t},\n\t\tasync exportPkcs8Der() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n\t\t},\n\t\tasync exportPkcs8Pem() {\n\t\t\treturn pemEncode('PRIVATE KEY', await this.exportPkcs8Der());\n\t\t},\n\t\texportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\texportPrivateJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n\t\t},\n\t};\n}\n\n/**\n * Export a public key as DER-encoded SubjectPublicKeyInfo.\n *\n * @see {@linkcode importSpkiDer} for the inverse operation\n * @see {@linkcode exportSpkiPem} for PEM output\n */\nexport async function exportSpkiDer(publicKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n}\n\n/**\n * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see {@linkcode importPkcs8Der} for the inverse operation\n * @see {@linkcode exportPkcs8Pem} for PEM output\n * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export\n */\nexport async function exportPkcs8Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n}\n\n/**\n * Export a public key as a JSON Web Key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const jwk = await exportPublicJwk(keys.publicKey);\n * ```\n */\nexport function exportPublicJwk(publicKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n}\n\n/**\n * Export a private key as a JSON Web Key.\n *\n * @see {@linkcode importPrivateJwk} for the inverse operation\n * @see {@linkcode exportPublicJwk} for public key export\n */\nexport function exportPrivateJwk(privateKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n}\n\n/**\n * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportPkcs8Pem(keys.privateKey);\n * // -----BEGIN PRIVATE KEY-----\n * // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...\n * // -----END PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importPkcs8Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export\n */\nexport async function exportPkcs8Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PRIVATE KEY', await exportPkcs8Der(privateKey));\n}\n\n/**\n * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.\n *\n * @param privateKey - The private key to export\n * @param options - Encryption options including password and optional algorithm settings\n *\n * @throws {RangeError} If `options.iterations` is not an integer from 1 to 4294967295\n *\n * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output\n */\nexport async function exportEncryptedPkcs8Der(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst encryption = await encryptPbes2(pkcs8, options);\n\treturn sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);\n}\n\n/**\n * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });\n * // -----BEGIN ENCRYPTED PRIVATE KEY-----\n * // MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...\n * // -----END ENCRYPTED PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs8Pem(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<string> {\n\treturn pemEncode('ENCRYPTED PRIVATE KEY', await exportEncryptedPkcs8Der(privateKey, options));\n}\n\n/**\n * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Der} for the inverse operation\n * @see {@linkcode exportPkcs1Pem} for PEM output\n */\nexport async function exportPkcs1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.rsaEncryption) {\n\t\tthrow new Error('PKCS#1 export requires an RSA private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export\n */\nexport async function exportPkcs1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('RSA PRIVATE KEY', await exportPkcs1Der(privateKey));\n}\n\n/**\n * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('RSA PRIVATE KEY', await exportPkcs1Der(privateKey), options);\n}\n\n/**\n * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * The output always carries the RFC 5915 `parameters [0]` named curve\n * (matching OpenSSL), so it re-imports via {@linkcode importSec1Der} without\n * an explicit curve.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Der} for the inverse operation\n * @see {@linkcode exportSec1Pem} for PEM output\n */\nexport async function exportSec1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.ecPublicKey) {\n\t\tthrow new Error('SEC1 export requires an EC private key');\n\t}\n\treturn ensureSec1NamedCurveParameters(parsed.privateKeyDer, parsed.parametersOid);\n}\n\n/**\n * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedSec1Pem} for password-protected export\n */\nexport async function exportSec1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('EC PRIVATE KEY', await exportSec1Der(privateKey));\n}\n\n/**\n * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importEncryptedSec1Pem} for the inverse operation\n */\nexport async function exportEncryptedSec1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('EC PRIVATE KEY', await exportSec1Der(privateKey), options);\n}\n\n/**\n * Export a public key as PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportSpkiPem(keys.publicKey);\n * ```\n */\nexport async function exportSpkiPem(publicKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PUBLIC KEY', await exportSpkiDer(publicKey));\n}\n\n/**\n * Derive the matching public key from an imported (or generated) private key.\n *\n * The `import*` functions that read a PKCS#8 / PKCS#1 / SEC 1 / JWK private key\n * return a bare `CryptoKey` with only `sign` (or, for RSA-OAEP, `decrypt`)\n * usage — there is no accompanying public handle. This bridges that gap: it\n * exports the private key's JWK, strips the private components, and re-imports\n * the public half with `verify` (RSA-OAEP: `encrypt`) usage, so callers can go\n * straight to {@linkcode exportSpkiDer} / {@linkcode exportSpkiPem} (e.g. to\n * rebuild a self-signed cert or distribute the public key when only the\n * private key is on disk).\n *\n * Supports RSA (`n`/`e`), ECDSA (`x`/`y`), and Ed25519 (`x`). The derived key\n * inherits the private key's algorithm parameters (hash, curve).\n *\n * @param privateKey - An extractable private `CryptoKey`\n * @returns Extractable public `CryptoKey` with `verify` (RSA-OAEP: `encrypt`) usage\n *\n * @throws {Error} If the key is not a private key, is non-extractable, or uses\n * an unsupported key type\n *\n * @example\n * ```ts\n * const privateKey = await importPkcs8PemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });\n * const publicKey = await derivePublicKey(privateKey);\n * const spkiPem = await exportSpkiPem(publicKey);\n * ```\n *\n * @see {@linkcode exportSpkiDer} for exporting the derived key\n */\nexport async function derivePublicKey(privateKey: CryptoKey): Promise<CryptoKey> {\n\tif (privateKey.type !== 'private') {\n\t\tthrow new Error('derivePublicKey requires a private CryptoKey');\n\t}\n\tif (!privateKey.extractable) {\n\t\tthrow new Error('Cannot derive public key from a non-extractable private key');\n\t}\n\tconst subtle = getCrypto().subtle;\n\tconst usage: KeyUsage = privateKey.algorithm.name === 'RSA-OAEP' ? 'encrypt' : 'verify';\n\tconst privateJwk = await subtle.exportKey('jwk', privateKey);\n\treturn subtle.importKey('jwk', toPublicJwk(privateJwk, usage), privateKey.algorithm, true, [\n\t\tusage,\n\t]);\n}\n\n/**\n * Export a key as raw base64 (no PEM headers).\n *\n * Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys.\n * Useful for compact storage or transmission where PEM overhead is undesirable.\n *\n * @throws {Error} If the key is a symmetric/secret key\n *\n * @see {@linkcode importSpkiBase64} for public key import\n * @see {@linkcode importPkcs8Base64} for private key import\n */\nexport async function exportBinaryBase64(key: CryptoKey): Promise<string> {\n\tif (key.type === 'public') {\n\t\treturn base64Encode(await exportSpkiDer(key));\n\t}\n\tif (key.type === 'private') {\n\t\treturn base64Encode(await exportPkcs8Der(key));\n\t}\n\tthrow new Error('Cannot export secret/symmetric CryptoKey');\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * When `algorithm` is omitted, the algorithm (and, for EC keys, the curve) is\n * inferred from the SPKI's own AlgorithmIdentifier — useful for keys whose type\n * isn't known ahead of time. Pass `algorithm` to additionally assert that the\n * DER matches an expected algorithm.\n *\n * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Optional expected algorithm; must match key contents when given\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`\n *\n * @see {@linkcode exportSpkiDer} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input\n */\nexport async function importSpkiDerOrThrow(\n\tder: Uint8Array,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst parsedSpki = parseSpkiDer(der);\n\tlet importInput: PublicKeyImportInput;\n\tif (algorithm === undefined) {\n\t\timportInput = inferKeyImportInput(parsedSpki, 'Unsupported SubjectPublicKeyInfo algorithm');\n\t} else {\n\t\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\t\timportInput = algorithm;\n\t}\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tpublicKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` or `'limit_exceeded'` result; invariants rethrow. */\nasync function importResult(run: () => Promise<CryptoKey>): Promise<ImportKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decodeFailureResult(error, DECODE_LIMIT_CODES, 'Malformed key');\n\t}\n}\n\n/** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */\nasync function encryptedImportResult(\n\trun: () => Promise<CryptoKey>,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn failureResult('invalid_password', error.message);\n\t\t}\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn failureResult('kdf_iterations_exceeded', error.message);\n\t\t}\n\t\treturn decodeFailureResult(error, DECODE_LIMIT_CODES, 'Malformed encrypted key');\n\t}\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiDerOrThrow` for the throwing variant\n */\nexport function importSpkiDer(\n\tder: Uint8Array,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiDerOrThrow(der, algorithm));\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const pem = `-----BEGIN PUBLIC KEY-----\n * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n * -----END PUBLIC KEY-----`;\n * const key = await importSpkiPemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport function importSpkiPemOrThrow(\n\tpem: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importSpkiDerOrThrow(pemDecodeOrThrow('PUBLIC KEY', pem), algorithm);\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiPemOrThrow` for the throwing variant\n */\nexport function importSpkiPem(\n\tpem: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiPemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input with headers\n */\nexport function importSpkiBase64OrThrow(\n\tbase64: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 SubjectPublicKeyInfo');\n\t}\n\treturn importSpkiDerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see `importSpkiBase64OrThrow` for the throwing variant\n */\nexport function importSpkiBase64(\n\tbase64: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiBase64OrThrow(base64, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * When `algorithm` is omitted, the algorithm (and, for EC keys, the curve) is\n * inferred from the PrivateKeyInfo's own `privateKeyAlgorithm` — useful for\n * keys whose type isn't known ahead of time. Pass `algorithm` to additionally\n * assert that the DER matches an expected algorithm.\n *\n * An RFC 5958 v2 `OneAsymmetricKey` carrying `attributes [0]` or `publicKey [1]`\n * is reduced to its v1 fields for the platform import, which Bun 1.3.14 and\n * earlier rejects outright\n * ([oven-sh/bun#35432](https://github.com/oven-sh/bun/issues/35432)). A\n * `publicKey [1]` field is checked against the private key it accompanies.\n *\n * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Optional expected algorithm; must match key contents when given\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed, encodes an unsupported algorithm, doesn't match `algorithm`, or carries a `publicKey [1]` that is not the private key's own\n *\n * @see {@linkcode exportPkcs8Der} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input\n * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8\n */\nexport async function importPkcs8DerOrThrow(\n\tder: Uint8Array,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet parsedPrivateKey: ReturnType<typeof parsePkcs8PrivateKey>;\n\ttry {\n\t\tparsedPrivateKey = parsePkcs8PrivateKey(der);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tlet importInput: PrivateKeyImportInput;\n\tif (algorithm === undefined) {\n\t\timportInput = inferKeyImportInput(parsedPrivateKey, 'Unsupported PKCS#8 private key algorithm');\n\t} else {\n\t\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\t\timportInput = algorithm;\n\t}\n\tlet privateKey: CryptoKey;\n\ttry {\n\t\tprivateKey = await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(parsedPrivateKey.v1Der),\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tprivateKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst declaredPublicKey = parsedPrivateKey.declaredPublicKey;\n\tif (declaredPublicKey !== undefined) {\n\t\tawait assertDeclaredPublicKeyMatches(privateKey, declaredPublicKey);\n\t}\n\treturn privateKey;\n}\n\n/**\n * Reject a OneAsymmetricKey whose `publicKey [1]` field is not the public key of\n * its own `privateKey`.\n *\n * RFC 8410 Appendix A: \"Key mismatch errors: If a public key is provided, it may\n * not agree with the private key because either it is wrong or the wrong\n * algorithm was used.\"\n */\nasync function assertDeclaredPublicKeyMatches(\n\tprivateKey: CryptoKey,\n\tdeclared: Uint8Array,\n): Promise<void> {\n\tconst spki = await exportSpkiDer(await derivePublicKey(privateKey));\n\tconst subjectPublicKey = readSequenceChildren(spki)[1];\n\tif (subjectPublicKey === undefined || subjectPublicKey.tag !== 0x03) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst derived = subjectPublicKey.value.slice(1);\n\tif (\n\t\tderived.length !== declared.length ||\n\t\tderived.some((byte, index) => byte !== declared[index])\n\t) {\n\t\tthrow new Error('PKCS#8 publicKey does not match the private key');\n\t}\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8DerOrThrow` for the throwing variant\n */\nexport function importPkcs8Der(\n\tder: Uint8Array,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8DerOrThrow(der, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * When `algorithm` is omitted, it is inferred from the key's own\n * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).\n *\n * @example\n * ```ts\n * const key = await importPkcs8PemOrThrow(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * const inferred = await importPkcs8PemOrThrow(pemString);\n * ```\n */\nexport function importPkcs8PemOrThrow(\n\tpem: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(pemDecodeOrThrow('PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8PemOrThrow` for the throwing variant\n */\nexport function importPkcs8Pem(\n\tpem: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Decrypts the PBES2 envelope using the provided password, then imports the key.\n *\n * When `algorithm` is omitted, it is inferred from the decrypted key's own\n * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).\n *\n * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Optional expected algorithm; must match decrypted key when given\n * @param options - KDF work-factor limit\n *\n * @throws {Error} If DER is malformed, password is wrong, the PBKDF2 iteration\n * count exceeds `options.maxKdfIterations`, or algorithm doesn't match\n *\n * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation\n */\nexport async function importEncryptedPkcs8DerOrThrow(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<CryptoKey> {\n\treturn await importEncryptedPkcs8WithBudget(der, password, algorithm, createKdfBudget(options));\n}\n\nasync function importEncryptedPkcs8WithBudget(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput | undefined,\n\tbudget: KdfBudget,\n): Promise<CryptoKey> {\n\tconst envelope = readEncryptedPkcs8Envelope(der);\n\tconst decrypted = await decryptPbes2(\n\t\tenvelope.algorithmIdentifierDer,\n\t\tenvelope.encryptedData,\n\t\tpassword,\n\t\tbudget,\n\t);\n\tassertDecryptedPrivateKey(\n\t\t() => parsePkcs8PrivateKey(decrypted),\n\t\t'Invalid password or encrypted content',\n\t);\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\n}\n\n/** Splits a DER `EncryptedPrivateKeyInfo` into its AlgorithmIdentifier DER and encryptedData bytes. */\nfunction readEncryptedPkcs8Envelope(der: Uint8Array): {\n\treadonly algorithmIdentifierDer: Uint8Array;\n\treadonly encryptedData: Uint8Array;\n} {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst algorithmIdentifier = children[0];\n\tconst encryptedData = children[1];\n\tif (\n\t\tchildren.length !== 2 ||\n\t\talgorithmIdentifier === undefined ||\n\t\tencryptedData === undefined ||\n\t\tencryptedData.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\treturn {\n\t\talgorithmIdentifierDer: der.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData: encryptedData.value,\n\t};\n}\n\n/**\n * Reads the PBES2 encryption parameters of a DER PKCS#8\n * `EncryptedPrivateKeyInfo` (RFC 5958 §3) without the password: PBKDF2\n * iteration count, salt, and PRF, plus the AES-CBC variant and IV.\n * Throws on malformed DER, a non-PBES2 encryption algorithm, or a PBKDF2\n * iteration count outside 1 to 4294967295.\n */\nexport function inspectEncryptedPkcs8Der(der: Uint8Array): Pbes2Parameters {\n\treturn parsePbes2AlgorithmIdentifier(readEncryptedPkcs8Envelope(der).algorithmIdentifierDer);\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Der(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() =>\n\t\timportEncryptedPkcs8DerOrThrow(der, password, algorithm, options),\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * When `algorithm` is omitted, it is inferred from the decrypted key's own\n * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8PemOrThrow(pem, 'secret', { kind: 'rsa' });\n * const inferred = await importEncryptedPkcs8PemOrThrow(pem, 'secret');\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<CryptoKey> {\n\tconst budget = createKdfBudget(options);\n\treturn await importEncryptedPkcs8WithBudget(\n\t\tpemDecodeOrThrow('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\n\t\tbudget,\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() =>\n\t\timportEncryptedPkcs8PemOrThrow(pem, password, algorithm, options),\n\t);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportPkcs1Der} for the inverse operation\n * @see {@linkcode importPkcs1Pem} for PEM input\n */\nexport function importPkcs1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1DerOrThrow` for the throwing variant\n */\nexport function importPkcs1Der(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * Expects the `-----BEGIN RSA PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM\n */\nexport function importPkcs1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs1DerOrThrow(pemDecodeOrThrow('RSA PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1PemOrThrow` for the throwing variant\n */\nexport function importPkcs1Pem(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedPkcs1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('RSA PRIVATE KEY', pem, password);\n\tassertDecryptedPrivateKey(\n\t\t() => parsePkcs1PrivateKey(decrypted),\n\t\t'Invalid password or encrypted PEM content',\n\t);\n\treturn importPkcs1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input with headers\n */\nexport function importPkcs8Base64OrThrow(\n\tbase64: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 PKCS#8 private key');\n\t}\n\treturn importPkcs8DerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see `importPkcs8Base64OrThrow` for the throwing variant\n */\nexport function importPkcs8Base64(\n\tbase64: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8Base64OrThrow(base64, algorithm));\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import.\n * When the ECPrivateKey carries the optional RFC 5915 `parameters [0]` field\n * (OpenSSL always writes it), its named-curve OID must match `algorithm.curve`;\n * when the field is absent, the caller-supplied curve is trusted.\n *\n * When `algorithm` is omitted, the curve is inferred from the embedded\n * `parameters [0]` field; a key without a supported named curve then fails.\n *\n * @throws {Error} If DER is not an ECPrivateKey, its embedded curve doesn't\n * match `algorithm`, or no curve is available (neither embedded nor supplied)\n *\n * @see {@linkcode exportSec1Der} for the inverse operation\n * @see {@linkcode importSec1Pem} for PEM input\n */\nexport async function importSec1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm?: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tlet parsedSec1: ReturnType<typeof parseSec1PrivateKey>;\n\ttry {\n\t\tparsedSec1 = parseSec1PrivateKey(der);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed SEC 1 private key');\n\t}\n\tlet importInput: ImportEcKeyInput;\n\tif (algorithm === undefined) {\n\t\timportInput = inferSec1ImportInput(parsedSec1);\n\t} else {\n\t\tassertSec1MatchesRequestedAlgorithm(parsedSec1, algorithm);\n\t\timportInput = algorithm;\n\t}\n\treturn await importPkcs8DerOrThrow(wrapSec1InPkcs8(der, importInput.curve), importInput);\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1DerOrThrow` for the throwing variant\n */\nexport function importSec1Der(\n\tder: Uint8Array,\n\talgorithm?: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label. When `algorithm` is\n * omitted, the curve is inferred from the embedded `parameters [0]` field\n * (see {@linkcode importSec1DerOrThrow}).\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport function importSec1PemOrThrow(\n\tpem: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importSec1DerOrThrow(pemDecodeOrThrow('EC PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1PemOrThrow` for the throwing variant\n */\nexport function importSec1Pem(\n\tpem: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedSec1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('EC PRIVATE KEY', pem, password);\n\tassertDecryptedPrivateKey(\n\t\t() => parseSec1PrivateKey(decrypted),\n\t\t'Invalid password or encrypted PEM content',\n\t);\n\treturn importSec1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * @see `importEncryptedSec1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedSec1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * When `algorithm` is omitted, it is inferred from the JWK's own `kty`, `crv`,\n * and `alg` members (e.g. `PS256` → RSA-PSS/SHA-256, `RSA-OAEP-256` →\n * RSA-OAEP/SHA-256; an RSA JWK without `alg` defaults to PKCS#1 v1.5 with\n * SHA-256). Pass `algorithm` to additionally assert an expected algorithm.\n *\n * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Optional expected algorithm; must match JWK's `kty` and `crv` when given\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst importInput = algorithm ?? inferJwkImportInput(jwk);\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, importInput);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'jwk',\n\t\t\tjwk,\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tpublicKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed public JWK');\n\t}\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @see `importPublicJwkOrThrow` for the throwing variant\n */\nexport function importPublicJwk(\n\tjwk: JsonWebKey,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPublicJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * When `algorithm` is omitted, it is inferred from the JWK's own `kty`, `crv`,\n * and `alg` members (see {@linkcode importPublicJwkOrThrow}).\n *\n * @param jwk - JSON Web Key object with private key components\n * @param algorithm - Optional expected algorithm; must match JWK's `kty` and `crv` when given\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If JWK is malformed, lacks private key material, encodes an\n * unsupported algorithm, or doesn't match `algorithm`\n *\n * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwkOrThrow(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * const inferred = await importPrivateJwkOrThrow(jwk);\n * ```\n *\n * @see {@linkcode exportPrivateJwk} for the inverse operation\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tconst importInput = algorithm ?? inferJwkImportInput(jwk);\n\tassertPrivateJwkMatchesRequestedAlgorithm(jwk, importInput);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'jwk',\n\t\t\tjwk,\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tprivateKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed private JWK');\n\t}\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @see `importPrivateJwkOrThrow` for the throwing variant\n */\nexport function importPrivateJwk(\n\tjwk: JsonWebKey,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPrivateJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Encrypt a small message with an RSA-OAEP public key.\n *\n * The key must have been generated or imported with `{ kind: 'rsa', scheme: 'oaep' }`.\n * RSA-OAEP encrypts at most modulus bytes − 2 × hash bytes − 2 per call\n * (190 bytes for a 2048-bit key with SHA-256) — encrypt a symmetric key, not\n * bulk data.\n *\n * @param publicKey - RSA-OAEP public `CryptoKey` with `encrypt` usage\n * @param plaintext - Message bytes, at most the OAEP capacity of the key\n * @param options - Optional OAEP label bound to the ciphertext\n *\n * @throws {Error} If the key is not an RSA-OAEP public encryption key, or the\n * plaintext exceeds the key's OAEP capacity\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });\n * const ciphertext = await encryptRsaOaepOrThrow(\n * \tkeys.publicKey,\n * \tnew TextEncoder().encode('session key'),\n * );\n * ```\n *\n * @see {@linkcode decryptRsaOaepOrThrow} for the inverse operation\n * @see `encryptRsaOaep` for the Result-returning variant\n */\nexport async function encryptRsaOaepOrThrow(\n\tpublicKey: CryptoKey,\n\tplaintext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<Uint8Array> {\n\tconst keyProblem = validateRsaOaepKey(publicKey, 'public', 'encrypt');\n\tif (keyProblem !== undefined) {\n\t\tthrow new Error(keyProblem);\n\t}\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.encrypt(\n\t\t\t\ttoRsaOaepParams(options),\n\t\t\t\tpublicKey,\n\t\t\t\ttoArrayBuffer(plaintext),\n\t\t\t),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tthrow new Error(\n\t\t\t'Plaintext exceeds the RSA-OAEP capacity of the key (modulus bytes − 2 × hash bytes − 2)',\n\t\t);\n\t}\n}\n\n/**\n * Encrypt a small message with an RSA-OAEP public key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });\n * const encrypted = await encryptRsaOaep(keys.publicKey, plaintext);\n * if (!encrypted.ok) {\n * \t// encrypted.code: 'invalid_key' | 'message_too_long'\n * \tthrow new Error(encrypted.message);\n * }\n * const ciphertext = encrypted.value;\n * ```\n *\n * @see `encryptRsaOaepOrThrow` for the throwing variant\n */\nexport async function encryptRsaOaep(\n\tpublicKey: CryptoKey,\n\tplaintext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<EncryptRsaOaepResult> {\n\tconst keyProblem = validateRsaOaepKey(publicKey, 'public', 'encrypt');\n\tif (keyProblem !== undefined) {\n\t\treturn failureResult('invalid_key', keyProblem);\n\t}\n\ttry {\n\t\treturn successResult(await encryptRsaOaepOrThrow(publicKey, plaintext, options));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'message_too_long',\n\t\t\terror instanceof Error ? error.message : 'Plaintext exceeds the RSA-OAEP capacity',\n\t\t);\n\t}\n}\n\n/**\n * Decrypt an RSA-OAEP ciphertext with the matching private key.\n *\n * The key must have been generated or imported with `{ kind: 'rsa', scheme: 'oaep' }`,\n * and `options.label` must repeat the label used at encryption time (if any).\n *\n * @param privateKey - RSA-OAEP private `CryptoKey` with `decrypt` usage\n * @param ciphertext - Ciphertext produced by {@linkcode encryptRsaOaep} (or any RSA-OAEP encryptor)\n * @param options - OAEP label matching the one bound at encryption\n *\n * @throws {Error} If the key is not an RSA-OAEP private decryption key, or\n * decryption fails — wrong key, wrong label, or corrupted ciphertext (OAEP\n * deliberately does not reveal which)\n *\n * @example\n * ```ts\n * const plaintext = await decryptRsaOaepOrThrow(keys.privateKey, ciphertext);\n * ```\n *\n * @see {@linkcode encryptRsaOaepOrThrow} for the inverse operation\n * @see `decryptRsaOaep` for the Result-returning variant\n */\nexport async function decryptRsaOaepOrThrow(\n\tprivateKey: CryptoKey,\n\tciphertext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<Uint8Array> {\n\tconst keyProblem = validateRsaOaepKey(privateKey, 'private', 'decrypt');\n\tif (keyProblem !== undefined) {\n\t\tthrow new Error(keyProblem);\n\t}\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\ttoRsaOaepParams(options),\n\t\t\t\tprivateKey,\n\t\t\t\ttoArrayBuffer(ciphertext),\n\t\t\t),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tthrow new Error('RSA-OAEP decryption failed: wrong key, wrong label, or corrupted ciphertext');\n\t}\n}\n\n/**\n * Decrypt an RSA-OAEP ciphertext with the matching private key.\n *\n * @example\n * ```ts\n * const decrypted = await decryptRsaOaep(keys.privateKey, ciphertext);\n * if (!decrypted.ok) {\n * \t// decrypted.code: 'invalid_key' | 'decryption_failed'\n * \tthrow new Error(decrypted.message);\n * }\n * const plaintext = decrypted.value;\n * ```\n *\n * @see `decryptRsaOaepOrThrow` for the throwing variant\n */\nexport async function decryptRsaOaep(\n\tprivateKey: CryptoKey,\n\tciphertext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<DecryptRsaOaepResult> {\n\tconst keyProblem = validateRsaOaepKey(privateKey, 'private', 'decrypt');\n\tif (keyProblem !== undefined) {\n\t\treturn failureResult('invalid_key', keyProblem);\n\t}\n\ttry {\n\t\treturn successResult(await decryptRsaOaepOrThrow(privateKey, ciphertext, options));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'decryption_failed',\n\t\t\terror instanceof Error ? error.message : 'RSA-OAEP decryption failed',\n\t\t);\n\t}\n}\n\n/** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */\nfunction toGenerateKeyAlgorithm(\n\talgorithm: KeyAlgorithmInput,\n): EcKeyGenParams | RsaHashedKeyGenParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\tmodulusLength: algorithm.modulusLength ?? 2048,\n\t\t\t\tpublicExponent: Uint8Array.of(0x01, 0x00, 0x01),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve ?? 'P-256',\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled KeyAlgorithmInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */\nfunction toImportAlgorithm(\n\talgorithm: PublicKeyImportInput,\n): EcKeyImportParams | RsaHashedImportParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve,\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PublicKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Rejects decrypted plaintext that is not the private-key structure it should be.\n *\n * PBES2 and traditional PEM both encrypt with unauthenticated AES-CBC, where a\n * wrong key clears the padding check roughly once in every 256 attempts and\n * yields random plaintext. Structure is the only integrity signal left, so\n * plaintext that fails to parse means the password was wrong or the ciphertext\n * was corrupted, not that the enclosing input was malformed.\n */\nfunction assertDecryptedPrivateKey(parse: () => unknown, message: string): void {\n\ttry {\n\t\tparse();\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow wrongPasswordError(message);\n\t}\n}\n\n/** Structural check for a PKCS#1 RSAPrivateKey, including optional multiprime fields. */\nfunction parsePkcs1PrivateKey(der: Uint8Array): void {\n\tconst children = readSequenceChildren(der);\n\tconst version = children[0];\n\tif (\n\t\tversion === undefined ||\n\t\tversion.tag !== 0x02 ||\n\t\tversion.value.length !== 1 ||\n\t\t!children.slice(1, 9).every((child) => child.tag === 0x02)\n\t) {\n\t\tthrow new Error('Malformed PKCS#1 private key');\n\t}\n\tconst versionValue = version.value[0];\n\tif (versionValue === 0x00 && children.length === 9) {\n\t\treturn;\n\t}\n\tconst otherPrimeInfos = children[9];\n\tif (\n\t\tversionValue !== 0x01 ||\n\t\tchildren.length !== 10 ||\n\t\totherPrimeInfos === undefined ||\n\t\t!isOtherPrimeInfosShape(der, otherPrimeInfos)\n\t) {\n\t\tthrow new Error('Malformed PKCS#1 private key');\n\t}\n}\n\n/** RFC 8017 Appendix A.1.2: OtherPrimeInfos is a non-empty SEQUENCE OF three-INTEGER entries. */\nfunction isOtherPrimeInfosShape(source: Uint8Array, element: DerElement): boolean {\n\tif (element.tag !== 0x30) {\n\t\treturn false;\n\t}\n\tconst otherPrimeInfosDer = source.slice(element.start - element.headerLength, element.end);\n\tconst infos = readSequenceChildren(otherPrimeInfosDer);\n\tif (infos.length === 0) {\n\t\treturn false;\n\t}\n\treturn infos.every((info) => {\n\t\tif (info.tag !== 0x30) {\n\t\t\treturn false;\n\t\t}\n\t\tconst fields = readSequenceChildren(\n\t\t\totherPrimeInfosDer.slice(info.start - info.headerLength, info.end),\n\t\t);\n\t\treturn fields.length === 3 && fields.every((field) => field.tag === 0x02);\n\t});\n}\n\n/** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */\nfunction parsePkcs8PrivateKey(der: Uint8Array): {\n\t/** OID identifying the algorithm family (e.g. rsaEncryption, ecPublicKey). */\n\treadonly algorithmOid: string;\n\t/** Optional algorithm parameter OID (e.g. named curve for EC keys). */\n\treadonly parametersOid?: string;\n\t/** Optional algorithm parameter tag. */\n\treadonly parametersTag?: number;\n\t/** Raw DER of the inner private key (PKCS#1 for RSA, SEC 1 for EC). */\n\treadonly privateKeyDer: Uint8Array;\n\t/** The same key reduced to `version`, `privateKeyAlgorithm`, and `privateKey`. */\n\treadonly v1Der: Uint8Array;\n\t/** `publicKey [1]` octets without the BIT STRING unused-bits octet, when the field is present. */\n\treadonly declaredPublicKey?: Uint8Array;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst version = children[0];\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tversion === undefined ||\n\t\tversion.tag !== 0x02 ||\n\t\talgorithm === undefined ||\n\t\talgorithm.tag !== 0x30 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst declaredPublicKey = validateOneAsymmetricKeyTail(children.slice(3));\n\tif (readPkcs8Version(version.value) !== (declaredPublicKey === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst algorithmDer = der.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\talgorithmOid.tag !== 0x06 ||\n\t\talgorithmChildren.length < 1 ||\n\t\talgorithmChildren.length > 2\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst parameters = algorithmChildren[1];\n\tconst oid = decodeObjectIdentifier(algorithmOid.value);\n\tif (CURVE_PRIVATE_KEY_ALGORITHM_OIDS.includes(oid)) {\n\t\tassertCurvePrivateKey(privateKey.value);\n\t}\n\treturn {\n\t\talgorithmOid: oid,\n\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t...(parameters?.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t: {}),\n\t\tprivateKeyDer: privateKey.value,\n\t\tv1Der:\n\t\t\tchildren.length === 3\n\t\t\t\t? der\n\t\t\t\t: sequence([integer(Uint8Array.of(0)), algorithmDer, octetString(privateKey.value)]),\n\t\t...(declaredPublicKey === undefined ? {} : { declaredPublicKey }),\n\t};\n}\n\n/** Algorithms whose `privateKey` field holds an RFC 8410 §7 `CurvePrivateKey`. */\nconst CURVE_PRIVATE_KEY_ALGORITHM_OIDS: readonly string[] = [\n\tOIDS.x25519,\n\tOIDS.x448,\n\tOIDS.ed25519,\n\tOIDS.ed448,\n];\n\n/**\n * Reject a `privateKey` field that does not hold exactly one DER `CurvePrivateKey`.\n *\n * RFC 8410 §7: \"when encoding a OneAsymmetricKey object, the private key is\n * wrapped in a CurvePrivateKey object and wrapped by the OCTET STRING of the\n * 'privateKey' field\", and `CurvePrivateKey ::= OCTET STRING`.\n */\nfunction assertCurvePrivateKey(content: Uint8Array): void {\n\tconst curvePrivateKey = readRootElement(content);\n\tif (curvePrivateKey.tag !== 0x04) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n}\n\n/**\n * Validate the OneAsymmetricKey tail after `privateKey` and return the\n * `publicKey [1]` octets when the field is present.\n *\n * RFC 5958 §2 encodes `attributes [0]` as an IMPLICIT constructed `SET OF`\n * (tag `A0`); RFC 8410 §7 adds `publicKey [1]` as an IMPLICIT primitive\n * `BIT STRING` (tag `81`) after it. Each appears at most once and in that order.\n * The type's two X.680 extensibility markers admit later additions, which take\n * the next context-specific numbers, so `[2]` and above are tolerated and every\n * other class is malformed.\n */\nfunction validateOneAsymmetricKeyTail(tail: readonly DerElement[]): Uint8Array | undefined {\n\tlet seenAttributes = false;\n\tlet publicKey: Uint8Array | undefined;\n\tlet seenUnknown = false;\n\tfor (const child of tail) {\n\t\tconst contextNumber = (child.tag & 0xc0) === 0x80 ? child.tagNumber : -1;\n\t\tif (contextNumber === 0) {\n\t\t\tif (seenAttributes || publicKey !== undefined || seenUnknown || child.tag !== 0xa0) {\n\t\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t\t}\n\t\t\tassertOneAsymmetricKeyAttributes(child.value);\n\t\t\tseenAttributes = true;\n\t\t} else if (contextNumber === 1) {\n\t\t\tif (publicKey !== undefined || seenUnknown || child.tag !== 0x81) {\n\t\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t\t}\n\t\t\tpublicKey = readPublicKeyBitString(child.value);\n\t\t} else if (contextNumber >= 2) {\n\t\t\tseenUnknown = true;\n\t\t} else {\n\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t}\n\t}\n\treturn publicKey;\n}\n\n/**\n * Reject an `attributes [0]` field that does not hold a `SET OF Attribute`.\n *\n * RFC 5958 §2 types the field `Attributes ::= SET OF Attribute`, over the\n * `Attribute ::= SEQUENCE { attrType OBJECT IDENTIFIER, attrValues SET OF\n * AttributeValue }` of RFC 5652 §5.3. The implicit tag has replaced the SET OF\n * tag, so the members are read back under a universal constructed one.\n */\nfunction assertOneAsymmetricKeyAttributes(content: Uint8Array): void {\n\tconst attributes = tlv(0x30, content);\n\tfor (const attribute of readSequenceChildren(attributes)) {\n\t\tif (attribute.tag !== 0x30) {\n\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t}\n\t\tconst fields = readSequenceChildren(\n\t\t\tattributes.slice(attribute.start - attribute.headerLength, attribute.end),\n\t\t);\n\t\tconst type = fields[0];\n\t\tconst values = fields[1];\n\t\tif (\n\t\t\tfields.length !== 2 ||\n\t\t\ttype === undefined ||\n\t\t\ttype.tag !== 0x06 ||\n\t\t\tvalues === undefined ||\n\t\t\tvalues.tag !== 0x31\n\t\t) {\n\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t}\n\t}\n}\n\n/** Reject a `publicKey [1]` BIT STRING that is not octet-aligned or carries no key octets. */\nfunction readPublicKeyBitString(content: Uint8Array): Uint8Array {\n\tif (content.length < 2 || content[0] !== 0x00) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\treturn content.slice(1);\n}\n\n/** Decode the canonical RFC 5958 version INTEGER content, `v1(0)` or `v2(1)`. */\nfunction readPkcs8Version(content: Uint8Array): number {\n\tconst value = content[0];\n\tif (content.length !== 1 || (value !== 0x00 && value !== 0x01)) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\treturn value;\n}\n\n/**\n * Extract the optional `parameters [0]` curve identifier from a SEC 1 ECPrivateKey.\n *\n * RFC 5915 §3: `ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) }\n * (ecPrivkeyVer1), privateKey OCTET STRING, parameters [0] ECParameters\n * {{ NamedCurve }} OPTIONAL, publicKey [1] BIT STRING OPTIONAL }`.\n */\nfunction parseSec1PrivateKey(der: Uint8Array): {\n\t/** Optional ECParameters tag inside `parameters [0]` (0x06 for a named curve). */\n\treadonly parametersTag?: number;\n\t/** Optional named-curve OID when the ECParameters choice is an OBJECT IDENTIFIER. */\n\treadonly parametersOid?: string;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst version = children[0];\n\tconst privateKey = children[1];\n\tconst third = children[2];\n\tconst fourth = children[3];\n\tif (\n\t\tchildren.length < 2 ||\n\t\tchildren.length > 4 ||\n\t\tversion === undefined ||\n\t\tversion.tag !== 0x02 ||\n\t\tversion.value.length !== 1 ||\n\t\tversion.value[0] !== 0x01 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04 ||\n\t\t(third !== undefined && third.tag !== 0xa0 && third.tag !== 0xa1) ||\n\t\t(fourth !== undefined && (third?.tag !== 0xa0 || fourth.tag !== 0xa1))\n\t) {\n\t\tthrow new Error('Malformed SEC 1 private key');\n\t}\n\tconst parameters = third?.tag === 0xa0 ? third : undefined;\n\tif (parameters === undefined) {\n\t\treturn {};\n\t}\n\tconst ecParameters = readRootElement(parameters.value);\n\treturn {\n\t\tparametersTag: ecParameters.tag,\n\t\t...(ecParameters.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(ecParameters.value) }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Ensure a SEC 1 ECPrivateKey carries the RFC 5915 `parameters [0]` named\n * curve. WebCrypto's PKCS#8 export omits it from the inner ECPrivateKey (the\n * curve lives in the envelope's privateKeyAlgorithm), but RFC 5915 wants it in\n * standalone SEC 1 — and OpenSSL always writes it. Injecting it keeps exports\n * self-describing, so they re-import without an explicit curve.\n */\nfunction ensureSec1NamedCurveParameters(\n\tsec1Der: Uint8Array,\n\tcurveOid: string | undefined,\n): Uint8Array {\n\tconst children = readSequenceChildren(sec1Der);\n\tif (children.some((child) => child.tag === 0xa0)) {\n\t\treturn new Uint8Array(sec1Der);\n\t}\n\tif (curveOid === undefined) {\n\t\tthrow new Error('SEC1 export requires a named curve in the PKCS#8 privateKeyAlgorithm');\n\t}\n\tconst raw = (child: DerElement): Uint8Array =>\n\t\tsec1Der.slice(child.start - child.headerLength, child.end);\n\t// RFC 5915 field order: version, privateKey, parameters [0], publicKey [1].\n\treturn sequence([\n\t\t...children.slice(0, 2).map(raw),\n\t\texplicitContext(0, objectIdentifier(curveOid)),\n\t\t...children.slice(2).map(raw),\n\t]);\n}\n\n/** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapPkcs1InPkcs8(der: Uint8Array): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapSec1InPkcs8(der: Uint8Array, curve: ImportEcKeyInput['curve']): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Project a private JWK onto its public-only members, discarding private key material. */\nfunction toPublicJwk(jwk: JsonWebKey, usage: KeyUsage): JsonWebKey {\n\tif (jwk.kty !== 'RSA' && jwk.kty !== 'EC' && jwk.kty !== 'OKP') {\n\t\tthrow new Error(`Cannot derive public key: unsupported JWK key type ${String(jwk.kty)}`);\n\t}\n\tconst publicJwk: JsonWebKey = { ...jwk };\n\t// Strip every private component: RSA (d, p, q, dp, dq, qi, oth), EC/OKP (d).\n\tfor (const field of ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] as const) {\n\t\tdelete publicJwk[field];\n\t}\n\tpublicJwk.key_ops = [usage];\n\tpublicJwk.ext = true;\n\treturn publicJwk;\n}\n\n/**\n * Single source of truth for the NIST curve ↔ named-curve OID mapping, read in\n * both directions by {@linkcode curveToOid} and {@linkcode oidToCurve}.\n */\nconst EC_CURVE_OIDS = [\n\t['P-256', OIDS.prime256v1],\n\t['P-384', OIDS.secp384r1],\n\t['P-521', OIDS.secp521r1],\n] as const satisfies readonly (readonly [EcNamedCurve, string])[];\n\n/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcKeyInput['curve']): string {\n\tfor (const [name, oid] of EC_CURVE_OIDS) {\n\t\tif (name === curve) {\n\t\t\treturn oid;\n\t\t}\n\t}\n\tthrow new Error(`Unsupported EC curve: ${curve}`);\n}\n\n/** Map an ASN.1 curve OID string back to its curve name, or `undefined` if unrecognized. */\nfunction oidToCurve(oid: string): EcNamedCurve | undefined {\n\tfor (const [name, curveOid] of EC_CURVE_OIDS) {\n\t\tif (curveOid === oid) {\n\t\t\treturn name;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */\nfunction rsaSchemeToWebCryptoAlgorithmName(\n\tscheme: RsaScheme | undefined,\n): 'RSASSA-PKCS1-v1_5' | 'RSA-PSS' | 'RSA-OAEP' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\tif (scheme === 'oaep') {\n\t\treturn 'RSA-OAEP';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\n}\n\n/** `true` when the algorithm input selects RSA-OAEP, whose keys carry encrypt/decrypt usages. */\nfunction isRsaOaepInput(algorithm: KeyAlgorithmInput | PublicKeyImportInput): boolean {\n\treturn algorithm.kind === 'rsa' && algorithm.scheme === 'oaep';\n}\n\n/** Key usages for an imported public key: `verify`, or `encrypt` for RSA-OAEP. */\nfunction publicKeyUsages(algorithm: PublicKeyImportInput): KeyUsage[] {\n\treturn isRsaOaepInput(algorithm) ? ['encrypt'] : ['verify'];\n}\n\n/** Key usages for an imported private key: `sign`, or `decrypt` for RSA-OAEP. */\nfunction privateKeyUsages(algorithm: PrivateKeyImportInput): KeyUsage[] {\n\treturn isRsaOaepInput(algorithm) ? ['decrypt'] : ['sign'];\n}\n\n/**\n * Diagnose a key unfit for the given RSA-OAEP operation.\n *\n * Returns a human-readable problem description, or `undefined` when the key is\n * usable — keeping key-level failures (`'invalid_key'`) separable from\n * ciphertext-level failures before WebCrypto is ever called.\n */\nfunction validateRsaOaepKey(\n\tkey: CryptoKey,\n\ttype: 'public' | 'private',\n\tusage: 'encrypt' | 'decrypt',\n): string | undefined {\n\tconst operation = usage === 'encrypt' ? 'encryption' : 'decryption';\n\tif (key.type !== type) {\n\t\treturn `RSA-OAEP ${operation} requires a ${type} CryptoKey`;\n\t}\n\tif (key.algorithm.name !== 'RSA-OAEP') {\n\t\treturn `RSA-OAEP ${operation} requires an RSA-OAEP key (got ${key.algorithm.name}); generate or import the key with scheme: 'oaep'`;\n\t}\n\tif (!key.usages.includes(usage)) {\n\t\treturn `RSA-OAEP ${operation} requires a key with '${usage}' usage`;\n\t}\n\treturn undefined;\n}\n\n/** Build the WebCrypto RSA-OAEP params, attaching the optional label. */\nfunction toRsaOaepParams(options: RsaOaepOptions): RsaOaepParams {\n\treturn {\n\t\tname: 'RSA-OAEP',\n\t\t...(options.label === undefined ? {} : { label: toArrayBuffer(options.label) }),\n\t};\n}\n\n/** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */\nasync function encryptTraditionalPem(\n\tlabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tder: Uint8Array,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tif (iv.length !== 16) {\n\t\tthrow new Error('Traditional PEM encryption requires a 16-byte IV');\n\t}\n\tconst cipher = options.cipher ?? 'AES-256-CBC';\n\tconst key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, [\n\t\t'encrypt',\n\t]);\n\tconst encrypted = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(der),\n\t\t),\n\t);\n\tconst body =\n\t\tbase64Encode(encrypted)\n\t\t\t.match(/.{1,64}/g)\n\t\t\t?.join('\\n') ?? '';\n\treturn [\n\t\t`-----BEGIN ${label}-----`,\n\t\t'Proc-Type: 4,ENCRYPTED',\n\t\t`DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,\n\t\t'',\n\t\tbody,\n\t\t`-----END ${label}-----`,\n\t].join('\\n');\n}\n\n/** Decrypt a `Proc-Type: 4,ENCRYPTED` PEM block, RFC 1421 §4.6 headers, to plaintext DER. */\nasync function decryptTraditionalPem(\n\texpectedLabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tpem: string,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parsed = parseTraditionalPemOrThrow(pem);\n\tif (parsed.label !== expectedLabel) {\n\t\tthrow new Error(`Expected ${expectedLabel} PEM block`);\n\t}\n\tconst dekInfo = parsed.headers.get('DEK-Info');\n\tconst procType = parsed.headers.get('Proc-Type');\n\tif (procType === undefined || !isEncryptedProcType(procType) || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',').map(trimLwsp);\n\tif (!isTraditionalPemCipher(cipher) || ivHex === undefined) {\n\t\tthrow new Error(\n\t\t\t'Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported',\n\t\t);\n\t}\n\tif (!isTraditionalPemIvHex(ivHex)) {\n\t\tthrow new Error(\n\t\t\t'Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters',\n\t\t);\n\t}\n\tconst iv = hexToBytes(ivHex);\n\tconst key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ['decrypt']);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(base64Decode(parsed.base64Body)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted PEM content');\n\t}\n}\n\n/** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */\nfunction importTraditionalPemAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst keyLength = traditionalPemCipherKeyLength(cipher);\n\tconst keyBytes = opensslBytesToKey(password, salt, keyLength / 8);\n\treturn getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'AES-CBC', length: keyLength },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/**\n * RFC 1421 §4.6.1.1 `Proc-Type: 4,ENCRYPTED`.\n *\n * Fields are trimmed because RFC 822 §3.1.1 unfolding leaves an LWSP-char\n * wherever the header was folded.\n */\nfunction isEncryptedProcType(value: string): boolean {\n\tconst fields = value.split(',');\n\treturn (\n\t\tfields.length === 2 &&\n\t\ttrimLwsp(fields[0] ?? '') === '4' &&\n\t\ttrimLwsp(fields[1] ?? '') === 'ENCRYPTED'\n\t);\n}\n\n/** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */\nfunction isTraditionalPemCipher(\n\tcipher: string | undefined,\n): cipher is 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC' {\n\treturn cipher === 'AES-128-CBC' || cipher === 'AES-192-CBC' || cipher === 'AES-256-CBC';\n}\n\nfunction isTraditionalPemIvHex(value: string): boolean {\n\treturn value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);\n}\n\n/** Return the AES key size in bits for a given cipher name. */\nfunction traditionalPemCipherKeyLength(\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n): 128 | 192 | 256 {\n\tswitch (cipher) {\n\t\tcase 'AES-128-CBC':\n\t\t\treturn 128;\n\t\tcase 'AES-192-CBC':\n\t\t\treturn 192;\n\t\tcase 'AES-256-CBC':\n\t\t\treturn 256;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = cipher;\n\t\t\tthrow new Error(`Unhandled traditional PEM cipher: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */\nfunction opensslBytesToKey(password: string, salt: Uint8Array, length: number): Uint8Array {\n\tconst passwordBytes = new TextEncoder().encode(password);\n\tconst chunks: Uint8Array[] = [];\n\tlet previous = new Uint8Array();\n\tlet total = 0;\n\twhile (total < length) {\n\t\tconst input = new Uint8Array(previous.length + passwordBytes.length + salt.length);\n\t\tinput.set(previous, 0);\n\t\tinput.set(passwordBytes, previous.length);\n\t\tinput.set(salt, previous.length + passwordBytes.length);\n\t\tprevious = md5(input);\n\t\tchunks.push(previous);\n\t\ttotal += previous.length;\n\t}\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tconst slice = chunk.slice(0, Math.min(chunk.length, length - offset));\n\t\tout.set(slice, offset);\n\t\toffset += slice.length;\n\t\tif (offset >= length) {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction parseSpkiDer(der: Uint8Array): {\n\treadonly algorithmOid: string;\n\treadonly parametersOid?: string;\n\treadonly parametersTag?: number;\n} {\n\ttry {\n\t\tconst children = readSequenceChildren(der);\n\t\tif (children.length !== 2) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst algorithm = children[0];\n\t\tconst subjectPublicKey = children[1];\n\t\tif (\n\t\t\talgorithm === undefined ||\n\t\t\talgorithm.tag !== 0x30 ||\n\t\t\tsubjectPublicKey === undefined ||\n\t\t\tsubjectPublicKey.tag !== 0x03\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\textractBitStringValue(subjectPublicKey);\n\t\tconst algorithmChildren = readSequenceChildren(\n\t\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\t);\n\t\tconst algorithmOid = algorithmChildren[0];\n\t\tif (\n\t\t\talgorithmOid === undefined ||\n\t\t\talgorithmOid.tag !== 0x06 ||\n\t\t\talgorithmChildren.length < 1 ||\n\t\t\talgorithmChildren.length > 2\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst parameters = algorithmChildren[1];\n\t\treturn {\n\t\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t\t...(parameters?.tag === 0x06\n\t\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t\t: {}),\n\t\t};\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/**\n * Derive the import algorithm from a key envelope's own AlgorithmIdentifier\n * (SPKI `algorithm` or PKCS#8 `privateKeyAlgorithm` — both share the shape).\n *\n * RSA keys default to the `pkcs1-v1_5`/`SHA-256` import parameters (a plain\n * `rsaEncryption` AlgorithmIdentifier does not encode padding scheme or hash);\n * EC keys carry their curve in the DER; Ed25519 is fully determined by its OID.\n */\nfunction inferKeyImportInput(\n\tparsed: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\tunsupportedMessage: string,\n): PublicKeyImportInput {\n\tswitch (parsed.algorithmOid) {\n\t\tcase OIDS.rsaEncryption:\n\t\t\tif (parsed.parametersTag === undefined || parsed.parametersTag === 0x05) {\n\t\t\t\treturn { kind: 'rsa' };\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OIDS.ecPublicKey: {\n\t\t\tconst curve =\n\t\t\t\tparsed.parametersTag === 0x06 && parsed.parametersOid !== undefined\n\t\t\t\t\t? oidToCurve(parsed.parametersOid)\n\t\t\t\t\t: undefined;\n\t\t\tif (curve !== undefined) {\n\t\t\t\treturn { kind: 'ecdsa', curve };\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase OIDS.ed25519:\n\t\t\tif (parsed.parametersTag === undefined) {\n\t\t\t\treturn { kind: 'ed25519' };\n\t\t\t}\n\t\t\tbreak;\n\t}\n\tthrow new Error(unsupportedMessage);\n}\n\n/**\n * Derive the import curve from a SEC 1 ECPrivateKey's own RFC 5915\n * `parameters [0]` field. SEC 1 encodes no algorithm family (it is EC by\n * definition), so only the named curve needs recovering — and it may be\n * absent, in which case the caller must supply it.\n */\nfunction inferSec1ImportInput(parsedSec1: {\n\treadonly parametersTag?: number;\n\treadonly parametersOid?: string;\n}): ImportEcKeyInput {\n\tconst curve =\n\t\tparsedSec1.parametersTag === 0x06 && parsedSec1.parametersOid !== undefined\n\t\t\t? oidToCurve(parsedSec1.parametersOid)\n\t\t\t: undefined;\n\tif (curve === undefined) {\n\t\tthrow new Error(\n\t\t\t'SEC 1 private key does not encode a supported named curve; pass the algorithm explicitly',\n\t\t);\n\t}\n\treturn { kind: 'ecdsa', curve };\n}\n\n/**\n * Derive the import algorithm from a JWK's own `kty`, `crv`, and `alg` members.\n *\n * `alg` disambiguates the RSA scheme and hash (`RS*`, `PS*`, `RSA-OAEP-*`) —\n * WebCrypto rejects a JWK whose `alg` disagrees with the import algorithm, so\n * it must be honored rather than defaulted over. An RSA JWK without `alg`\n * defaults to `pkcs1-v1_5`/`SHA-256`, mirroring SPKI inference.\n */\nfunction inferJwkImportInput(jwk: JsonWebKey): PublicKeyImportInput {\n\tif (jwk.kty === 'RSA') {\n\t\treturn rsaImportInputFromJwkAlg(jwk.alg);\n\t}\n\tif (jwk.kty === 'EC') {\n\t\tif (jwk.crv === 'P-256' || jwk.crv === 'P-384' || jwk.crv === 'P-521') {\n\t\t\treturn { kind: 'ecdsa', curve: jwk.crv };\n\t\t}\n\t\tthrow new Error(`Unsupported EC JWK curve: ${String(jwk.crv)}`);\n\t}\n\tif (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {\n\t\treturn { kind: 'ed25519' };\n\t}\n\tthrow new Error('Unsupported JWK key type');\n}\n\n/** Map a JWA `alg` identifier to the RSA scheme + hash it pins down. */\nfunction rsaImportInputFromJwkAlg(alg: string | undefined): ImportRsaKeyInput {\n\tswitch (alg) {\n\t\tcase undefined:\n\t\tcase 'RS256':\n\t\t\treturn { kind: 'rsa' };\n\t\tcase 'RS384':\n\t\t\treturn { kind: 'rsa', hash: 'SHA-384' };\n\t\tcase 'RS512':\n\t\t\treturn { kind: 'rsa', hash: 'SHA-512' };\n\t\tcase 'PS256':\n\t\t\treturn { kind: 'rsa', scheme: 'pss' };\n\t\tcase 'PS384':\n\t\t\treturn { kind: 'rsa', scheme: 'pss', hash: 'SHA-384' };\n\t\tcase 'PS512':\n\t\t\treturn { kind: 'rsa', scheme: 'pss', hash: 'SHA-512' };\n\t\tcase 'RSA-OAEP-256':\n\t\t\treturn { kind: 'rsa', scheme: 'oaep' };\n\t\tcase 'RSA-OAEP-384':\n\t\t\treturn { kind: 'rsa', scheme: 'oaep', hash: 'SHA-384' };\n\t\tcase 'RSA-OAEP-512':\n\t\t\treturn { kind: 'rsa', scheme: 'oaep', hash: 'SHA-512' };\n\t\tdefault:\n\t\t\t// Includes plain 'RSA-OAEP' (SHA-1) — this library supports SHA-2 only.\n\t\t\tthrow new Error(`Unsupported RSA JWK alg: ${alg}`);\n\t}\n}\n\nfunction assertSpkiMatchesRequestedAlgorithm(\n\tparsedSpki: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PublicKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedSpki.parametersTag !== undefined && parsedSpki.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedSpki.parametersTag !== 0x06 ||\n\t\t\t\tparsedSpki.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== undefined) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PublicKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction assertPkcs8MatchesRequestedAlgorithm(\n\tparsedPrivateKey: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedPrivateKey.parametersTag !== undefined && parsedPrivateKey.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedPrivateKey.parametersTag !== 0x06 ||\n\t\t\t\tparsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ed25519 ||\n\t\t\t\tparsedPrivateKey.parametersTag !== undefined\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PrivateKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction assertSec1MatchesRequestedAlgorithm(\n\tparsedSec1: {\n\t\treadonly parametersTag?: number;\n\t\treadonly parametersOid?: string;\n\t},\n\talgorithm: ImportEcKeyInput,\n): void {\n\tif (parsedSec1.parametersTag === undefined) {\n\t\t// Parameters field absent: nothing encoded to cross-check, trust the caller.\n\t\treturn;\n\t}\n\tif (\n\t\tparsedSec1.parametersTag !== 0x06 ||\n\t\tparsedSec1.parametersOid !== curveToOid(algorithm.curve)\n\t) {\n\t\tthrow new Error('SEC 1 private key curve does not match requested import algorithm');\n\t}\n}\n\nfunction assertPublicJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): void {\n\tif (\n\t\tjwk.k !== undefined ||\n\t\tjwk.d !== undefined ||\n\t\tjwk.p !== undefined ||\n\t\tjwk.q !== undefined ||\n\t\tjwk.dp !== undefined ||\n\t\tjwk.dq !== undefined ||\n\t\tjwk.qi !== undefined ||\n\t\tjwk.oth !== undefined\n\t) {\n\t\tthrow new Error('Public JWK must not contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PublicKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction assertPrivateJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tif (jwk.k !== undefined || jwk.oth !== undefined) {\n\t\tthrow new Error('Private JWK must not contain symmetric or multi-prime key material');\n\t}\n\tif (typeof jwk.d !== 'string') {\n\t\tthrow new Error('Private JWK must contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'RSA' ||\n\t\t\t\ttypeof jwk.n !== 'string' ||\n\t\t\t\ttypeof jwk.e !== 'string' ||\n\t\t\t\ttypeof jwk.p !== 'string' ||\n\t\t\t\ttypeof jwk.q !== 'string' ||\n\t\t\t\ttypeof jwk.dp !== 'string' ||\n\t\t\t\ttypeof jwk.dq !== 'string' ||\n\t\t\t\ttypeof jwk.qi !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Private JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Private JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Private JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\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AY,OAAOA,EAAI,KAAM,UACtE,MAAU,MAAM,gEAAgE;GAEjF;EACD,KAAK;GACJ,IACCA,EAAI,QAAQ,QACZA,EAAI,QAAQvD,EAAU,SACtB,OAAOuD,EAAI,KAAM,YACjB,OAAOA,EAAI,KAAM,UAEjB,MAAU,MAAM,gEAAgE;GAEjF;EACD,KAAK;GACJ,IAAIA,EAAI,QAAQ,SAASA,EAAI,QAAQ,aAAa,OAAOA,EAAI,KAAM,UAClE,MAAU,MAAM,gEAAgE;GAEjF;EACD,SAEC,MAAU,MAAM,wCAAwC,OAAO3D,CAAW,GAAG;CAE/E;AACD;AAEA,SAAS,0CACR,GACA,GACO;CACP,IAAI2D,EAAI,MAAM,KAAA,KAAaA,EAAI,QAAQ,KAAA,GACtC,MAAU,MAAM,oEAAoE;CAErF,IAAI,OAAOA,EAAI,KAAM,UACpB,MAAU,MAAM,+CAA+C;CAEhE,QAAQvD,EAAU,MAAlB;EACC,KAAK;GACJ,IACCuD,EAAI,QAAQ,SACZ,OAAOA,EAAI,KAAM,YACjB,OAAOA,EAAI,KAAM,YACjB,OAAOA,EAAI,KAAM,YACjB,OAAOA,EAAI,KAAM,YACjB,OAAOA,EAAI,MAAO,YAClB,OAAOA,EAAI,MAAO,YAClB,OAAOA,EAAI,MAAO,UAElB,MAAU,MAAM,iEAAiE;GAElF;EACD,KAAK;GACJ,IACCA,EAAI,QAAQ,QACZA,EAAI,QAAQvD,EAAU,SACtB,OAAOuD,EAAI,KAAM,YACjB,OAAOA,EAAI,KAAM,UAEjB,MAAU,MAAM,iEAAiE;GAElF;EACD,KAAK;GACJ,IAAIA,EAAI,QAAQ,SAASA,EAAI,QAAQ,aAAa,OAAOA,EAAI,KAAM,UAClE,MAAU,MAAM,iEAAiE;GAElF;EACD,SAEC,MAAU,MAAM,yCAAyC,OAAO3D,CAAW,GAAG;CAEhF;AACD"}
1
+ {"version":3,"file":"keys.js","names":["_exhaustive","subtle","getCrypto","usages","algorithm","generated","publicKey","pemEncode","privateKey","pkcs8","encryption","encryptPbes2","options","sequence","octetString","parsed","OIDS","usage","privateJwk","key","base64Encode","parsedSpki","der","importInput","successResult","run","error","rethrowIfInvariant","decodeFailureResult","DECODE_LIMIT_CODES","isWrongPasswordError","failureResult","isKdfIterationLimitError","pemDecodeOrThrow","pem","decoded","base64Decode","base64","parsedPrivateKey","rethrowDecodeRefusal","declaredPublicKey","spki","subjectPublicKey","readSequenceChildren","derived","declared","byte","index","password","createKdfBudget","envelope","decrypted","decryptPbes2","budget","children","algorithmIdentifier","encryptedData","parsePbes2AlgorithmIdentifier","parsedSec1","jwk","keyProblem","toArrayBuffer","plaintext","ciphertext","wrongPasswordError","message","version","child","versionValue","otherPrimeInfos","element","otherPrimeInfosDer","source","infos","info","fields","field","algorithmDer","algorithmChildren","algorithmOid","parameters","oid","decodeObjectIdentifier","CURVE_PRIVATE_KEY_ALGORITHM_OIDS","integer","readRootElement","content","seenAttributes","seenUnknown","tail","contextNumber","attributes","tlv","attribute","type","values","value","third","fourth","ecParameters","sec1Der","curveOid","explicitContext","objectIdentifier","nullValue","curve","publicJwk","EC_CURVE_OIDS","name","scheme","operation","iv","cipher","encrypted","body","label","toHex","parseTraditionalPemOrThrow","expectedLabel","dekInfo","procType","ivHex","trimLwsp","hexToBytes","keyLength","keyBytes","salt","passwordBytes","chunks","previous","total","length","input","md5","out","offset","chunk","slice","unsupportedMessage","alg"],"sources":["../../src/keys/keys.ts"],"sourcesContent":["/**\n * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.\n *\n * Supports RSA (PKCS#1v1.5, PSS, and OAEP), ECDSA (P-256, P-384, P-521), and Ed25519 keys.\n * All functions use the WebCrypto API and return extractable keys.\n *\n * @example\n * ```ts\n * import { unwrap } from 'micro509';\n * import { generateKeyPair, exportSpkiPem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const publicPem = await exportSpkiPem(keys.publicKey);\n *\n * // Import — Result-returning; unwrap() throws on failure\n * const publicKey = unwrap(await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' }));\n * ```\n *\n * @module\n */\n\nimport {\n\tdecodeObjectIdentifier,\n\textractBitStringValue,\n\thexToBytes,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_LIMIT_CODES,\n\tdecodeFailureResult,\n\trethrowDecodeRefusal,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\texplicitContext,\n\tinteger,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { md5 } from '#micro509/internal/crypto/hash';\nimport type { KdfBudget, KdfLimitOptions, Pbes2Parameters } from '#micro509/internal/crypto/pbes2';\nimport {\n\tcreateKdfBudget,\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisKdfIterationLimitError,\n\tisWrongPasswordError,\n\tparsePbes2AlgorithmIdentifier,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport {\n\tparseTraditionalPemOrThrow,\n\tpemDecodeOrThrow,\n\tpemEncode,\n\ttrimLwsp,\n} from '#micro509/pem/pem';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\n\nexport type {\n\tKdfLimitOptions,\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Parameters,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2';\nexport { parsePbes2AlgorithmIdentifier } from '#micro509/internal/crypto/pbes2';\n\n/** Hash algorithm paired with an RSA key. */\nexport type RsaHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** RSA signature padding scheme. */\nexport type RsaSignatureScheme = 'pkcs1-v1_5' | 'pss';\n\n/**\n * RSA padding scheme: a signature scheme, or `'oaep'` for RSA-OAEP encryption\n * keys (usable with {@linkcode encryptRsaOaep} / {@linkcode decryptRsaOaep}).\n */\nexport type RsaScheme = RsaSignatureScheme | 'oaep';\n\n/** NIST elliptic curve for ECDSA keys. */\nexport type EcNamedCurve = 'P-256' | 'P-384' | 'P-521';\n\n/** RSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface RsaKeyAlgorithmInput {\n\t/** Discriminant selecting RSA key generation. */\n\treadonly kind: 'rsa';\n\t/** RSA modulus size in bits. Defaults to `2048`. */\n\treadonly modulusLength?: 2048 | 3072 | 4096;\n\t/** Hash algorithm for the key. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/**\n\t * Padding scheme. Defaults to `'pkcs1-v1_5'`. Pass `'oaep'` to generate an\n\t * RSA-OAEP encryption pair (`encrypt`/`decrypt` usages instead of `sign`/`verify`).\n\t */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface EcKeyAlgorithmInput {\n\t/** Discriminant selecting ECDSA key generation. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve. Defaults to `'P-256'`. */\n\treadonly curve?: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode KeyAlgorithmInput}. */\nexport interface Ed25519KeyAlgorithmInput {\n\t/** Discriminant selecting Ed25519 key generation. */\n\treadonly kind: 'ed25519';\n}\n\n/** Input for {@linkcode generateKeyPair}. Selects algorithm family and parameters. */\nexport type KeyAlgorithmInput =\n\t| RsaKeyAlgorithmInput\n\t| EcKeyAlgorithmInput\n\t| Ed25519KeyAlgorithmInput;\n\n/** Key pair with convenience export helpers. Returned by {@linkcode generateKeyPair}. */\nexport interface KeyPairMaterial {\n\t/** The WebCrypto public key (extractable, `verify` usage; `encrypt` for RSA-OAEP). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage; `decrypt` for RSA-OAEP). */\n\treadonly privateKey: CryptoKey;\n\t/** Export the public key as DER-encoded SubjectPublicKeyInfo. */\n\texportSpkiDer(): Promise<Uint8Array>;\n\t/** Export the public key as PEM-encoded SubjectPublicKeyInfo. */\n\texportSpkiPem(): Promise<string>;\n\t/** Export the private key as DER-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Der(): Promise<Uint8Array>;\n\t/** Export the private key as PEM-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Pem(): Promise<string>;\n\t/** Export the public key as a JSON Web Key. */\n\texportPublicJwk(): Promise<JsonWebKey>;\n\t/** Export the private key as a JSON Web Key. */\n\texportPrivateJwk(): Promise<JsonWebKey>;\n}\n\n/** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport type ImportRsaKeyInput = {\n\t/** Discriminant selecting RSA import. */\n\treadonly kind: 'rsa';\n} & (\n\t| {\n\t\t\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\t\t\treadonly scheme?: RsaSignatureScheme;\n\t\t\t/** Signature hash. Defaults to `'SHA-256'`. */\n\t\t\treadonly hash?: RsaHash;\n\t }\n\t| {\n\t\t\t/** Import an encryption key with `encrypt`/`decrypt` usages. */\n\t\t\treadonly scheme: 'oaep';\n\t\t\t/** Hash. Defaults to `'SHA-256'`. Explicit `'SHA-1'` supports legacy OAEP envelopes. */\n\t\t\treadonly hash?: RsaHash | 'SHA-1';\n\t }\n);\n\n/** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEcKeyInput {\n\t/** Discriminant selecting ECDSA import. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve the key belongs to. Required for EC import. */\n\treadonly curve: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEd25519KeyInput {\n\t/** Discriminant selecting Ed25519 import. */\n\treadonly kind: 'ed25519';\n}\n\n/** Algorithm descriptor for public key import functions. */\nexport type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\n/** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */\nexport type PrivateKeyImportInput = PublicKeyImportInput;\n\n/** PBES2 encryption options for the encrypted PKCS#8 export/import functions. */\nexport interface EncryptedPkcs8Options {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\t/** PBKDF2 pseudo-random function. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: 'HMAC-SHA-1' | 'HMAC-SHA-256';\n}\n\n/** Options for OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM encryption (PKCS#1/SEC1). */\nexport interface LegacyPemEncryptionOptions {\n\t/** Passphrase used to derive the encryption key. */\n\treadonly password: string;\n\t/** 16-byte initialization vector. Random when omitted. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Defaults to `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n}\n\n/**\n * Machine-readable failure reason for the `import*` key functions.\n *\n * `limit_exceeded` is an implementation limit: an OBJECT IDENTIFIER\n * sub-identifier encoded in more than 64 octets, a tag number of 2^53 or more,\n * or DER nested deeper than 64 levels.\n */\nexport type ImportKeyErrorCode = Exclude<DecodeFailureCode, 'unsupported'>;\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `import*` key functions.\n *\n * On failure, `code` is `'malformed'` for structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures alike (see the\n * throwing `*OrThrow` variants for raw error messages), and `'limit_exceeded'`\n * for an implementation limit.\n */\nexport type ImportKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>;\n\n/**\n * Machine-readable failure reason for the `importEncrypted*` key functions.\n *\n * Distinguishes a wrong decryption password (`'invalid_password'`) from\n * structurally invalid input or algorithm mismatches (`'malformed'`), from an\n * encoded KDF iteration count above the caller's limit\n * (`'kdf_iterations_exceeded'`), and from a decoding limit of micro509's own\n * (`'limit_exceeded'`, see {@linkcode ImportKeyErrorCode}).\n */\nexport type ImportEncryptedKeyErrorCode =\n\t| ImportKeyErrorCode\n\t| 'invalid_password'\n\t| 'kdf_iterations_exceeded';\n\n/** Options for the encrypted PKCS#8 import functions. */\nexport type ImportEncryptedKeyOptions = KdfLimitOptions;\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `importEncrypted*` key functions.\n *\n * On failure, `code` is `'invalid_password'` when decryption failed (wrong\n * password or corrupted ciphertext) and `'malformed'` for everything else.\n */\nexport type ImportEncryptedKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportEncryptedKeyErrorCode, Record<never, never>, ImportEncryptedKeyFailure>;\n\n/** Options shared by {@linkcode encryptRsaOaep} and {@linkcode decryptRsaOaep}. */\nexport interface RsaOaepOptions {\n\t/**\n\t * Optional OAEP label bound to the ciphertext. Not encrypted, but decryption\n\t * fails unless the exact same label is presented. Default: empty.\n\t */\n\treadonly label?: Uint8Array;\n}\n\n/**\n * Machine-readable failure reason for {@linkcode encryptRsaOaep}.\n *\n * `'invalid_key'` when the key is not an RSA-OAEP public key with `encrypt`\n * usage; `'message_too_long'` when the plaintext exceeds the OAEP capacity of\n * the key (modulus bytes − 2 × hash bytes − 2).\n */\nexport type EncryptRsaOaepErrorCode = 'invalid_key' | 'message_too_long';\n\n/** Structured failure payload for {@linkcode encryptRsaOaep}. */\nexport interface EncryptRsaOaepFailure extends Micro509Error<EncryptRsaOaepErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result returned by {@linkcode encryptRsaOaep}. */\nexport type EncryptRsaOaepResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<EncryptRsaOaepErrorCode, Record<never, never>, EncryptRsaOaepFailure>;\n\n/**\n * Machine-readable failure reason for {@linkcode decryptRsaOaep}.\n *\n * `'invalid_key'` when the key is not an RSA-OAEP private key with `decrypt`\n * usage; `'decryption_failed'` for every ciphertext-level failure (wrong key,\n * wrong label, tampered or truncated ciphertext) — OAEP deliberately does not\n * reveal which.\n */\nexport type DecryptRsaOaepErrorCode = 'invalid_key' | 'decryption_failed';\n\n/** Structured failure payload for {@linkcode decryptRsaOaep}. */\nexport interface DecryptRsaOaepFailure extends Micro509Error<DecryptRsaOaepErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result returned by {@linkcode decryptRsaOaep}. */\nexport type DecryptRsaOaepResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<DecryptRsaOaepErrorCode, Record<never, never>, DecryptRsaOaepFailure>;\n\n/**\n * Generate an asymmetric key pair for signing and verification, or — with\n * `{ kind: 'rsa', scheme: 'oaep' }` — for RSA-OAEP encryption and decryption.\n *\n * @example\n * ```ts\n * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });\n * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });\n * const edKeys = await generateKeyPair({ kind: 'ed25519' });\n * const oaepKeys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });\n *\n * // Default: ECDSA P-256\n * const keys = await generateKeyPair();\n * const pem = await keys.exportPkcs8Pem();\n * ```\n */\nexport async function generateKeyPair(\n\talgorithm: KeyAlgorithmInput = { kind: 'ecdsa', curve: 'P-256' },\n): Promise<KeyPairMaterial> {\n\tconst subtle = getCrypto().subtle;\n\tconst usages: KeyUsage[] = isRsaOaepInput(algorithm)\n\t\t? ['encrypt', 'decrypt']\n\t\t: ['sign', 'verify'];\n\tconst generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, usages);\n\n\tif (!('publicKey' in generated) || !('privateKey' in generated)) {\n\t\tthrow new Error('Expected an asymmetric key pair');\n\t}\n\n\treturn wrapKeyPair(generated.publicKey, generated.privateKey);\n}\n\nfunction wrapKeyPair(publicKey: CryptoKey, privateKey: CryptoKey): KeyPairMaterial {\n\treturn {\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tasync exportSpkiDer() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n\t\t},\n\t\tasync exportSpkiPem() {\n\t\t\treturn pemEncode('PUBLIC KEY', await this.exportSpkiDer());\n\t\t},\n\t\tasync exportPkcs8Der() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n\t\t},\n\t\tasync exportPkcs8Pem() {\n\t\t\treturn pemEncode('PRIVATE KEY', await this.exportPkcs8Der());\n\t\t},\n\t\texportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\texportPrivateJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n\t\t},\n\t};\n}\n\n/**\n * Export a public key as DER-encoded SubjectPublicKeyInfo.\n *\n * @see {@linkcode importSpkiDer} for the inverse operation\n * @see {@linkcode exportSpkiPem} for PEM output\n */\nexport async function exportSpkiDer(publicKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n}\n\n/**\n * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see {@linkcode importPkcs8Der} for the inverse operation\n * @see {@linkcode exportPkcs8Pem} for PEM output\n * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export\n */\nexport async function exportPkcs8Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n}\n\n/**\n * Export a public key as a JSON Web Key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const jwk = await exportPublicJwk(keys.publicKey);\n * ```\n */\nexport function exportPublicJwk(publicKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n}\n\n/**\n * Export a private key as a JSON Web Key.\n *\n * @see {@linkcode importPrivateJwk} for the inverse operation\n * @see {@linkcode exportPublicJwk} for public key export\n */\nexport function exportPrivateJwk(privateKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n}\n\n/**\n * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportPkcs8Pem(keys.privateKey);\n * // -----BEGIN PRIVATE KEY-----\n * // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...\n * // -----END PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importPkcs8Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export\n */\nexport async function exportPkcs8Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PRIVATE KEY', await exportPkcs8Der(privateKey));\n}\n\n/**\n * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.\n *\n * @param privateKey - The private key to export\n * @param options - Encryption options including password and optional algorithm settings\n *\n * @throws {RangeError} If `options.iterations` is not an integer from 1 to 4294967295\n *\n * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output\n */\nexport async function exportEncryptedPkcs8Der(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst encryption = await encryptPbes2(pkcs8, options);\n\treturn sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);\n}\n\n/**\n * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });\n * // -----BEGIN ENCRYPTED PRIVATE KEY-----\n * // MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...\n * // -----END ENCRYPTED PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs8Pem(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<string> {\n\treturn pemEncode('ENCRYPTED PRIVATE KEY', await exportEncryptedPkcs8Der(privateKey, options));\n}\n\n/**\n * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Der} for the inverse operation\n * @see {@linkcode exportPkcs1Pem} for PEM output\n */\nexport async function exportPkcs1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.rsaEncryption) {\n\t\tthrow new Error('PKCS#1 export requires an RSA private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export\n */\nexport async function exportPkcs1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('RSA PRIVATE KEY', await exportPkcs1Der(privateKey));\n}\n\n/**\n * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('RSA PRIVATE KEY', await exportPkcs1Der(privateKey), options);\n}\n\n/**\n * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * The output always carries the RFC 5915 `parameters [0]` named curve\n * (matching OpenSSL), so it re-imports via {@linkcode importSec1Der} without\n * an explicit curve.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Der} for the inverse operation\n * @see {@linkcode exportSec1Pem} for PEM output\n */\nexport async function exportSec1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.ecPublicKey) {\n\t\tthrow new Error('SEC1 export requires an EC private key');\n\t}\n\treturn ensureSec1NamedCurveParameters(parsed.privateKeyDer, parsed.parametersOid);\n}\n\n/**\n * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedSec1Pem} for password-protected export\n */\nexport async function exportSec1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('EC PRIVATE KEY', await exportSec1Der(privateKey));\n}\n\n/**\n * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importEncryptedSec1Pem} for the inverse operation\n */\nexport async function exportEncryptedSec1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('EC PRIVATE KEY', await exportSec1Der(privateKey), options);\n}\n\n/**\n * Export a public key as PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportSpkiPem(keys.publicKey);\n * ```\n */\nexport async function exportSpkiPem(publicKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PUBLIC KEY', await exportSpkiDer(publicKey));\n}\n\n/**\n * Derive the matching public key from an imported (or generated) private key.\n *\n * The `import*` functions that read a PKCS#8 / PKCS#1 / SEC 1 / JWK private key\n * return a bare `CryptoKey` with only `sign` (or, for RSA-OAEP, `decrypt`)\n * usage — there is no accompanying public handle. This bridges that gap: it\n * exports the private key's JWK, strips the private components, and re-imports\n * the public half with `verify` (RSA-OAEP: `encrypt`) usage, so callers can go\n * straight to {@linkcode exportSpkiDer} / {@linkcode exportSpkiPem} (e.g. to\n * rebuild a self-signed cert or distribute the public key when only the\n * private key is on disk).\n *\n * Supports RSA (`n`/`e`), ECDSA (`x`/`y`), and Ed25519 (`x`). The derived key\n * inherits the private key's algorithm parameters (hash, curve).\n *\n * @param privateKey - An extractable private `CryptoKey`\n * @returns Extractable public `CryptoKey` with `verify` (RSA-OAEP: `encrypt`) usage\n *\n * @throws {Error} If the key is not a private key, is non-extractable, or uses\n * an unsupported key type\n *\n * @example\n * ```ts\n * const privateKey = await importPkcs8PemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });\n * const publicKey = await derivePublicKey(privateKey);\n * const spkiPem = await exportSpkiPem(publicKey);\n * ```\n *\n * @see {@linkcode exportSpkiDer} for exporting the derived key\n */\nexport async function derivePublicKey(privateKey: CryptoKey): Promise<CryptoKey> {\n\tif (privateKey.type !== 'private') {\n\t\tthrow new Error('derivePublicKey requires a private CryptoKey');\n\t}\n\tif (!privateKey.extractable) {\n\t\tthrow new Error('Cannot derive public key from a non-extractable private key');\n\t}\n\tconst subtle = getCrypto().subtle;\n\tconst usage: KeyUsage = privateKey.algorithm.name === 'RSA-OAEP' ? 'encrypt' : 'verify';\n\tconst privateJwk = await subtle.exportKey('jwk', privateKey);\n\treturn subtle.importKey('jwk', toPublicJwk(privateJwk, usage), privateKey.algorithm, true, [\n\t\tusage,\n\t]);\n}\n\n/**\n * Export a key as raw base64 (no PEM headers).\n *\n * Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys.\n * Useful for compact storage or transmission where PEM overhead is undesirable.\n *\n * @throws {Error} If the key is a symmetric/secret key\n *\n * @see {@linkcode importSpkiBase64} for public key import\n * @see {@linkcode importPkcs8Base64} for private key import\n */\nexport async function exportBinaryBase64(key: CryptoKey): Promise<string> {\n\tif (key.type === 'public') {\n\t\treturn base64Encode(await exportSpkiDer(key));\n\t}\n\tif (key.type === 'private') {\n\t\treturn base64Encode(await exportPkcs8Der(key));\n\t}\n\tthrow new Error('Cannot export secret/symmetric CryptoKey');\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * When `algorithm` is omitted, the algorithm (and, for EC keys, the curve) is\n * inferred from the SPKI's own AlgorithmIdentifier — useful for keys whose type\n * isn't known ahead of time. Pass `algorithm` to additionally assert that the\n * DER matches an expected algorithm.\n *\n * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Optional expected algorithm; must match key contents when given\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`\n *\n * @see {@linkcode exportSpkiDer} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input\n */\nexport async function importSpkiDerOrThrow(\n\tder: Uint8Array,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst parsedSpki = parseSpkiDer(der);\n\tlet importInput: PublicKeyImportInput;\n\tif (algorithm === undefined) {\n\t\timportInput = inferKeyImportInput(parsedSpki, 'Unsupported SubjectPublicKeyInfo algorithm');\n\t} else {\n\t\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\t\timportInput = algorithm;\n\t}\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tpublicKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` or `'limit_exceeded'` result; invariants rethrow. */\nasync function importResult(run: () => Promise<CryptoKey>): Promise<ImportKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decodeFailureResult(error, DECODE_LIMIT_CODES, 'Malformed key');\n\t}\n}\n\n/** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */\nasync function encryptedImportResult(\n\trun: () => Promise<CryptoKey>,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn failureResult('invalid_password', error.message);\n\t\t}\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn failureResult('kdf_iterations_exceeded', error.message);\n\t\t}\n\t\treturn decodeFailureResult(error, DECODE_LIMIT_CODES, 'Malformed encrypted key');\n\t}\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiDerOrThrow` for the throwing variant\n */\nexport function importSpkiDer(\n\tder: Uint8Array,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiDerOrThrow(der, algorithm));\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const pem = `-----BEGIN PUBLIC KEY-----\n * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n * -----END PUBLIC KEY-----`;\n * const key = await importSpkiPemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport function importSpkiPemOrThrow(\n\tpem: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importSpkiDerOrThrow(pemDecodeOrThrow('PUBLIC KEY', pem), algorithm);\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiPemOrThrow` for the throwing variant\n */\nexport function importSpkiPem(\n\tpem: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiPemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input with headers\n */\nexport function importSpkiBase64OrThrow(\n\tbase64: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 SubjectPublicKeyInfo');\n\t}\n\treturn importSpkiDerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see `importSpkiBase64OrThrow` for the throwing variant\n */\nexport function importSpkiBase64(\n\tbase64: string,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiBase64OrThrow(base64, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * When `algorithm` is omitted, the algorithm (and, for EC keys, the curve) is\n * inferred from the PrivateKeyInfo's own `privateKeyAlgorithm` — useful for\n * keys whose type isn't known ahead of time. Pass `algorithm` to additionally\n * assert that the DER matches an expected algorithm.\n *\n * An RFC 5958 v2 `OneAsymmetricKey` carrying `attributes [0]` or `publicKey [1]`\n * is reduced to its v1 fields for the platform import, which Bun 1.3.14 and\n * earlier rejects outright\n * ([oven-sh/bun#35432](https://github.com/oven-sh/bun/issues/35432)). A\n * `publicKey [1]` field is checked against the private key it accompanies.\n *\n * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Optional expected algorithm; must match key contents when given\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed, encodes an unsupported algorithm, doesn't match `algorithm`, or carries a `publicKey [1]` that is not the private key's own\n *\n * @see {@linkcode exportPkcs8Der} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input\n * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8\n */\nexport async function importPkcs8DerOrThrow(\n\tder: Uint8Array,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet parsedPrivateKey: ReturnType<typeof parsePkcs8PrivateKey>;\n\ttry {\n\t\tparsedPrivateKey = parsePkcs8PrivateKey(der);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tlet importInput: PrivateKeyImportInput;\n\tif (algorithm === undefined) {\n\t\timportInput = inferKeyImportInput(parsedPrivateKey, 'Unsupported PKCS#8 private key algorithm');\n\t} else {\n\t\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\t\timportInput = algorithm;\n\t}\n\tlet privateKey: CryptoKey;\n\ttry {\n\t\tprivateKey = await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(parsedPrivateKey.v1Der),\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tprivateKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst declaredPublicKey = parsedPrivateKey.declaredPublicKey;\n\tif (declaredPublicKey !== undefined) {\n\t\tawait assertDeclaredPublicKeyMatches(privateKey, declaredPublicKey);\n\t}\n\treturn privateKey;\n}\n\n/**\n * Reject a OneAsymmetricKey whose `publicKey [1]` field is not the public key of\n * its own `privateKey`.\n *\n * RFC 8410 Appendix A: \"Key mismatch errors: If a public key is provided, it may\n * not agree with the private key because either it is wrong or the wrong\n * algorithm was used.\"\n */\nasync function assertDeclaredPublicKeyMatches(\n\tprivateKey: CryptoKey,\n\tdeclared: Uint8Array,\n): Promise<void> {\n\tconst spki = await exportSpkiDer(await derivePublicKey(privateKey));\n\tconst subjectPublicKey = readSequenceChildren(spki)[1];\n\tif (subjectPublicKey === undefined || subjectPublicKey.tag !== 0x03) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst derived = subjectPublicKey.value.slice(1);\n\tif (\n\t\tderived.length !== declared.length ||\n\t\tderived.some((byte, index) => byte !== declared[index])\n\t) {\n\t\tthrow new Error('PKCS#8 publicKey does not match the private key');\n\t}\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8DerOrThrow` for the throwing variant\n */\nexport function importPkcs8Der(\n\tder: Uint8Array,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8DerOrThrow(der, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * When `algorithm` is omitted, it is inferred from the key's own\n * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).\n *\n * @example\n * ```ts\n * const key = await importPkcs8PemOrThrow(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * const inferred = await importPkcs8PemOrThrow(pemString);\n * ```\n */\nexport function importPkcs8PemOrThrow(\n\tpem: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(pemDecodeOrThrow('PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8PemOrThrow` for the throwing variant\n */\nexport function importPkcs8Pem(\n\tpem: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Decrypts the PBES2 envelope using the provided password, then imports the key.\n *\n * When `algorithm` is omitted, it is inferred from the decrypted key's own\n * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).\n *\n * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Optional expected algorithm; must match decrypted key when given\n * @param options - KDF work-factor limit\n *\n * @throws {Error} If DER is malformed, password is wrong, the PBKDF2 iteration\n * count exceeds `options.maxKdfIterations`, or algorithm doesn't match\n *\n * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation\n */\nexport async function importEncryptedPkcs8DerOrThrow(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<CryptoKey> {\n\treturn await importEncryptedPkcs8WithBudget(der, password, algorithm, createKdfBudget(options));\n}\n\nasync function importEncryptedPkcs8WithBudget(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput | undefined,\n\tbudget: KdfBudget,\n): Promise<CryptoKey> {\n\tconst envelope = readEncryptedPkcs8Envelope(der);\n\tconst decrypted = await decryptPbes2(\n\t\tenvelope.algorithmIdentifierDer,\n\t\tenvelope.encryptedData,\n\t\tpassword,\n\t\tbudget,\n\t);\n\tassertDecryptedPrivateKey(\n\t\t() => parsePkcs8PrivateKey(decrypted),\n\t\t'Invalid password or encrypted content',\n\t);\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\n}\n\n/** Splits a DER `EncryptedPrivateKeyInfo` into its AlgorithmIdentifier DER and encryptedData bytes. */\nfunction readEncryptedPkcs8Envelope(der: Uint8Array): {\n\treadonly algorithmIdentifierDer: Uint8Array;\n\treadonly encryptedData: Uint8Array;\n} {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst algorithmIdentifier = children[0];\n\tconst encryptedData = children[1];\n\tif (\n\t\tchildren.length !== 2 ||\n\t\talgorithmIdentifier === undefined ||\n\t\tencryptedData === undefined ||\n\t\tencryptedData.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\treturn {\n\t\talgorithmIdentifierDer: der.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData: encryptedData.value,\n\t};\n}\n\n/**\n * Reads the PBES2 encryption parameters of a DER PKCS#8\n * `EncryptedPrivateKeyInfo` (RFC 5958 §3) without the password: PBKDF2\n * iteration count, salt, and PRF, plus the AES-CBC variant and IV.\n * Throws on malformed DER, a non-PBES2 encryption algorithm, or a PBKDF2\n * iteration count outside 1 to 4294967295.\n */\nexport function inspectEncryptedPkcs8Der(der: Uint8Array): Pbes2Parameters {\n\treturn parsePbes2AlgorithmIdentifier(readEncryptedPkcs8Envelope(der).algorithmIdentifierDer);\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Der(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() =>\n\t\timportEncryptedPkcs8DerOrThrow(der, password, algorithm, options),\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * When `algorithm` is omitted, it is inferred from the decrypted key's own\n * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8PemOrThrow(pem, 'secret', { kind: 'rsa' });\n * const inferred = await importEncryptedPkcs8PemOrThrow(pem, 'secret');\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<CryptoKey> {\n\tconst budget = createKdfBudget(options);\n\treturn await importEncryptedPkcs8WithBudget(\n\t\tpemDecodeOrThrow('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\n\t\tbudget,\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: PrivateKeyImportInput,\n\toptions?: ImportEncryptedKeyOptions,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() =>\n\t\timportEncryptedPkcs8PemOrThrow(pem, password, algorithm, options),\n\t);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportPkcs1Der} for the inverse operation\n * @see {@linkcode importPkcs1Pem} for PEM input\n */\nexport function importPkcs1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1DerOrThrow` for the throwing variant\n */\nexport function importPkcs1Der(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * Expects the `-----BEGIN RSA PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM\n */\nexport function importPkcs1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs1DerOrThrow(pemDecodeOrThrow('RSA PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1PemOrThrow` for the throwing variant\n */\nexport function importPkcs1Pem(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedPkcs1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('RSA PRIVATE KEY', pem, password);\n\tassertDecryptedPrivateKey(\n\t\t() => parsePkcs1PrivateKey(decrypted),\n\t\t'Invalid password or encrypted PEM content',\n\t);\n\treturn importPkcs1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input with headers\n */\nexport function importPkcs8Base64OrThrow(\n\tbase64: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 PKCS#8 private key');\n\t}\n\treturn importPkcs8DerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see `importPkcs8Base64OrThrow` for the throwing variant\n */\nexport function importPkcs8Base64(\n\tbase64: string,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8Base64OrThrow(base64, algorithm));\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import.\n * When the ECPrivateKey carries the optional RFC 5915 `parameters [0]` field\n * (OpenSSL always writes it), its named-curve OID must match `algorithm.curve`;\n * when the field is absent, the caller-supplied curve is trusted.\n *\n * When `algorithm` is omitted, the curve is inferred from the embedded\n * `parameters [0]` field; a key without a supported named curve then fails.\n *\n * @throws {Error} If DER is not an ECPrivateKey, its embedded curve doesn't\n * match `algorithm`, or no curve is available (neither embedded nor supplied)\n *\n * @see {@linkcode exportSec1Der} for the inverse operation\n * @see {@linkcode importSec1Pem} for PEM input\n */\nexport async function importSec1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm?: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tlet parsedSec1: ReturnType<typeof parseSec1PrivateKey>;\n\ttry {\n\t\tparsedSec1 = parseSec1PrivateKey(der);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed SEC 1 private key');\n\t}\n\tlet importInput: ImportEcKeyInput;\n\tif (algorithm === undefined) {\n\t\timportInput = inferSec1ImportInput(parsedSec1);\n\t} else {\n\t\tassertSec1MatchesRequestedAlgorithm(parsedSec1, algorithm);\n\t\timportInput = algorithm;\n\t}\n\treturn await importPkcs8DerOrThrow(wrapSec1InPkcs8(der, importInput.curve), importInput);\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1DerOrThrow` for the throwing variant\n */\nexport function importSec1Der(\n\tder: Uint8Array,\n\talgorithm?: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label. When `algorithm` is\n * omitted, the curve is inferred from the embedded `parameters [0]` field\n * (see {@linkcode importSec1DerOrThrow}).\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport function importSec1PemOrThrow(\n\tpem: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importSec1DerOrThrow(pemDecodeOrThrow('EC PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1PemOrThrow` for the throwing variant\n */\nexport function importSec1Pem(\n\tpem: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedSec1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('EC PRIVATE KEY', pem, password);\n\tassertDecryptedPrivateKey(\n\t\t() => parseSec1PrivateKey(decrypted),\n\t\t'Invalid password or encrypted PEM content',\n\t);\n\treturn importSec1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * @see `importEncryptedSec1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedSec1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm?: ImportEcKeyInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * When `algorithm` is omitted, it is inferred from the JWK's own `kty`, `crv`,\n * and `alg` members (e.g. `PS256` → RSA-PSS/SHA-256, `RSA-OAEP-256` →\n * RSA-OAEP/SHA-256; an RSA JWK without `alg` defaults to PKCS#1 v1.5 with\n * SHA-256). Pass `algorithm` to additionally assert an expected algorithm.\n *\n * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Optional expected algorithm; must match JWK's `kty` and `crv` when given\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm?: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst importInput = algorithm ?? inferJwkImportInput(jwk);\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, importInput);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'jwk',\n\t\t\tjwk,\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tpublicKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed public JWK');\n\t}\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @see `importPublicJwkOrThrow` for the throwing variant\n */\nexport function importPublicJwk(\n\tjwk: JsonWebKey,\n\talgorithm?: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPublicJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * When `algorithm` is omitted, it is inferred from the JWK's own `kty`, `crv`,\n * and `alg` members (see {@linkcode importPublicJwkOrThrow}).\n *\n * @param jwk - JSON Web Key object with private key components\n * @param algorithm - Optional expected algorithm; must match JWK's `kty` and `crv` when given\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If JWK is malformed, lacks private key material, encodes an\n * unsupported algorithm, or doesn't match `algorithm`\n *\n * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwkOrThrow(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * const inferred = await importPrivateJwkOrThrow(jwk);\n * ```\n *\n * @see {@linkcode exportPrivateJwk} for the inverse operation\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tconst importInput = algorithm ?? inferJwkImportInput(jwk);\n\tassertPrivateJwkMatchesRequestedAlgorithm(jwk, importInput);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'jwk',\n\t\t\tjwk,\n\t\t\ttoImportAlgorithm(importInput),\n\t\t\ttrue,\n\t\t\tprivateKeyUsages(importInput),\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed private JWK');\n\t}\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @see `importPrivateJwkOrThrow` for the throwing variant\n */\nexport function importPrivateJwk(\n\tjwk: JsonWebKey,\n\talgorithm?: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPrivateJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Encrypt a small message with an RSA-OAEP public key.\n *\n * The key must have been generated or imported with `{ kind: 'rsa', scheme: 'oaep' }`.\n * RSA-OAEP encrypts at most modulus bytes − 2 × hash bytes − 2 per call\n * (190 bytes for a 2048-bit key with SHA-256) — encrypt a symmetric key, not\n * bulk data.\n *\n * @param publicKey - RSA-OAEP public `CryptoKey` with `encrypt` usage\n * @param plaintext - Message bytes, at most the OAEP capacity of the key\n * @param options - Optional OAEP label bound to the ciphertext\n *\n * @throws {Error} If the key is not an RSA-OAEP public encryption key, or the\n * plaintext exceeds the key's OAEP capacity\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });\n * const ciphertext = await encryptRsaOaepOrThrow(\n * \tkeys.publicKey,\n * \tnew TextEncoder().encode('session key'),\n * );\n * ```\n *\n * @see {@linkcode decryptRsaOaepOrThrow} for the inverse operation\n * @see `encryptRsaOaep` for the Result-returning variant\n */\nexport async function encryptRsaOaepOrThrow(\n\tpublicKey: CryptoKey,\n\tplaintext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<Uint8Array> {\n\tconst keyProblem = validateRsaOaepKey(publicKey, 'public', 'encrypt');\n\tif (keyProblem !== undefined) {\n\t\tthrow new Error(keyProblem);\n\t}\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.encrypt(\n\t\t\t\ttoRsaOaepParams(options),\n\t\t\t\tpublicKey,\n\t\t\t\ttoArrayBuffer(plaintext),\n\t\t\t),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tthrow new Error(\n\t\t\t'Plaintext exceeds the RSA-OAEP capacity of the key (modulus bytes − 2 × hash bytes − 2)',\n\t\t);\n\t}\n}\n\n/**\n * Encrypt a small message with an RSA-OAEP public key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });\n * const encrypted = await encryptRsaOaep(keys.publicKey, plaintext);\n * if (!encrypted.ok) {\n * \t// encrypted.code: 'invalid_key' | 'message_too_long'\n * \tthrow new Error(encrypted.message);\n * }\n * const ciphertext = encrypted.value;\n * ```\n *\n * @see `encryptRsaOaepOrThrow` for the throwing variant\n */\nexport async function encryptRsaOaep(\n\tpublicKey: CryptoKey,\n\tplaintext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<EncryptRsaOaepResult> {\n\tconst keyProblem = validateRsaOaepKey(publicKey, 'public', 'encrypt');\n\tif (keyProblem !== undefined) {\n\t\treturn failureResult('invalid_key', keyProblem);\n\t}\n\ttry {\n\t\treturn successResult(await encryptRsaOaepOrThrow(publicKey, plaintext, options));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'message_too_long',\n\t\t\terror instanceof Error ? error.message : 'Plaintext exceeds the RSA-OAEP capacity',\n\t\t);\n\t}\n}\n\n/**\n * Decrypt an RSA-OAEP ciphertext with the matching private key.\n *\n * The key must have been generated or imported with `{ kind: 'rsa', scheme: 'oaep' }`,\n * and `options.label` must repeat the label used at encryption time (if any).\n *\n * @param privateKey - RSA-OAEP private `CryptoKey` with `decrypt` usage\n * @param ciphertext - Ciphertext produced by {@linkcode encryptRsaOaep} (or any RSA-OAEP encryptor)\n * @param options - OAEP label matching the one bound at encryption\n *\n * @throws {Error} If the key is not an RSA-OAEP private decryption key, or\n * decryption fails — wrong key, wrong label, or corrupted ciphertext (OAEP\n * deliberately does not reveal which)\n *\n * @example\n * ```ts\n * const plaintext = await decryptRsaOaepOrThrow(keys.privateKey, ciphertext);\n * ```\n *\n * @see {@linkcode encryptRsaOaepOrThrow} for the inverse operation\n * @see `decryptRsaOaep` for the Result-returning variant\n */\nexport async function decryptRsaOaepOrThrow(\n\tprivateKey: CryptoKey,\n\tciphertext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<Uint8Array> {\n\tconst keyProblem = validateRsaOaepKey(privateKey, 'private', 'decrypt');\n\tif (keyProblem !== undefined) {\n\t\tthrow new Error(keyProblem);\n\t}\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\ttoRsaOaepParams(options),\n\t\t\t\tprivateKey,\n\t\t\t\ttoArrayBuffer(ciphertext),\n\t\t\t),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tthrow new Error('RSA-OAEP decryption failed: wrong key, wrong label, or corrupted ciphertext');\n\t}\n}\n\n/**\n * Decrypt an RSA-OAEP ciphertext with the matching private key.\n *\n * @example\n * ```ts\n * const decrypted = await decryptRsaOaep(keys.privateKey, ciphertext);\n * if (!decrypted.ok) {\n * \t// decrypted.code: 'invalid_key' | 'decryption_failed'\n * \tthrow new Error(decrypted.message);\n * }\n * const plaintext = decrypted.value;\n * ```\n *\n * @see `decryptRsaOaepOrThrow` for the throwing variant\n */\nexport async function decryptRsaOaep(\n\tprivateKey: CryptoKey,\n\tciphertext: Uint8Array,\n\toptions: RsaOaepOptions = {},\n): Promise<DecryptRsaOaepResult> {\n\tconst keyProblem = validateRsaOaepKey(privateKey, 'private', 'decrypt');\n\tif (keyProblem !== undefined) {\n\t\treturn failureResult('invalid_key', keyProblem);\n\t}\n\ttry {\n\t\treturn successResult(await decryptRsaOaepOrThrow(privateKey, ciphertext, options));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'decryption_failed',\n\t\t\terror instanceof Error ? error.message : 'RSA-OAEP decryption failed',\n\t\t);\n\t}\n}\n\n/** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */\nfunction toGenerateKeyAlgorithm(\n\talgorithm: KeyAlgorithmInput,\n): EcKeyGenParams | RsaHashedKeyGenParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\tmodulusLength: algorithm.modulusLength ?? 2048,\n\t\t\t\tpublicExponent: Uint8Array.of(0x01, 0x00, 0x01),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve ?? 'P-256',\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled KeyAlgorithmInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */\nfunction toImportAlgorithm(\n\talgorithm: PublicKeyImportInput,\n): EcKeyImportParams | RsaHashedImportParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve,\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PublicKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Rejects decrypted plaintext that is not the private-key structure it should be.\n *\n * PBES2 and traditional PEM both encrypt with unauthenticated AES-CBC, where a\n * wrong key clears the padding check roughly once in every 256 attempts and\n * yields random plaintext. Structure is the only integrity signal left, so\n * plaintext that fails to parse means the password was wrong or the ciphertext\n * was corrupted, not that the enclosing input was malformed.\n */\nfunction assertDecryptedPrivateKey(parse: () => unknown, message: string): void {\n\ttry {\n\t\tparse();\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow wrongPasswordError(message);\n\t}\n}\n\n/** Structural check for a PKCS#1 RSAPrivateKey, including optional multiprime fields. */\nfunction parsePkcs1PrivateKey(der: Uint8Array): void {\n\tconst children = readSequenceChildren(der);\n\tconst version = children[0];\n\tif (\n\t\tversion === undefined ||\n\t\tversion.tag !== 0x02 ||\n\t\tversion.value.length !== 1 ||\n\t\t!children.slice(1, 9).every((child) => child.tag === 0x02)\n\t) {\n\t\tthrow new Error('Malformed PKCS#1 private key');\n\t}\n\tconst versionValue = version.value[0];\n\tif (versionValue === 0x00 && children.length === 9) {\n\t\treturn;\n\t}\n\tconst otherPrimeInfos = children[9];\n\tif (\n\t\tversionValue !== 0x01 ||\n\t\tchildren.length !== 10 ||\n\t\totherPrimeInfos === undefined ||\n\t\t!isOtherPrimeInfosShape(der, otherPrimeInfos)\n\t) {\n\t\tthrow new Error('Malformed PKCS#1 private key');\n\t}\n}\n\n/** RFC 8017 Appendix A.1.2: OtherPrimeInfos is a non-empty SEQUENCE OF three-INTEGER entries. */\nfunction isOtherPrimeInfosShape(source: Uint8Array, element: DerElement): boolean {\n\tif (element.tag !== 0x30) {\n\t\treturn false;\n\t}\n\tconst otherPrimeInfosDer = source.slice(element.start - element.headerLength, element.end);\n\tconst infos = readSequenceChildren(otherPrimeInfosDer);\n\tif (infos.length === 0) {\n\t\treturn false;\n\t}\n\treturn infos.every((info) => {\n\t\tif (info.tag !== 0x30) {\n\t\t\treturn false;\n\t\t}\n\t\tconst fields = readSequenceChildren(\n\t\t\totherPrimeInfosDer.slice(info.start - info.headerLength, info.end),\n\t\t);\n\t\treturn fields.length === 3 && fields.every((field) => field.tag === 0x02);\n\t});\n}\n\n/** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */\nfunction parsePkcs8PrivateKey(der: Uint8Array): {\n\t/** OID identifying the algorithm family (e.g. rsaEncryption, ecPublicKey). */\n\treadonly algorithmOid: string;\n\t/** Optional algorithm parameter OID (e.g. named curve for EC keys). */\n\treadonly parametersOid?: string;\n\t/** Optional algorithm parameter tag. */\n\treadonly parametersTag?: number;\n\t/** Raw DER of the inner private key (PKCS#1 for RSA, SEC 1 for EC). */\n\treadonly privateKeyDer: Uint8Array;\n\t/** The same key reduced to `version`, `privateKeyAlgorithm`, and `privateKey`. */\n\treadonly v1Der: Uint8Array;\n\t/** `publicKey [1]` octets without the BIT STRING unused-bits octet, when the field is present. */\n\treadonly declaredPublicKey?: Uint8Array;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst version = children[0];\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tversion === undefined ||\n\t\tversion.tag !== 0x02 ||\n\t\talgorithm === undefined ||\n\t\talgorithm.tag !== 0x30 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst declaredPublicKey = validateOneAsymmetricKeyTail(children.slice(3));\n\tif (readPkcs8Version(version.value) !== (declaredPublicKey === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst algorithmDer = der.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\talgorithmOid.tag !== 0x06 ||\n\t\talgorithmChildren.length < 1 ||\n\t\talgorithmChildren.length > 2\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst parameters = algorithmChildren[1];\n\tconst oid = decodeObjectIdentifier(algorithmOid.value);\n\tif (CURVE_PRIVATE_KEY_ALGORITHM_OIDS.includes(oid)) {\n\t\tassertCurvePrivateKey(privateKey.value);\n\t}\n\treturn {\n\t\talgorithmOid: oid,\n\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t...(parameters?.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t: {}),\n\t\tprivateKeyDer: privateKey.value,\n\t\tv1Der:\n\t\t\tchildren.length === 3\n\t\t\t\t? der\n\t\t\t\t: sequence([integer(Uint8Array.of(0)), algorithmDer, octetString(privateKey.value)]),\n\t\t...(declaredPublicKey === undefined ? {} : { declaredPublicKey }),\n\t};\n}\n\n/** Algorithms whose `privateKey` field holds an RFC 8410 §7 `CurvePrivateKey`. */\nconst CURVE_PRIVATE_KEY_ALGORITHM_OIDS: readonly string[] = [\n\tOIDS.x25519,\n\tOIDS.x448,\n\tOIDS.ed25519,\n\tOIDS.ed448,\n];\n\n/**\n * Reject a `privateKey` field that does not hold exactly one DER `CurvePrivateKey`.\n *\n * RFC 8410 §7: \"when encoding a OneAsymmetricKey object, the private key is\n * wrapped in a CurvePrivateKey object and wrapped by the OCTET STRING of the\n * 'privateKey' field\", and `CurvePrivateKey ::= OCTET STRING`.\n */\nfunction assertCurvePrivateKey(content: Uint8Array): void {\n\tconst curvePrivateKey = readRootElement(content);\n\tif (curvePrivateKey.tag !== 0x04) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n}\n\n/**\n * Validate the OneAsymmetricKey tail after `privateKey` and return the\n * `publicKey [1]` octets when the field is present.\n *\n * RFC 5958 §2 encodes `attributes [0]` as an IMPLICIT constructed `SET OF`\n * (tag `A0`); RFC 8410 §7 adds `publicKey [1]` as an IMPLICIT primitive\n * `BIT STRING` (tag `81`) after it. Each appears at most once and in that order.\n * The type's two X.680 extensibility markers admit later additions, which take\n * the next context-specific numbers, so `[2]` and above are tolerated and every\n * other class is malformed.\n */\nfunction validateOneAsymmetricKeyTail(tail: readonly DerElement[]): Uint8Array | undefined {\n\tlet seenAttributes = false;\n\tlet publicKey: Uint8Array | undefined;\n\tlet seenUnknown = false;\n\tfor (const child of tail) {\n\t\tconst contextNumber = (child.tag & 0xc0) === 0x80 ? child.tagNumber : -1;\n\t\tif (contextNumber === 0) {\n\t\t\tif (seenAttributes || publicKey !== undefined || seenUnknown || child.tag !== 0xa0) {\n\t\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t\t}\n\t\t\tassertOneAsymmetricKeyAttributes(child.value);\n\t\t\tseenAttributes = true;\n\t\t} else if (contextNumber === 1) {\n\t\t\tif (publicKey !== undefined || seenUnknown || child.tag !== 0x81) {\n\t\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t\t}\n\t\t\tpublicKey = readPublicKeyBitString(child.value);\n\t\t} else if (contextNumber >= 2) {\n\t\t\tseenUnknown = true;\n\t\t} else {\n\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t}\n\t}\n\treturn publicKey;\n}\n\n/**\n * Reject an `attributes [0]` field that does not hold a `SET OF Attribute`.\n *\n * RFC 5958 §2 types the field `Attributes ::= SET OF Attribute`, over the\n * `Attribute ::= SEQUENCE { attrType OBJECT IDENTIFIER, attrValues SET OF\n * AttributeValue }` of RFC 5652 §5.3. The implicit tag has replaced the SET OF\n * tag, so the members are read back under a universal constructed one.\n */\nfunction assertOneAsymmetricKeyAttributes(content: Uint8Array): void {\n\tconst attributes = tlv(0x30, content);\n\tfor (const attribute of readSequenceChildren(attributes)) {\n\t\tif (attribute.tag !== 0x30) {\n\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t}\n\t\tconst fields = readSequenceChildren(\n\t\t\tattributes.slice(attribute.start - attribute.headerLength, attribute.end),\n\t\t);\n\t\tconst type = fields[0];\n\t\tconst values = fields[1];\n\t\tif (\n\t\t\tfields.length !== 2 ||\n\t\t\ttype === undefined ||\n\t\t\ttype.tag !== 0x06 ||\n\t\t\tvalues === undefined ||\n\t\t\tvalues.tag !== 0x31\n\t\t) {\n\t\t\tthrow new Error('Malformed PKCS#8 private key');\n\t\t}\n\t}\n}\n\n/** Reject a `publicKey [1]` BIT STRING that is not octet-aligned or carries no key octets. */\nfunction readPublicKeyBitString(content: Uint8Array): Uint8Array {\n\tif (content.length < 2 || content[0] !== 0x00) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\treturn content.slice(1);\n}\n\n/** Decode the canonical RFC 5958 version INTEGER content, `v1(0)` or `v2(1)`. */\nfunction readPkcs8Version(content: Uint8Array): number {\n\tconst value = content[0];\n\tif (content.length !== 1 || (value !== 0x00 && value !== 0x01)) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\treturn value;\n}\n\n/**\n * Extract the optional `parameters [0]` curve identifier from a SEC 1 ECPrivateKey.\n *\n * RFC 5915 §3: `ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) }\n * (ecPrivkeyVer1), privateKey OCTET STRING, parameters [0] ECParameters\n * {{ NamedCurve }} OPTIONAL, publicKey [1] BIT STRING OPTIONAL }`.\n */\nfunction parseSec1PrivateKey(der: Uint8Array): {\n\t/** Optional ECParameters tag inside `parameters [0]` (0x06 for a named curve). */\n\treadonly parametersTag?: number;\n\t/** Optional named-curve OID when the ECParameters choice is an OBJECT IDENTIFIER. */\n\treadonly parametersOid?: string;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst version = children[0];\n\tconst privateKey = children[1];\n\tconst third = children[2];\n\tconst fourth = children[3];\n\tif (\n\t\tchildren.length < 2 ||\n\t\tchildren.length > 4 ||\n\t\tversion === undefined ||\n\t\tversion.tag !== 0x02 ||\n\t\tversion.value.length !== 1 ||\n\t\tversion.value[0] !== 0x01 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04 ||\n\t\t(third !== undefined && third.tag !== 0xa0 && third.tag !== 0xa1) ||\n\t\t(fourth !== undefined && (third?.tag !== 0xa0 || fourth.tag !== 0xa1))\n\t) {\n\t\tthrow new Error('Malformed SEC 1 private key');\n\t}\n\tconst parameters = third?.tag === 0xa0 ? third : undefined;\n\tif (parameters === undefined) {\n\t\treturn {};\n\t}\n\tconst ecParameters = readRootElement(parameters.value);\n\treturn {\n\t\tparametersTag: ecParameters.tag,\n\t\t...(ecParameters.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(ecParameters.value) }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Ensure a SEC 1 ECPrivateKey carries the RFC 5915 `parameters [0]` named\n * curve. WebCrypto's PKCS#8 export omits it from the inner ECPrivateKey (the\n * curve lives in the envelope's privateKeyAlgorithm), but RFC 5915 wants it in\n * standalone SEC 1 — and OpenSSL always writes it. Injecting it keeps exports\n * self-describing, so they re-import without an explicit curve.\n */\nfunction ensureSec1NamedCurveParameters(\n\tsec1Der: Uint8Array,\n\tcurveOid: string | undefined,\n): Uint8Array {\n\tconst children = readSequenceChildren(sec1Der);\n\tif (children.some((child) => child.tag === 0xa0)) {\n\t\treturn new Uint8Array(sec1Der);\n\t}\n\tif (curveOid === undefined) {\n\t\tthrow new Error('SEC1 export requires a named curve in the PKCS#8 privateKeyAlgorithm');\n\t}\n\tconst raw = (child: DerElement): Uint8Array =>\n\t\tsec1Der.slice(child.start - child.headerLength, child.end);\n\t// RFC 5915 field order: version, privateKey, parameters [0], publicKey [1].\n\treturn sequence([\n\t\t...children.slice(0, 2).map(raw),\n\t\texplicitContext(0, objectIdentifier(curveOid)),\n\t\t...children.slice(2).map(raw),\n\t]);\n}\n\n/** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapPkcs1InPkcs8(der: Uint8Array): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapSec1InPkcs8(der: Uint8Array, curve: ImportEcKeyInput['curve']): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Project a private JWK onto its public-only members, discarding private key material. */\nfunction toPublicJwk(jwk: JsonWebKey, usage: KeyUsage): JsonWebKey {\n\tif (jwk.kty !== 'RSA' && jwk.kty !== 'EC' && jwk.kty !== 'OKP') {\n\t\tthrow new Error(`Cannot derive public key: unsupported JWK key type ${String(jwk.kty)}`);\n\t}\n\tconst publicJwk: JsonWebKey = { ...jwk };\n\t// Strip every private component: RSA (d, p, q, dp, dq, qi, oth), EC/OKP (d).\n\tfor (const field of ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] as const) {\n\t\tdelete publicJwk[field];\n\t}\n\tpublicJwk.key_ops = [usage];\n\tpublicJwk.ext = true;\n\treturn publicJwk;\n}\n\n/**\n * Single source of truth for the NIST curve ↔ named-curve OID mapping, read in\n * both directions by {@linkcode curveToOid} and {@linkcode oidToCurve}.\n */\nconst EC_CURVE_OIDS = [\n\t['P-256', OIDS.prime256v1],\n\t['P-384', OIDS.secp384r1],\n\t['P-521', OIDS.secp521r1],\n] as const satisfies readonly (readonly [EcNamedCurve, string])[];\n\n/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcKeyInput['curve']): string {\n\tfor (const [name, oid] of EC_CURVE_OIDS) {\n\t\tif (name === curve) {\n\t\t\treturn oid;\n\t\t}\n\t}\n\tthrow new Error(`Unsupported EC curve: ${curve}`);\n}\n\n/** Map an ASN.1 curve OID string back to its curve name, or `undefined` if unrecognized. */\nfunction oidToCurve(oid: string): EcNamedCurve | undefined {\n\tfor (const [name, curveOid] of EC_CURVE_OIDS) {\n\t\tif (curveOid === oid) {\n\t\t\treturn name;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */\nfunction rsaSchemeToWebCryptoAlgorithmName(\n\tscheme: RsaScheme | undefined,\n): 'RSASSA-PKCS1-v1_5' | 'RSA-PSS' | 'RSA-OAEP' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\tif (scheme === 'oaep') {\n\t\treturn 'RSA-OAEP';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\n}\n\n/** `true` when the algorithm input selects RSA-OAEP, whose keys carry encrypt/decrypt usages. */\nfunction isRsaOaepInput(algorithm: KeyAlgorithmInput | PublicKeyImportInput): boolean {\n\treturn algorithm.kind === 'rsa' && algorithm.scheme === 'oaep';\n}\n\n/** Key usages for an imported public key: `verify`, or `encrypt` for RSA-OAEP. */\nfunction publicKeyUsages(algorithm: PublicKeyImportInput): KeyUsage[] {\n\treturn isRsaOaepInput(algorithm) ? ['encrypt'] : ['verify'];\n}\n\n/** Key usages for an imported private key: `sign`, or `decrypt` for RSA-OAEP. */\nfunction privateKeyUsages(algorithm: PrivateKeyImportInput): KeyUsage[] {\n\treturn isRsaOaepInput(algorithm) ? ['decrypt'] : ['sign'];\n}\n\n/**\n * Diagnose a key unfit for the given RSA-OAEP operation.\n *\n * Returns a human-readable problem description, or `undefined` when the key is\n * usable — keeping key-level failures (`'invalid_key'`) separable from\n * ciphertext-level failures before WebCrypto is ever called.\n */\nfunction validateRsaOaepKey(\n\tkey: CryptoKey,\n\ttype: 'public' | 'private',\n\tusage: 'encrypt' | 'decrypt',\n): string | undefined {\n\tconst operation = usage === 'encrypt' ? 'encryption' : 'decryption';\n\tif (key.type !== type) {\n\t\treturn `RSA-OAEP ${operation} requires a ${type} CryptoKey`;\n\t}\n\tif (key.algorithm.name !== 'RSA-OAEP') {\n\t\treturn `RSA-OAEP ${operation} requires an RSA-OAEP key (got ${key.algorithm.name}); generate or import the key with scheme: 'oaep'`;\n\t}\n\tif (!key.usages.includes(usage)) {\n\t\treturn `RSA-OAEP ${operation} requires a key with '${usage}' usage`;\n\t}\n\treturn undefined;\n}\n\n/** Build the WebCrypto RSA-OAEP params, attaching the optional label. */\nfunction toRsaOaepParams(options: RsaOaepOptions): RsaOaepParams {\n\treturn {\n\t\tname: 'RSA-OAEP',\n\t\t...(options.label === undefined ? {} : { label: toArrayBuffer(options.label) }),\n\t};\n}\n\n/** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */\nasync function encryptTraditionalPem(\n\tlabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tder: Uint8Array,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tif (iv.length !== 16) {\n\t\tthrow new Error('Traditional PEM encryption requires a 16-byte IV');\n\t}\n\tconst cipher = options.cipher ?? 'AES-256-CBC';\n\tconst key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, [\n\t\t'encrypt',\n\t]);\n\tconst encrypted = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(der),\n\t\t),\n\t);\n\tconst body =\n\t\tbase64Encode(encrypted)\n\t\t\t.match(/.{1,64}/g)\n\t\t\t?.join('\\n') ?? '';\n\treturn [\n\t\t`-----BEGIN ${label}-----`,\n\t\t'Proc-Type: 4,ENCRYPTED',\n\t\t`DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,\n\t\t'',\n\t\tbody,\n\t\t`-----END ${label}-----`,\n\t].join('\\n');\n}\n\n/** Decrypt a `Proc-Type: 4,ENCRYPTED` PEM block, RFC 1421 §4.6 headers, to plaintext DER. */\nasync function decryptTraditionalPem(\n\texpectedLabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tpem: string,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parsed = parseTraditionalPemOrThrow(pem);\n\tif (parsed.label !== expectedLabel) {\n\t\tthrow new Error(`Expected ${expectedLabel} PEM block`);\n\t}\n\tconst dekInfo = parsed.headers.get('DEK-Info');\n\tconst procType = parsed.headers.get('Proc-Type');\n\tif (procType === undefined || !isEncryptedProcType(procType) || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',').map(trimLwsp);\n\tif (!isTraditionalPemCipher(cipher) || ivHex === undefined) {\n\t\tthrow new Error(\n\t\t\t'Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported',\n\t\t);\n\t}\n\tif (!isTraditionalPemIvHex(ivHex)) {\n\t\tthrow new Error(\n\t\t\t'Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters',\n\t\t);\n\t}\n\tconst iv = hexToBytes(ivHex);\n\tconst key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ['decrypt']);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(base64Decode(parsed.base64Body)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted PEM content');\n\t}\n}\n\n/** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */\nfunction importTraditionalPemAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst keyLength = traditionalPemCipherKeyLength(cipher);\n\tconst keyBytes = opensslBytesToKey(password, salt, keyLength / 8);\n\treturn getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'AES-CBC', length: keyLength },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/**\n * RFC 1421 §4.6.1.1 `Proc-Type: 4,ENCRYPTED`.\n *\n * Fields are trimmed because RFC 822 §3.1.1 unfolding leaves an LWSP-char\n * wherever the header was folded.\n */\nfunction isEncryptedProcType(value: string): boolean {\n\tconst fields = value.split(',');\n\treturn (\n\t\tfields.length === 2 &&\n\t\ttrimLwsp(fields[0] ?? '') === '4' &&\n\t\ttrimLwsp(fields[1] ?? '') === 'ENCRYPTED'\n\t);\n}\n\n/** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */\nfunction isTraditionalPemCipher(\n\tcipher: string | undefined,\n): cipher is 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC' {\n\treturn cipher === 'AES-128-CBC' || cipher === 'AES-192-CBC' || cipher === 'AES-256-CBC';\n}\n\nfunction isTraditionalPemIvHex(value: string): boolean {\n\treturn value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);\n}\n\n/** Return the AES key size in bits for a given cipher name. */\nfunction traditionalPemCipherKeyLength(\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n): 128 | 192 | 256 {\n\tswitch (cipher) {\n\t\tcase 'AES-128-CBC':\n\t\t\treturn 128;\n\t\tcase 'AES-192-CBC':\n\t\t\treturn 192;\n\t\tcase 'AES-256-CBC':\n\t\t\treturn 256;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = cipher;\n\t\t\tthrow new Error(`Unhandled traditional PEM cipher: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */\nfunction opensslBytesToKey(password: string, salt: Uint8Array, length: number): Uint8Array {\n\tconst passwordBytes = new TextEncoder().encode(password);\n\tconst chunks: Uint8Array[] = [];\n\tlet previous = new Uint8Array();\n\tlet total = 0;\n\twhile (total < length) {\n\t\tconst input = new Uint8Array(previous.length + passwordBytes.length + salt.length);\n\t\tinput.set(previous, 0);\n\t\tinput.set(passwordBytes, previous.length);\n\t\tinput.set(salt, previous.length + passwordBytes.length);\n\t\tprevious = md5(input);\n\t\tchunks.push(previous);\n\t\ttotal += previous.length;\n\t}\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tconst slice = chunk.slice(0, Math.min(chunk.length, length - offset));\n\t\tout.set(slice, offset);\n\t\toffset += slice.length;\n\t\tif (offset >= length) {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction parseSpkiDer(der: Uint8Array): {\n\treadonly algorithmOid: string;\n\treadonly parametersOid?: string;\n\treadonly parametersTag?: number;\n} {\n\ttry {\n\t\tconst children = readSequenceChildren(der);\n\t\tif (children.length !== 2) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst algorithm = children[0];\n\t\tconst subjectPublicKey = children[1];\n\t\tif (\n\t\t\talgorithm === undefined ||\n\t\t\talgorithm.tag !== 0x30 ||\n\t\t\tsubjectPublicKey === undefined ||\n\t\t\tsubjectPublicKey.tag !== 0x03\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\textractBitStringValue(subjectPublicKey);\n\t\tconst algorithmChildren = readSequenceChildren(\n\t\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\t);\n\t\tconst algorithmOid = algorithmChildren[0];\n\t\tif (\n\t\t\talgorithmOid === undefined ||\n\t\t\talgorithmOid.tag !== 0x06 ||\n\t\t\talgorithmChildren.length < 1 ||\n\t\t\talgorithmChildren.length > 2\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst parameters = algorithmChildren[1];\n\t\treturn {\n\t\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t\t...(parameters?.tag === 0x06\n\t\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t\t: {}),\n\t\t};\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/**\n * Derive the import algorithm from a key envelope's own AlgorithmIdentifier\n * (SPKI `algorithm` or PKCS#8 `privateKeyAlgorithm` — both share the shape).\n *\n * RSA keys default to the `pkcs1-v1_5`/`SHA-256` import parameters (a plain\n * `rsaEncryption` AlgorithmIdentifier does not encode padding scheme or hash);\n * EC keys carry their curve in the DER; Ed25519 is fully determined by its OID.\n */\nfunction inferKeyImportInput(\n\tparsed: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\tunsupportedMessage: string,\n): PublicKeyImportInput {\n\tswitch (parsed.algorithmOid) {\n\t\tcase OIDS.rsaEncryption:\n\t\t\tif (parsed.parametersTag === undefined || parsed.parametersTag === 0x05) {\n\t\t\t\treturn { kind: 'rsa' };\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OIDS.ecPublicKey: {\n\t\t\tconst curve =\n\t\t\t\tparsed.parametersTag === 0x06 && parsed.parametersOid !== undefined\n\t\t\t\t\t? oidToCurve(parsed.parametersOid)\n\t\t\t\t\t: undefined;\n\t\t\tif (curve !== undefined) {\n\t\t\t\treturn { kind: 'ecdsa', curve };\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase OIDS.ed25519:\n\t\t\tif (parsed.parametersTag === undefined) {\n\t\t\t\treturn { kind: 'ed25519' };\n\t\t\t}\n\t\t\tbreak;\n\t}\n\tthrow new Error(unsupportedMessage);\n}\n\n/**\n * Derive the import curve from a SEC 1 ECPrivateKey's own RFC 5915\n * `parameters [0]` field. SEC 1 encodes no algorithm family (it is EC by\n * definition), so only the named curve needs recovering — and it may be\n * absent, in which case the caller must supply it.\n */\nfunction inferSec1ImportInput(parsedSec1: {\n\treadonly parametersTag?: number;\n\treadonly parametersOid?: string;\n}): ImportEcKeyInput {\n\tconst curve =\n\t\tparsedSec1.parametersTag === 0x06 && parsedSec1.parametersOid !== undefined\n\t\t\t? oidToCurve(parsedSec1.parametersOid)\n\t\t\t: undefined;\n\tif (curve === undefined) {\n\t\tthrow new Error(\n\t\t\t'SEC 1 private key does not encode a supported named curve; pass the algorithm explicitly',\n\t\t);\n\t}\n\treturn { kind: 'ecdsa', curve };\n}\n\n/**\n * Derive the import algorithm from a JWK's own `kty`, `crv`, and `alg` members.\n *\n * `alg` disambiguates the RSA scheme and hash (`RS*`, `PS*`, `RSA-OAEP-*`) —\n * WebCrypto rejects a JWK whose `alg` disagrees with the import algorithm, so\n * it must be honored rather than defaulted over. An RSA JWK without `alg`\n * defaults to `pkcs1-v1_5`/`SHA-256`, mirroring SPKI inference.\n */\nfunction inferJwkImportInput(jwk: JsonWebKey): PublicKeyImportInput {\n\tif (jwk.kty === 'RSA') {\n\t\treturn rsaImportInputFromJwkAlg(jwk.alg);\n\t}\n\tif (jwk.kty === 'EC') {\n\t\tif (jwk.crv === 'P-256' || jwk.crv === 'P-384' || jwk.crv === 'P-521') {\n\t\t\treturn { kind: 'ecdsa', curve: jwk.crv };\n\t\t}\n\t\tthrow new Error(`Unsupported EC JWK curve: ${String(jwk.crv)}`);\n\t}\n\tif (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {\n\t\treturn { kind: 'ed25519' };\n\t}\n\tthrow new Error('Unsupported JWK key type');\n}\n\n/** Map a JWA `alg` identifier to the RSA scheme + hash it pins down. */\nfunction rsaImportInputFromJwkAlg(alg: string | undefined): ImportRsaKeyInput {\n\tswitch (alg) {\n\t\tcase undefined:\n\t\tcase 'RS256':\n\t\t\treturn { kind: 'rsa' };\n\t\tcase 'RS384':\n\t\t\treturn { kind: 'rsa', hash: 'SHA-384' };\n\t\tcase 'RS512':\n\t\t\treturn { kind: 'rsa', hash: 'SHA-512' };\n\t\tcase 'PS256':\n\t\t\treturn { kind: 'rsa', scheme: 'pss' };\n\t\tcase 'PS384':\n\t\t\treturn { kind: 'rsa', scheme: 'pss', hash: 'SHA-384' };\n\t\tcase 'PS512':\n\t\t\treturn { kind: 'rsa', scheme: 'pss', hash: 'SHA-512' };\n\t\tcase 'RSA-OAEP-256':\n\t\t\treturn { kind: 'rsa', scheme: 'oaep' };\n\t\tcase 'RSA-OAEP-384':\n\t\t\treturn { kind: 'rsa', scheme: 'oaep', hash: 'SHA-384' };\n\t\tcase 'RSA-OAEP-512':\n\t\t\treturn { kind: 'rsa', scheme: 'oaep', hash: 'SHA-512' };\n\t\tdefault:\n\t\t\t// Legacy 'RSA-OAEP' (SHA-1) requires explicit scheme and hash options.\n\t\t\tthrow new Error(`Unsupported RSA JWK alg: ${alg}`);\n\t}\n}\n\nfunction assertSpkiMatchesRequestedAlgorithm(\n\tparsedSpki: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PublicKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedSpki.parametersTag !== undefined && parsedSpki.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedSpki.parametersTag !== 0x06 ||\n\t\t\t\tparsedSpki.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== undefined) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PublicKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction assertPkcs8MatchesRequestedAlgorithm(\n\tparsedPrivateKey: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedPrivateKey.parametersTag !== undefined && parsedPrivateKey.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedPrivateKey.parametersTag !== 0x06 ||\n\t\t\t\tparsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ed25519 ||\n\t\t\t\tparsedPrivateKey.parametersTag !== undefined\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PrivateKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction assertSec1MatchesRequestedAlgorithm(\n\tparsedSec1: {\n\t\treadonly parametersTag?: number;\n\t\treadonly parametersOid?: string;\n\t},\n\talgorithm: ImportEcKeyInput,\n): void {\n\tif (parsedSec1.parametersTag === undefined) {\n\t\t// Parameters field absent: nothing encoded to cross-check, trust the caller.\n\t\treturn;\n\t}\n\tif (\n\t\tparsedSec1.parametersTag !== 0x06 ||\n\t\tparsedSec1.parametersOid !== curveToOid(algorithm.curve)\n\t) {\n\t\tthrow new Error('SEC 1 private key curve does not match requested import algorithm');\n\t}\n}\n\nfunction assertPublicJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): void {\n\tif (\n\t\tjwk.k !== undefined ||\n\t\tjwk.d !== undefined ||\n\t\tjwk.p !== undefined ||\n\t\tjwk.q !== undefined ||\n\t\tjwk.dp !== undefined ||\n\t\tjwk.dq !== undefined ||\n\t\tjwk.qi !== undefined ||\n\t\tjwk.oth !== undefined\n\t) {\n\t\tthrow new Error('Public JWK must not contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PublicKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction assertPrivateJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tif (jwk.k !== undefined || jwk.oth !== undefined) {\n\t\tthrow new Error('Private JWK must not contain symmetric or multi-prime key material');\n\t}\n\tif (typeof jwk.d !== 'string') {\n\t\tthrow new Error('Private JWK must contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'RSA' ||\n\t\t\t\ttypeof jwk.n !== 'string' ||\n\t\t\t\ttypeof jwk.e !== 'string' ||\n\t\t\t\ttypeof jwk.p !== 'string' ||\n\t\t\t\ttypeof jwk.q !== 'string' ||\n\t\t\t\ttypeof jwk.dp !== 'string' ||\n\t\t\t\ttypeof jwk.dq !== 'string' ||\n\t\t\t\ttypeof jwk.qi !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Private JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Private JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Private JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = algorithm;\n\t\t\tthrow new Error(`Unhandled PrivateKeyImportInput kind: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmVA,eAAsB,gBACrB,IAA+B;CAAE,MAAM;CAAS,OAAO;AAAQ,GACpC;CAC3B,IAAMC,IAASC,EAAU,CAAC,CAAC,QACrBC,IAAqB,eAAeC,CAAS,IAChD,CAAC,WAAW,SAAS,IACrB,CAAC,QAAQ,QAAQ,GACdC,IAAY,MAAMJ,EAAO,YAAY,uBAAuBG,CAAS,GAAG,IAAMD,CA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