micro509 0.6.0 → 0.7.1

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 (68) hide show
  1. package/dist/index.d.ts +13 -14
  2. package/dist/index.js +1 -1
  3. package/dist/internal/crypto/ecdsa.js +1 -1
  4. package/dist/internal/crypto/ecdsa.js.map +1 -1
  5. package/dist/internal/crypto/pbes2.d.ts +6 -6
  6. package/dist/internal/crypto/pbes2.js +1 -1
  7. package/dist/internal/crypto/pbes2.js.map +1 -1
  8. package/dist/internal/crypto/signing.js +1 -1
  9. package/dist/internal/crypto/signing.js.map +1 -1
  10. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  11. package/dist/internal/x509/extension-bits.js.map +1 -1
  12. package/dist/keys/keys.d.ts +15 -15
  13. package/dist/keys/keys.js +1 -1
  14. package/dist/keys/keys.js.map +1 -1
  15. package/dist/keys.d.ts +2 -3
  16. package/dist/pem/pem.d.ts +57 -6
  17. package/dist/pem/pem.js +5 -5
  18. package/dist/pem/pem.js.map +1 -1
  19. package/dist/pem.d.ts +2 -2
  20. package/dist/pem.js +1 -1
  21. package/dist/pkcs/pfx.d.ts +4 -4
  22. package/dist/pkcs/pfx.js +1 -1
  23. package/dist/pkcs/pfx.js.map +1 -1
  24. package/dist/pkcs/pkcs12-mac.d.ts +29 -5
  25. package/dist/pkcs/pkcs12-mac.js +1 -1
  26. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  27. package/dist/pkcs/pkcs7.d.ts +36 -50
  28. package/dist/pkcs/pkcs7.js +1 -1
  29. package/dist/pkcs/pkcs7.js.map +1 -1
  30. package/dist/pkcs.d.ts +3 -4
  31. package/dist/pkcs.js +1 -1
  32. package/dist/result/result.d.ts +3 -12
  33. package/dist/result/result.js.map +1 -1
  34. package/dist/result.d.ts +2 -2
  35. package/dist/result.js +1 -1
  36. package/dist/revocation/chain.d.ts +35 -34
  37. package/dist/revocation/chain.js +1 -1
  38. package/dist/revocation/chain.js.map +1 -1
  39. package/dist/revocation/crl.d.ts +40 -15
  40. package/dist/revocation/crl.js +1 -1
  41. package/dist/revocation/crl.js.map +1 -1
  42. package/dist/revocation/ocsp.d.ts +63 -13
  43. package/dist/revocation/ocsp.js +1 -1
  44. package/dist/revocation/ocsp.js.map +1 -1
  45. package/dist/revocation/revocation.d.ts +21 -19
  46. package/dist/revocation/revocation.js +1 -1
  47. package/dist/revocation/revocation.js.map +1 -1
  48. package/dist/revocation.d.ts +7 -5
  49. package/dist/revocation.js +1 -1
  50. package/dist/verify/identity.d.ts +4 -10
  51. package/dist/verify/identity.js +1 -1
  52. package/dist/verify/identity.js.map +1 -1
  53. package/dist/verify/verify.d.ts +9 -9
  54. package/dist/verify/verify.js +1 -1
  55. package/dist/verify/verify.js.map +1 -1
  56. package/dist/verify.d.ts +2 -2
  57. package/dist/x509/certificate.d.ts +2 -2
  58. package/dist/x509/certificate.js.map +1 -1
  59. package/dist/x509/csr.d.ts +2 -2
  60. package/dist/x509/csr.js.map +1 -1
  61. package/dist/x509/extensions.d.ts +21 -6
  62. package/dist/x509/extensions.js.map +1 -1
  63. package/dist/x509/parse.d.ts +3 -4
  64. package/dist/x509/parse.js +1 -1
  65. package/dist/x509/parse.js.map +1 -1
  66. package/dist/x509.d.ts +3 -4
  67. package/package.json +3 -1
  68. package/dist/internal/x509/extension-bits.d.ts +0 -18
@@ -1 +1 @@
1
- {"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der.ts';\nimport type { DistributionPointReason, KeyUsage } from '#micro509/x509/extensions.ts';\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nexport interface ParsedBitFlags<T extends string> {\n\t/** Decoded flag values, padding bits masked. */\n\treadonly flags: readonly T[];\n\t/** `true` when the original encoding had non-zero padding bits (DER violation). */\n\treadonly nonZeroPadding: boolean;\n}\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.2 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":"gEA4BA,MAAM,EAAkB,CACvB,mBACA,iBACA,kBACA,mBACA,eACA,cACA,UACA,eACA,cACD,EAGM,EAAkC,CACvC,gBACA,eACA,qBACA,aACA,uBACA,kBACA,qBACA,cACD,EAOA,SAAgB,EAAwB,EAAyC,CAChF,IAAM,EAAU,EAAe,EAAS,GACvC,EAAa,EAAiB,EAAO,WAAW,CACjD,EACA,OAAO,EAAU,EAAQ,MAAO,EAAQ,UAAU,CACnD,CAOA,SAAgB,EAAuB,EAA6C,CACnF,IAAM,EAAmB,EAAgB,EAAO,CAAE,SAAA,EAAgC,CAAC,EACnF,GAAI,EAAiB,MAAQ,EAC5B,MAAU,MAAM,+BAA+B,EAEhD,OAAO,EACN,EAAe,EAAiB,MAAO,EAAiB,CAAC,EACzD,UACD,CACD,CAQA,SAAgB,EACf,EACa,CACb,IAAM,EAAU,EACf,EACC,GACA,EAAa,EAAiC,EAAQ,2BAA2B,EAAI,CACvF,EACA,OAAO,WAAW,GAAG,EAAQ,WAAY,GAAG,EAAQ,KAAK,CAC1D,CAQA,SAAgB,EACf,EAC0C,CAC1C,OAAO,EACN,EAAe,EAAO,EAAiC,CAAC,EACxD,2BACD,CACD,CAGA,SAAS,EACR,EACA,EAIC,CACD,GAAI,EAAO,SAAW,EACrB,MAAO,CAAE,MAAO,IAAI,WAAe,WAAY,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,EAAM,sCAAsC,EAEhE,OAAO,CACR,CAGA,SAAS,EAA+B,EAAqB,EAAU,EAAuB,CAC7F,IAAM,EAAQ,EAAM,QAAQ,CAAK,EACjC,GAAI,EAAQ,EACX,MAAU,MAAM,eAAe,EAAM,IAAI,GAAO,EAEjD,OAAO,CACR"}
1
+ {"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der.ts';\nimport type { DistributionPointReason, KeyUsage } from '#micro509/x509/extensions.ts';\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nimport type { ParsedBitFlags } from '#micro509/x509/extensions.ts';\n\nexport type { ParsedBitFlags };\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.2 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":"gEAyBA,MAAM,EAAkB,CACvB,mBACA,iBACA,kBACA,mBACA,eACA,cACA,UACA,eACA,cACD,EAGM,EAAkC,CACvC,gBACA,eACA,qBACA,aACA,uBACA,kBACA,qBACA,cACD,EAOA,SAAgB,EAAwB,EAAyC,CAChF,IAAM,EAAU,EAAe,EAAS,GACvC,EAAa,EAAiB,EAAO,WAAW,CACjD,EACA,OAAO,EAAU,EAAQ,MAAO,EAAQ,UAAU,CACnD,CAOA,SAAgB,EAAuB,EAA6C,CACnF,IAAM,EAAmB,EAAgB,EA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M,OAAS,IAGpC,IAFiB,EAAM,EAAM,OAAS,IAAM,IACvB,GAAK,GAAc,IACM,GAE/C,IAAM,EAAa,CAAC,EACpB,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAW,OAAQ,GAAS,EAAG,CAC1D,IAAM,EAAM,EAAQ,EACd,EAAY,KAAK,MAAM,EAAM,CAAC,EACpC,GAAI,GAAa,EAAM,OACtB,MAID,IAFa,EAAM,IAAc,GAEpB,GAAM,EADF,EAAM,EACmB,CACzC,IAAM,EAAY,EAAW,GACzB,IAAc,IAAA,IACjB,EAAM,KAAK,CAAS,CAEtB,CACD,CACA,MAAO,CAAE,QAAO,gBAAe,CAChC,CAEA,SAAS,EACR,EACA,EACoB,CACpB,GAAI,EAAO,eACV,MAAU,MAAM,GAAG,EAAM,sCAAsC,EAEhE,OAAO,CACR,CAGA,SAAS,EAA+B,EAAqB,EAAU,EAAuB,CAC7F,IAAM,EAAQ,EAAM,QAAQ,CAAK,EACjC,GAAI,EAAQ,EACX,MAAU,MAAM,eAAe,EAAM,IAAI,GAAO,EAEjD,OAAO,CACR"}
@@ -52,8 +52,8 @@ interface KeyPairMaterial {
52
52
  /** Export the private key as a JSON Web Key. */
53
53
  exportPrivateJwk(): Promise<JsonWebKey>;
54
54
  }
55
- /** RSA variant of {@linkcode PublicKeyImportInput}. */
56
- interface ImportRsaPublicKeyInput {
55
+ /** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */
56
+ interface ImportRsaKeyInput {
57
57
  /** Discriminant selecting RSA import. */
58
58
  readonly kind: "rsa";
59
59
  /** Hash algorithm. Defaults to `'SHA-256'`. */
@@ -61,23 +61,23 @@ interface ImportRsaPublicKeyInput {
61
61
  /** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */
62
62
  readonly scheme?: RsaScheme;
63
63
  }
64
- /** ECDSA variant of {@linkcode PublicKeyImportInput}. */
65
- interface ImportEcPublicKeyInput {
64
+ /** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */
65
+ interface ImportEcKeyInput {
66
66
  /** Discriminant selecting ECDSA import. */
67
67
  readonly kind: "ecdsa";
68
68
  /** NIST curve the key belongs to. Required for EC import. */
69
69
  readonly curve: EcNamedCurve;
70
70
  }
71
- /** Ed25519 variant of {@linkcode PublicKeyImportInput}. */
72
- interface ImportEd25519PublicKeyInput {
71
+ /** Ed25519 variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */
72
+ interface ImportEd25519KeyInput {
73
73
  /** Discriminant selecting Ed25519 import. */
74
74
  readonly kind: "ed25519";
75
75
  }
76
76
  /** Algorithm descriptor for public key import functions. */
77
- type PublicKeyImportInput = ImportRsaPublicKeyInput | ImportEcPublicKeyInput | ImportEd25519PublicKeyInput;
77
+ type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;
78
78
  /** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */
79
79
  type PrivateKeyImportInput = PublicKeyImportInput;
80
- /** PBES2 encryption options for {@linkcode exportEncryptedPkcs8Der} and {@linkcode exportEncryptedPkcs8Pem}. */
80
+ /** PBES2 encryption options for the encrypted PKCS#8 export/import functions. */
81
81
  type EncryptedPkcs8Options = Pbes2EncryptionOptions;
82
82
  /** Options for OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM encryption (PKCS#1/SEC1). */
83
83
  interface LegacyPemEncryptionOptions {
@@ -349,19 +349,19 @@ declare function importEncryptedPkcs8Pem(pem: string, password: string, algorith
349
349
  *
350
350
  * @see `importPkcs1DerOrThrow` for the throwing variant
351
351
  */
352
- declare function importPkcs1Der(der: Uint8Array, algorithm?: ImportRsaPublicKeyInput): Promise<ImportKeyResult<CryptoKey>>;
352
+ declare function importPkcs1Der(der: Uint8Array, algorithm?: ImportRsaKeyInput): Promise<ImportKeyResult<CryptoKey>>;
353
353
  /**
354
354
  * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
355
355
  *
356
356
  * @see `importPkcs1PemOrThrow` for the throwing variant
357
357
  */
358
- declare function importPkcs1Pem(pem: string, algorithm?: ImportRsaPublicKeyInput): Promise<ImportKeyResult<CryptoKey>>;
358
+ declare function importPkcs1Pem(pem: string, algorithm?: ImportRsaKeyInput): Promise<ImportKeyResult<CryptoKey>>;
359
359
  /**
360
360
  * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
361
361
  *
362
362
  * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant
363
363
  */
364
- declare function importEncryptedPkcs1Pem(pem: string, password: string, algorithm?: ImportRsaPublicKeyInput): Promise<ImportEncryptedKeyResult<CryptoKey>>;
364
+ declare function importEncryptedPkcs1Pem(pem: string, password: string, algorithm?: ImportRsaKeyInput): Promise<ImportEncryptedKeyResult<CryptoKey>>;
365
365
  /**
366
366
  * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
367
367
  *
@@ -373,19 +373,19 @@ declare function importPkcs8Base64(base64: string, algorithm: PrivateKeyImportIn
373
373
  *
374
374
  * @see `importSec1DerOrThrow` for the throwing variant
375
375
  */
376
- declare function importSec1Der(der: Uint8Array, algorithm: ImportEcPublicKeyInput): Promise<ImportKeyResult<CryptoKey>>;
376
+ declare function importSec1Der(der: Uint8Array, algorithm: ImportEcKeyInput): Promise<ImportKeyResult<CryptoKey>>;
377
377
  /**
378
378
  * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
379
379
  *
380
380
  * @see `importSec1PemOrThrow` for the throwing variant
381
381
  */
382
- declare function importSec1Pem(pem: string, algorithm: ImportEcPublicKeyInput): Promise<ImportKeyResult<CryptoKey>>;
382
+ declare function importSec1Pem(pem: string, algorithm: ImportEcKeyInput): Promise<ImportKeyResult<CryptoKey>>;
383
383
  /**
384
384
  * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
385
385
  *
386
386
  * @see `importEncryptedSec1PemOrThrow` for the throwing variant
387
387
  */
388
- declare function importEncryptedSec1Pem(pem: string, password: string, algorithm: ImportEcPublicKeyInput): Promise<ImportEncryptedKeyResult<CryptoKey>>;
388
+ declare function importEncryptedSec1Pem(pem: string, password: string, algorithm: ImportEcKeyInput): Promise<ImportEncryptedKeyResult<CryptoKey>>;
389
389
  /**
390
390
  * Import a public verification key from a JSON Web Key.
391
391
  *
@@ -399,5 +399,5 @@ declare function importPublicJwk(jwk: JsonWebKey, algorithm: PublicKeyImportInpu
399
399
  */
400
400
  declare function importPrivateJwk(jwk: JsonWebKey, algorithm: PrivateKeyImportInput): Promise<ImportKeyResult<CryptoKey>>;
401
401
  //#endregion
402
- export { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcPublicKeyInput, ImportEd25519PublicKeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaPublicKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem };
402
+ export { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcKeyInput, ImportEd25519KeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem };
403
403
  //# sourceMappingURL=keys.d.ts.map
package/dist/keys/keys.js CHANGED
@@ -1,4 +1,4 @@
1
- import{nullValue as e,objectIdentifier as t,octetString as n,readSequenceChildren as r,sequence as i}from"../internal/asn1/der.js";import{decodeObjectIdentifier as a,extractBitStringValue as o,hexToBytes as s,toArrayBuffer as c,toHex as l}from"../internal/asn1/asn1.js";import{OIDS as u}from"../internal/asn1/oids.js";import{md5 as ee}from"../internal/crypto/hash.js";import{getCrypto as d}from"../internal/crypto/webcrypto.js";import{decryptPbes2 as te,encryptPbes2 as ne,isWrongPasswordError as re,wrongPasswordError as ie}from"../internal/crypto/pbes2.js";import{base64Decode as f,base64Encode as p}from"../internal/shared/base64.js";import{pemDecode as m,pemEncode as h}from"../pem/pem.js";import{failureResult as g,rethrowIfInvariant as _,successResult as v}from"../result/result.js";async function ae(e={kind:`ecdsa`,curve:`P-256`}){let t=await d().subtle.generateKey(Oe(e),!0,[`sign`,`verify`]);if(!(`publicKey`in t)||!(`privateKey`in t))throw Error(`Expected an asymmetric key pair`);return y(t.publicKey,t.privateKey)}function y(e,t){return{publicKey:e,privateKey:t,async exportSpkiDer(){return new Uint8Array(await d().subtle.exportKey(`spki`,e))},async exportSpkiPem(){return h(`PUBLIC KEY`,await this.exportSpkiDer())},async exportPkcs8Der(){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,t))},async exportPkcs8Pem(){return h(`PRIVATE KEY`,await this.exportPkcs8Der())},async exportPublicJwk(){return d().subtle.exportKey(`jwk`,e)},async exportPrivateJwk(){return d().subtle.exportKey(`jwk`,t)}}}async function b(e){return new Uint8Array(await d().subtle.exportKey(`spki`,e))}async function x(e){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,e))}async function oe(e){return d().subtle.exportKey(`jwk`,e)}async function se(e){return d().subtle.exportKey(`jwk`,e)}async function ce(e){return h(`PRIVATE KEY`,await x(e))}async function S(e,t){let r=await ne(await x(e),t);return i([r.algorithmIdentifierDer,n(r.encryptedData)])}async function le(e,t){return h(`ENCRYPTED PRIVATE KEY`,await S(e,t))}async function C(e){let t=J(await x(e));if(t.algorithmOid!==u.rsaEncryption)throw Error(`PKCS#1 export requires an RSA private key`);return t.privateKeyDer}async function ue(e){return h(`RSA PRIVATE KEY`,await C(e))}async function de(e,t){return Z(`RSA PRIVATE KEY`,await C(e),t)}async function w(e){let t=J(await x(e));if(t.algorithmOid!==u.ecPublicKey)throw Error(`SEC1 export requires an EC private key`);return t.privateKeyDer}async function fe(e){return h(`EC PRIVATE KEY`,await w(e))}async function T(e,t){return Z(`EC PRIVATE KEY`,await w(e),t)}async function pe(e){return h(`PUBLIC KEY`,await b(e))}async function me(e){if(e.type===`public`)return p(await b(e));if(e.type===`private`)return p(await x(e));throw Error(`Cannot export secret/symmetric CryptoKey`)}async function E(e,t){Le(Ie(e),t);try{return await d().subtle.importKey(`spki`,new Uint8Array(e),q(t),!0,[`verify`])}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}async function D(e){try{return v(await e())}catch(e){return _(e),g(`malformed`,e instanceof Error?e.message:`Malformed key`)}}async function O(e){try{return v(await e())}catch(e){return _(e),re(e)?g(`invalid_password`,e.message):g(`malformed`,e instanceof Error?e.message:`Malformed encrypted key`)}}function he(e,t){return D(()=>E(e,t))}async function k(e,t){return E(m(`PUBLIC KEY`,e),t)}function ge(e,t){return D(()=>k(e,t))}async function A(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 SubjectPublicKeyInfo`)}return E(n,t)}function _e(e,t){return D(()=>A(e,t))}async function j(e,t){let n;try{n=J(e)}catch{throw Error(`Malformed PKCS#8 private key`)}Re(n,t);try{return await d().subtle.importKey(`pkcs8`,new Uint8Array(e),q(t),!0,[`sign`])}catch{throw Error(`Malformed PKCS#8 private key`)}}function ve(e,t){return D(()=>j(e,t))}async function M(e,t){return j(m(`PRIVATE KEY`,e),t)}function N(e,t){return D(()=>M(e,t))}async function P(e,t,n){let i;try{i=r(e)}catch{throw Error(`Malformed EncryptedPrivateKeyInfo`)}let a=i[0],o=i[1];if(i.length!==2||a===void 0||o===void 0||o.tag!==4)throw Error(`Malformed EncryptedPrivateKeyInfo`);return j(await te(e.slice(a.start-a.headerLength,a.end),o.value,t),n)}function F(e,t,n){return O(()=>P(e,t,n))}async function I(e,t,n){return P(m(`ENCRYPTED PRIVATE KEY`,e),t,n)}function ye(e,t,n){return O(()=>I(e,t,n))}async function L(e,t={kind:`rsa`}){return j(ke(e),t)}function be(e,t={kind:`rsa`}){return D(()=>L(e,t))}async function R(e,t={kind:`rsa`}){return L(m(`RSA PRIVATE KEY`,e),t)}function z(e,t={kind:`rsa`}){return D(()=>R(e,t))}async function B(e,t,n={kind:`rsa`}){return L(await Q(`RSA PRIVATE KEY`,e,t),n)}function xe(e,t,n={kind:`rsa`}){return O(()=>B(e,t,n))}async function V(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 PKCS#8 private key`)}return j(n,t)}function Se(e,t){return D(()=>V(e,t))}async function H(e,t){return j(Ae(e,t.curve),t)}function Ce(e,t){return D(()=>H(e,t))}async function U(e,t){return H(m(`EC PRIVATE KEY`,e),t)}function we(e,t){return D(()=>U(e,t))}async function W(e,t,n){return H(await Q(`EC PRIVATE KEY`,e,t),n)}function Te(e,t,n){return O(()=>W(e,t,n))}async function G(e,t){ze(e,t);try{return await d().subtle.importKey(`jwk`,e,q(t),!0,[`verify`])}catch{throw Error(`Malformed public JWK`)}}function Ee(e,t){return D(()=>G(e,t))}async function K(e,t){return d().subtle.importKey(`jwk`,e,q(t),!0,[`sign`])}function De(e,t){return D(()=>K(e,t))}function Oe(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),modulusLength:e.modulusLength??2048,publicExponent:Uint8Array.of(1,0,1),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve??`P-256`};case`ed25519`:return{name:`Ed25519`}}}function q(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve};case`ed25519`:return{name:`Ed25519`}}}function J(e){let t=r(e),n=t[1],i=t[2];if(t.length<3||t.length>4||n===void 0||n.tag!==48||i===void 0||i.tag!==4)throw Error(`Malformed PKCS#8 private key`);let o=r(e.slice(n.start-n.headerLength,n.end)),s=o[0];if(s===void 0||s.tag!==6||o.length<1||o.length>2)throw Error(`Malformed PKCS#8 private key`);let c=o[1];return{algorithmOid:a(s.value),...c===void 0?{}:{parametersTag:c.tag},...c?.tag===6?{parametersOid:a(c.value)}:{},privateKeyDer:i.value}}function ke(r){return i([Uint8Array.of(2,1,0),i([t(u.rsaEncryption),e()]),n(new Uint8Array(r))])}function Ae(e,r){return i([Uint8Array.of(2,1,0),i([t(u.ecPublicKey),t(Y(r))]),n(new Uint8Array(e))])}function Y(e){switch(e){case`P-256`:return u.prime256v1;case`P-384`:return u.secp384r1;case`P-521`:return u.secp521r1}}function X(e){return e===`pss`?`RSA-PSS`:`RSASSA-PKCS1-v1_5`}async function Z(e,t,n){let r=n.iv??d().getRandomValues(new Uint8Array(16));if(r.length!==16)throw Error(`Traditional PEM encryption requires a 16-byte IV`);let i=n.cipher??`AES-256-CBC`,a=await $(n.password,r.slice(0,8),i,[`encrypt`]),o=p(new Uint8Array(await d().subtle.encrypt({name:`AES-CBC`,iv:c(r)},a,c(t)))).match(/.{1,64}/g)?.join(`
1
+ import{nullValue as e,objectIdentifier as t,octetString as n,readSequenceChildren as r,sequence as i}from"../internal/asn1/der.js";import{decodeObjectIdentifier as a,extractBitStringValue as o,hexToBytes as s,toArrayBuffer as c,toHex as l}from"../internal/asn1/asn1.js";import{OIDS as u}from"../internal/asn1/oids.js";import{md5 as ee}from"../internal/crypto/hash.js";import{getCrypto as d}from"../internal/crypto/webcrypto.js";import{decryptPbes2 as te,encryptPbes2 as ne,isWrongPasswordError as re,wrongPasswordError as ie}from"../internal/crypto/pbes2.js";import{base64Decode as f,base64Encode as p}from"../internal/shared/base64.js";import{failureResult as m,rethrowIfInvariant as h,successResult as g}from"../result/result.js";import{pemDecodeOrThrow as _,pemEncode as v}from"../pem/pem.js";async function ae(e={kind:`ecdsa`,curve:`P-256`}){let t=await d().subtle.generateKey(Oe(e),!0,[`sign`,`verify`]);if(!(`publicKey`in t)||!(`privateKey`in t))throw Error(`Expected an asymmetric key pair`);return y(t.publicKey,t.privateKey)}function y(e,t){return{publicKey:e,privateKey:t,async exportSpkiDer(){return new Uint8Array(await d().subtle.exportKey(`spki`,e))},async exportSpkiPem(){return v(`PUBLIC KEY`,await this.exportSpkiDer())},async exportPkcs8Der(){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,t))},async exportPkcs8Pem(){return v(`PRIVATE KEY`,await this.exportPkcs8Der())},async exportPublicJwk(){return d().subtle.exportKey(`jwk`,e)},async exportPrivateJwk(){return d().subtle.exportKey(`jwk`,t)}}}async function b(e){return new Uint8Array(await d().subtle.exportKey(`spki`,e))}async function x(e){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,e))}async function oe(e){return d().subtle.exportKey(`jwk`,e)}async function se(e){return d().subtle.exportKey(`jwk`,e)}async function ce(e){return v(`PRIVATE KEY`,await x(e))}async function S(e,t){let r=await ne(await x(e),t);return i([r.algorithmIdentifierDer,n(r.encryptedData)])}async function le(e,t){return v(`ENCRYPTED PRIVATE KEY`,await S(e,t))}async function C(e){let t=J(await x(e));if(t.algorithmOid!==u.rsaEncryption)throw Error(`PKCS#1 export requires an RSA private key`);return t.privateKeyDer}async function ue(e){return v(`RSA PRIVATE KEY`,await C(e))}async function de(e,t){return Z(`RSA PRIVATE KEY`,await C(e),t)}async function w(e){let t=J(await x(e));if(t.algorithmOid!==u.ecPublicKey)throw Error(`SEC1 export requires an EC private key`);return t.privateKeyDer}async function fe(e){return v(`EC PRIVATE KEY`,await w(e))}async function T(e,t){return Z(`EC PRIVATE KEY`,await w(e),t)}async function pe(e){return v(`PUBLIC KEY`,await b(e))}async function me(e){if(e.type===`public`)return p(await b(e));if(e.type===`private`)return p(await x(e));throw Error(`Cannot export secret/symmetric CryptoKey`)}async function E(e,t){Le(Ie(e),t);try{return await d().subtle.importKey(`spki`,new Uint8Array(e),q(t),!0,[`verify`])}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}async function D(e){try{return g(await e())}catch(e){return h(e),m(`malformed`,e instanceof Error?e.message:`Malformed key`)}}async function O(e){try{return g(await e())}catch(e){return h(e),re(e)?m(`invalid_password`,e.message):m(`malformed`,e instanceof Error?e.message:`Malformed encrypted key`)}}function he(e,t){return D(()=>E(e,t))}async function k(e,t){return E(_(`PUBLIC KEY`,e),t)}function ge(e,t){return D(()=>k(e,t))}async function A(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 SubjectPublicKeyInfo`)}return E(n,t)}function _e(e,t){return D(()=>A(e,t))}async function j(e,t){let n;try{n=J(e)}catch{throw Error(`Malformed PKCS#8 private key`)}Re(n,t);try{return await d().subtle.importKey(`pkcs8`,new Uint8Array(e),q(t),!0,[`sign`])}catch{throw Error(`Malformed PKCS#8 private key`)}}function ve(e,t){return D(()=>j(e,t))}async function M(e,t){return j(_(`PRIVATE KEY`,e),t)}function N(e,t){return D(()=>M(e,t))}async function P(e,t,n){let i;try{i=r(e)}catch{throw Error(`Malformed EncryptedPrivateKeyInfo`)}let a=i[0],o=i[1];if(i.length!==2||a===void 0||o===void 0||o.tag!==4)throw Error(`Malformed EncryptedPrivateKeyInfo`);return j(await te(e.slice(a.start-a.headerLength,a.end),o.value,t),n)}function F(e,t,n){return O(()=>P(e,t,n))}async function I(e,t,n){return P(_(`ENCRYPTED PRIVATE KEY`,e),t,n)}function ye(e,t,n){return O(()=>I(e,t,n))}async function L(e,t={kind:`rsa`}){return j(ke(e),t)}function be(e,t={kind:`rsa`}){return D(()=>L(e,t))}async function R(e,t={kind:`rsa`}){return L(_(`RSA PRIVATE KEY`,e),t)}function z(e,t={kind:`rsa`}){return D(()=>R(e,t))}async function B(e,t,n={kind:`rsa`}){return L(await Q(`RSA PRIVATE KEY`,e,t),n)}function xe(e,t,n={kind:`rsa`}){return O(()=>B(e,t,n))}async function V(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 PKCS#8 private key`)}return j(n,t)}function Se(e,t){return D(()=>V(e,t))}async function H(e,t){return j(Ae(e,t.curve),t)}function Ce(e,t){return D(()=>H(e,t))}async function U(e,t){return H(_(`EC PRIVATE KEY`,e),t)}function we(e,t){return D(()=>U(e,t))}async function W(e,t,n){return H(await Q(`EC PRIVATE KEY`,e,t),n)}function Te(e,t,n){return O(()=>W(e,t,n))}async function G(e,t){ze(e,t);try{return await d().subtle.importKey(`jwk`,e,q(t),!0,[`verify`])}catch{throw Error(`Malformed public JWK`)}}function Ee(e,t){return D(()=>G(e,t))}async function K(e,t){return d().subtle.importKey(`jwk`,e,q(t),!0,[`sign`])}function De(e,t){return D(()=>K(e,t))}function Oe(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),modulusLength:e.modulusLength??2048,publicExponent:Uint8Array.of(1,0,1),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve??`P-256`};case`ed25519`:return{name:`Ed25519`}}}function q(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve};case`ed25519`:return{name:`Ed25519`}}}function J(e){let t=r(e),n=t[1],i=t[2];if(t.length<3||t.length>4||n===void 0||n.tag!==48||i===void 0||i.tag!==4)throw Error(`Malformed PKCS#8 private key`);let o=r(e.slice(n.start-n.headerLength,n.end)),s=o[0];if(s===void 0||s.tag!==6||o.length<1||o.length>2)throw Error(`Malformed PKCS#8 private key`);let c=o[1];return{algorithmOid:a(s.value),...c===void 0?{}:{parametersTag:c.tag},...c?.tag===6?{parametersOid:a(c.value)}:{},privateKeyDer:i.value}}function ke(r){return i([Uint8Array.of(2,1,0),i([t(u.rsaEncryption),e()]),n(new Uint8Array(r))])}function Ae(e,r){return i([Uint8Array.of(2,1,0),i([t(u.ecPublicKey),t(Y(r))]),n(new Uint8Array(e))])}function Y(e){switch(e){case`P-256`:return u.prime256v1;case`P-384`:return u.secp384r1;case`P-521`:return u.secp521r1}}function X(e){return e===`pss`?`RSA-PSS`:`RSASSA-PKCS1-v1_5`}async function Z(e,t,n){let r=n.iv??d().getRandomValues(new Uint8Array(16));if(r.length!==16)throw Error(`Traditional PEM encryption requires a 16-byte IV`);let i=n.cipher??`AES-256-CBC`,a=await $(n.password,r.slice(0,8),i,[`encrypt`]),o=p(new Uint8Array(await d().subtle.encrypt({name:`AES-CBC`,iv:c(r)},a,c(t)))).match(/.{1,64}/g)?.join(`
2
2
  `)??``;return[`-----BEGIN ${e}-----`,`Proc-Type: 4,ENCRYPTED`,`DEK-Info: ${i},${l(r).toUpperCase()}`,``,o,`-----END ${e}-----`].join(`
3
3
  `)}async function Q(e,t,n){let r=Fe(t);if(r.label!==e)throw Error(`Expected ${e} PEM block`);let i=r.headers.get(`DEK-Info`);if(r.headers.get(`Proc-Type`)!==`4,ENCRYPTED`||i===void 0)throw Error(`Traditional PEM encryption headers missing`);let[a,o]=i.split(`,`);if(!je(a)||o===void 0)throw Error(`Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported`);if(!Me(o))throw Error(`Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters`);let l=s(o),u=await $(n,l.slice(0,8),a,[`decrypt`]);try{return new Uint8Array(await d().subtle.decrypt({name:`AES-CBC`,iv:c(l)},u,c(f(r.base64Body))))}catch{throw ie(`Invalid password or encrypted PEM content`)}}async function $(e,t,n,r){let i=Ne(n),a=Pe(e,t,i/8);return d().subtle.importKey(`raw`,c(a),{name:`AES-CBC`,length:i},!1,r)}function je(e){return e===`AES-128-CBC`||e===`AES-192-CBC`||e===`AES-256-CBC`}function Me(e){return e.length===32&&/^[0-9A-Fa-f]+$/.test(e)}function Ne(e){switch(e){case`AES-128-CBC`:return 128;case`AES-192-CBC`:return 192;case`AES-256-CBC`:return 256}}function Pe(e,t,n){let r=new TextEncoder().encode(e),i=[],a=new Uint8Array,o=0;for(;o<n;){let e=new Uint8Array(a.length+r.length+t.length);e.set(a,0),e.set(r,a.length),e.set(t,a.length+r.length),a=ee(e),i.push(a),o+=a.length}let s=new Uint8Array(n),c=0;for(let e of i){let t=e.slice(0,Math.min(e.length,n-c));if(s.set(t,c),c+=t.length,c>=n)break}return s}function Fe(e){let t=e.replace(/\r/g,``).trim().split(`
4
4
  `),n=t[0],r=t[t.length-1];if(n===void 0||r===void 0||!n.startsWith(`-----BEGIN `)||!r.startsWith(`-----END `))throw Error(`Invalid PEM block`);let i=n.slice(11,-5);if(r!==`-----END ${i}-----`)throw Error(`PEM boundaries do not match`);let a=new Map,o=1;for(;o<t.length-1;){let e=t[o];if(e===void 0)break;if(e.length===0){o+=1;break}let n=e.indexOf(`: `);if(n===-1)break;let r=e.slice(0,n);if(a.has(r))throw Error(`Duplicate PEM header: ${r}`);a.set(r,e.slice(n+2)),o+=1}return{label:i,headers:a,base64Body:t.slice(o,t.length-1).join(``)}}function Ie(e){try{let t=r(e);if(t.length!==2)throw Error(`Malformed SubjectPublicKeyInfo`);let n=t[0],i=t[1];if(n===void 0||n.tag!==48||i===void 0||i.tag!==3)throw Error(`Malformed SubjectPublicKeyInfo`);o(i);let s=r(e.slice(n.start-n.headerLength,n.end)),c=s[0];if(c===void 0||c.tag!==6||s.length<1||s.length>2)throw Error(`Malformed SubjectPublicKeyInfo`);let l=s[1];return{algorithmOid:a(c.value),...l===void 0?{}:{parametersTag:l.tag},...l?.tag===6?{parametersOid:a(l.value)}:{}}}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}function Le(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return}}function Re(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return}}function ze(e,t){if(e.k!==void 0||e.d!==void 0||e.p!==void 0||e.q!==void 0||e.dp!==void 0||e.dq!==void 0||e.qi!==void 0||e.oth!==void 0)throw Error(`Public JWK must not contain private key material`);switch(t.kind){case`rsa`:if(e.kty!==`RSA`||typeof e.n!=`string`||typeof e.e!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.kty!==`EC`||e.crv!==t.curve||typeof e.x!=`string`||typeof e.y!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.kty!==`OKP`||e.crv!==`Ed25519`||typeof e.x!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return}}export{me as exportBinaryBase64,de as exportEncryptedPkcs1Pem,S as exportEncryptedPkcs8Der,le as exportEncryptedPkcs8Pem,T as exportEncryptedSec1Pem,C as exportPkcs1Der,ue as exportPkcs1Pem,x as exportPkcs8Der,ce as exportPkcs8Pem,se as exportPrivateJwk,oe as exportPublicJwk,w as exportSec1Der,fe as exportSec1Pem,b as exportSpkiDer,pe as exportSpkiPem,ae as generateKeyPair,xe as importEncryptedPkcs1Pem,B as importEncryptedPkcs1PemOrThrow,F as importEncryptedPkcs8Der,P as importEncryptedPkcs8DerOrThrow,ye as importEncryptedPkcs8Pem,I as importEncryptedPkcs8PemOrThrow,Te as importEncryptedSec1Pem,W as importEncryptedSec1PemOrThrow,be as importPkcs1Der,L as importPkcs1DerOrThrow,z as importPkcs1Pem,R as importPkcs1PemOrThrow,Se as importPkcs8Base64,V as importPkcs8Base64OrThrow,ve as importPkcs8Der,j as importPkcs8DerOrThrow,N as importPkcs8Pem,M as importPkcs8PemOrThrow,De as importPrivateJwk,K as importPrivateJwkOrThrow,Ee as importPublicJwk,G as importPublicJwkOrThrow,Ce as importSec1Der,H as importSec1DerOrThrow,we as importSec1Pem,U as importSec1PemOrThrow,_e as importSpkiBase64,A as importSpkiBase64OrThrow,he as importSpkiDer,E as importSpkiDerOrThrow,ge as importSpkiPem,k as importSpkiPemOrThrow};
@@ -1 +1 @@
1
- {"version":3,"file":"keys.js","names":[],"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 and PSS), 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 { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const privatePem = await exportPkcs8Pem(keys.privateKey);\n *\n * // Import\n * const publicKey = 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.ts';\nimport {\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { md5 } from '#micro509/internal/crypto/hash.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { pemDecode, pemEncode } from '#micro509/pem/pem.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\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 RsaScheme = 'pkcs1-v1_5' | 'pss';\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/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\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). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage). */\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}. */\nexport interface ImportRsaPublicKeyInput {\n\t/** Discriminant selecting RSA import. */\n\treadonly kind: 'rsa';\n\t/** Hash algorithm. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode PublicKeyImportInput}. */\nexport interface ImportEcPublicKeyInput {\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}. */\nexport interface ImportEd25519PublicKeyInput {\n\t/** Discriminant selecting Ed25519 import. */\n\treadonly kind: 'ed25519';\n}\n\n/** Algorithm descriptor for public key import functions. */\nexport type PublicKeyImportInput =\n\t| ImportRsaPublicKeyInput\n\t| ImportEcPublicKeyInput\n\t| ImportEd25519PublicKeyInput;\n\n/** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */\nexport type PrivateKeyImportInput = PublicKeyImportInput;\n\n/** PBES2 encryption options for {@linkcode exportEncryptedPkcs8Der} and {@linkcode exportEncryptedPkcs8Pem}. */\nexport type EncryptedPkcs8Options = Pbes2EncryptionOptions;\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/** Machine-readable failure reason for the `import*` key functions. */\nexport type ImportKeyErrorCode = 'malformed';\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\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 always `'malformed'`: structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures all surface\n * the same way (see the throwing `*OrThrow` variants for raw error messages).\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'`).\n */\nexport type ImportEncryptedKeyErrorCode = 'malformed' | 'invalid_password';\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\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/**\n * Generate an asymmetric key pair for signing and verification.\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 *\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 generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, [\n\t\t'sign',\n\t\t'verify',\n\t]);\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\tasync exportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\tasync exportPrivateJwk() {\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 async 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 async 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 * @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 * @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 parsed.privateKeyDer;\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 * 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 * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\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\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['verify'],\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'` 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 failureResult('malformed', error instanceof Error ? error.message : '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\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed encrypted key',\n\t\t);\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 importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport async function importSpkiPemOrThrow(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importSpkiDerOrThrow(pemDecode('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 async 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 * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\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 {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['sign'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 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 * @example\n * ```ts\n * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPkcs8PemOrThrow(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(pemDecode('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 * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Expected algorithm (must match decrypted key)\n *\n * @throws {Error} If DER is malformed, password is wrong, 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): Promise<CryptoKey> {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch {\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\tconst decrypted = await decryptPbes2(\n\t\tder.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData.value,\n\t\tpassword,\n\t);\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\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): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importEncryptedPkcs8DerOrThrow(\n\t\tpemDecode('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\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): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));\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 async function importPkcs1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportRsaPublicKeyInput = { 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: ImportRsaPublicKeyInput = { 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 async function importPkcs1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportRsaPublicKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs1DerOrThrow(pemDecode('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: ImportRsaPublicKeyInput = { 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: ImportRsaPublicKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('RSA PRIVATE KEY', pem, password);\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: ImportRsaPublicKeyInput = { 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 async 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 *\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: ImportEcPublicKeyInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);\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: ImportEcPublicKeyInput,\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.\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport async function importSec1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportEcPublicKeyInput,\n): Promise<CryptoKey> {\n\treturn importSec1DerOrThrow(pemDecode('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: ImportEcPublicKeyInput,\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: ImportEcPublicKeyInput,\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('EC PRIVATE KEY', pem, password);\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: ImportEcPublicKeyInput,\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 * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed or algorithm doesn't match\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, [\n\t\t\t'verify',\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 * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, ['sign']);\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/** 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}\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}\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} {\n\tconst children = readSequenceChildren(der);\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tchildren.length > 4 ||\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 algorithmChildren = readSequenceChildren(\n\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t);\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\treturn {\n\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\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};\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: ImportEcPublicKeyInput['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/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcPublicKeyInput['curve']): string {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn OIDS.prime256v1;\n\t\tcase 'P-384':\n\t\t\treturn OIDS.secp384r1;\n\t\tcase 'P-521':\n\t\t\treturn OIDS.secp521r1;\n\t}\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' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\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 an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back 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 = parseTraditionalPem(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\tif (parsed.headers.get('Proc-Type') !== '4,ENCRYPTED' || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',');\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`. */\nasync function 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/** 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}\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\n/** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */\nfunction parseTraditionalPem(pem: string): {\n\t/** PEM type label between `BEGIN` and `END` markers. */\n\treadonly label: string;\n\t/** RFC 1421 encapsulated headers (e.g. `Proc-Type`, `DEK-Info`). */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n} {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst lines = normalized.split('\\n');\n\tconst begin = lines[0];\n\tconst end = lines[lines.length - 1];\n\tif (\n\t\tbegin === undefined ||\n\t\tend === undefined ||\n\t\t!begin.startsWith('-----BEGIN ') ||\n\t\t!end.startsWith('-----END ')\n\t) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tconst label = begin.slice(11, -5);\n\tif (end !== `-----END ${label}-----`) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tconst delimiter = line.indexOf(': ');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 2));\n\t\tindex += 1;\n\t}\n\tconst body = lines.slice(index, lines.length - 1).join('');\n\treturn { label, headers, base64Body: body };\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 {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\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}\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}\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}\n}\n"],"mappings":"qxBAgOA,eAAsB,GACrB,EAA+B,CAAE,KAAM,QAAS,MAAO,OAAQ,EACpC,CAE3B,IAAM,EAAY,MADH,EAAU,CAAC,CAAC,OACI,YAAY,GAAuB,CAAS,EAAG,GAAM,CACnF,OACA,QACD,CAAC,EAED,GAAI,EAAE,cAAe,IAAc,EAAE,eAAgB,GACpD,MAAU,MAAM,iCAAiC,EAGlD,OAAO,EAAY,EAAU,UAAW,EAAU,UAAU,CAC7D,CAEA,SAAS,EAAY,EAAsB,EAAwC,CAClF,MAAO,CACN,YACA,aACA,MAAM,eAAgB,CACrB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,OAAQ,CAAS,CAAC,CAC5E,EACA,MAAM,eAAgB,CACrB,OAAO,EAAU,aAAc,MAAM,KAAK,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,EAAI,IAAM,IAAA,IACV,EAAI,IAAM,IAAA,IACV,EAAI,KAAO,IAAA,IACX,EAAI,KAAO,IAAA,IACX,EAAI,KAAO,IAAA,IACX,EAAI,MAAQ,IAAA,GAEZ,MAAU,MAAM,kDAAkD,EAEnE,OAAQ,EAAU,KAAlB,CACC,IAAK,MACJ,GAAI,EAAI,MAAQ,OAAS,OAAO,EAAI,GAAM,UAAY,OAAO,EAAI,GAAM,SACtE,MAAU,MAAM,gEAAgE,EAEjF,OACD,IAAK,QACJ,GACC,EAAI,MAAQ,MACZ,EAAI,MAAQ,EAAU,OACtB,OAAO,EAAI,GAAM,UACjB,OAAO,EAAI,GAAM,SAEjB,MAAU,MAAM,gEAAgE,EAEjF,OACD,IAAK,UACJ,GAAI,EAAI,MAAQ,OAAS,EAAI,MAAQ,WAAa,OAAO,EAAI,GAAM,SAClE,MAAU,MAAM,gEAAgE,EAEjF,MACF,CACD"}
1
+ {"version":3,"file":"keys.js","names":[],"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 and PSS), 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 { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const privatePem = await exportPkcs8Pem(keys.privateKey);\n *\n * // Import\n * const publicKey = 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.ts';\nimport {\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { md5 } from '#micro509/internal/crypto/hash.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\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 RsaScheme = 'pkcs1-v1_5' | 'pss';\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/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\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). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage). */\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/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\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 type EncryptedPkcs8Options = Pbes2EncryptionOptions;\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/** Machine-readable failure reason for the `import*` key functions. */\nexport type ImportKeyErrorCode = 'malformed';\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\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 always `'malformed'`: structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures all surface\n * the same way (see the throwing `*OrThrow` variants for raw error messages).\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'`).\n */\nexport type ImportEncryptedKeyErrorCode = 'malformed' | 'invalid_password';\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\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/**\n * Generate an asymmetric key pair for signing and verification.\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 *\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 generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, [\n\t\t'sign',\n\t\t'verify',\n\t]);\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\tasync exportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\tasync exportPrivateJwk() {\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 async 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 async 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 * @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 * @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 parsed.privateKeyDer;\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 * 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 * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\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\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['verify'],\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'` 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 failureResult('malformed', error instanceof Error ? error.message : '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\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed encrypted key',\n\t\t);\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 importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport async 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 async 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 * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\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 {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['sign'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 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 * @example\n * ```ts\n * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async 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 * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Expected algorithm (must match decrypted key)\n *\n * @throws {Error} If DER is malformed, password is wrong, 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): Promise<CryptoKey> {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch {\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\tconst decrypted = await decryptPbes2(\n\t\tder.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData.value,\n\t\tpassword,\n\t);\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\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): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importEncryptedPkcs8DerOrThrow(\n\t\tpemDecodeOrThrow('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\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): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));\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 async 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 async 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\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 async 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 *\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\treturn importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);\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.\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport async 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\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 * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed or algorithm doesn't match\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, [\n\t\t\t'verify',\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 * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, ['sign']);\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/** 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}\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}\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} {\n\tconst children = readSequenceChildren(der);\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tchildren.length > 4 ||\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 algorithmChildren = readSequenceChildren(\n\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t);\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\treturn {\n\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\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};\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/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcKeyInput['curve']): string {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn OIDS.prime256v1;\n\t\tcase 'P-384':\n\t\t\treturn OIDS.secp384r1;\n\t\tcase 'P-521':\n\t\t\treturn OIDS.secp521r1;\n\t}\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' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\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 an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back 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 = parseTraditionalPem(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\tif (parsed.headers.get('Proc-Type') !== '4,ENCRYPTED' || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',');\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`. */\nasync function 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/** 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}\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\n/** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */\nfunction parseTraditionalPem(pem: string): {\n\t/** PEM type label between `BEGIN` and `END` markers. */\n\treadonly label: string;\n\t/** RFC 1421 encapsulated headers (e.g. `Proc-Type`, `DEK-Info`). */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n} {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst lines = normalized.split('\\n');\n\tconst begin = lines[0];\n\tconst end = lines[lines.length - 1];\n\tif (\n\t\tbegin === undefined ||\n\t\tend === undefined ||\n\t\t!begin.startsWith('-----BEGIN ') ||\n\t\t!end.startsWith('-----END ')\n\t) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tconst label = begin.slice(11, -5);\n\tif (end !== `-----END ${label}-----`) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tconst delimiter = line.indexOf(': ');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 2));\n\t\tindex += 1;\n\t}\n\tconst body = lines.slice(index, lines.length - 1).join('');\n\treturn { label, headers, base64Body: body };\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 {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\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}\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}\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}\n}\n"],"mappings":"4xBA6NA,eAAsB,GACrB,EAA+B,CAAE,KAAM,QAAS,MAAO,OAAQ,EACpC,CAE3B,IAAM,EAAY,MADH,EAAU,CAAC,CAAC,OACI,YAAY,GAAuB,CAAS,EAAG,GAAM,CACnF,OACA,QACD,CAAC,EAED,GAAI,EAAE,cAAe,IAAc,EAAE,eAAgB,GACpD,MAAU,MAAM,iCAAiC,EAGlD,OAAO,EAAY,EAAU,UAAW,EAAU,UAAU,CAC7D,CAEA,SAAS,EAAY,EAAsB,EAAwC,CAClF,MAAO,CACN,YACA,aACA,MAAM,eAAgB,CACrB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,OAAQ,CAAS,CAAC,CAC5E,EACA,MAAM,eAAgB,CACrB,OAAO,EAAU,aAAc,MAAM,KAAK,cAAc,CAAC,CAC1D,EACA,MAAM,gBAAiB,CACtB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,QAAS,CAAU,CAAC,CAC9E,EACA,MAAM,gBAAiB,CACtB,OAAO,EAAU,cAAe,MAAM,KAAK,eAAe,CAAC,CAC5D,EACA,MAAM,iBAAkB,CACvB,OAAO,EAAU,CAAC,CAAC,OAAO,UAAU,MAAO,CAAS,CACrD,EACA,MAAM,kBAAmB,CACxB,OAAO,EAAU,CAAC,CAAC,OAAO,UAAU,MAAO,CAAU,CACtD,CACD,CACD,CAQA,eAAsB,EAAc,EAA2C,CAC9E,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,OAAQ,CAAS,CAAC,CAC5E,CASA,eAAsB,EAAe,EAA4C,CAChF,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,QAAS,CAAU,CAAC,CA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keys.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- import { Pbes2EncryptionOptions, Pbes2EncryptionScheme, Pbes2Prf } from "./internal/crypto/pbes2.js";
2
- import { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcPublicKeyInput, ImportEd25519PublicKeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaPublicKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem } from "./keys/keys.js";
3
- export { type EcKeyAlgorithmInput, type EcNamedCurve, type Ed25519KeyAlgorithmInput, type EncryptedPkcs8Options, type ImportEcPublicKeyInput, type ImportEd25519PublicKeyInput, type ImportEncryptedKeyErrorCode, type ImportEncryptedKeyFailure, type ImportEncryptedKeyResult, type ImportKeyErrorCode, type ImportKeyFailure, type ImportKeyResult, type ImportRsaPublicKeyInput, type KeyAlgorithmInput, type KeyPairMaterial, type LegacyPemEncryptionOptions, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, type PrivateKeyImportInput, type PublicKeyImportInput, type RsaHash, type RsaKeyAlgorithmInput, type RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem };
1
+ import { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcKeyInput, ImportEd25519KeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem } from "./keys/keys.js";
2
+ export { type EcKeyAlgorithmInput, type EcNamedCurve, type Ed25519KeyAlgorithmInput, type EncryptedPkcs8Options, type ImportEcKeyInput, type ImportEd25519KeyInput, type ImportEncryptedKeyErrorCode, type ImportEncryptedKeyFailure, type ImportEncryptedKeyResult, type ImportKeyErrorCode, type ImportKeyFailure, type ImportKeyResult, type ImportRsaKeyInput, type KeyAlgorithmInput, type KeyPairMaterial, type LegacyPemEncryptionOptions, type PrivateKeyImportInput, type PublicKeyImportInput, type RsaHash, type RsaKeyAlgorithmInput, type RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem };