micro509 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +105 -225
  3. package/dist/crypto/crypto.d.ts +42 -11
  4. package/dist/crypto/crypto.js +53 -22
  5. package/dist/crypto/crypto.js.map +1 -1
  6. package/dist/crypto.d.ts +2 -2
  7. package/dist/crypto.js +1 -2
  8. package/dist/der/der.d.ts +41 -33
  9. package/dist/der/der.js +26 -24
  10. package/dist/der/der.js.map +1 -1
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +19 -19
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +343 -43
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js +146 -0
  17. package/dist/internal/asn1/ber.js.map +1 -0
  18. package/dist/internal/asn1/decode-refusal.js +29 -0
  19. package/dist/internal/asn1/decode-refusal.js.map +1 -0
  20. package/dist/internal/asn1/der.d.ts +38 -41
  21. package/dist/internal/asn1/der.js +131 -52
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +83 -53
  24. package/dist/internal/asn1/oids.js.map +1 -1
  25. package/dist/internal/asn1/oids2.js +1 -2
  26. package/dist/internal/asn1/oids2.js.map +1 -1
  27. package/dist/internal/crypto/algorithm-names.js +1 -2
  28. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  29. package/dist/internal/crypto/ecdsa.js +13 -8
  30. package/dist/internal/crypto/ecdsa.js.map +1 -1
  31. package/dist/internal/crypto/hash.js +1 -2
  32. package/dist/internal/crypto/hash.js.map +1 -1
  33. package/dist/internal/crypto/pbes2.d.ts +24 -11
  34. package/dist/internal/crypto/pbes2.js +79 -26
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +46 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +4 -7
  39. package/dist/internal/crypto/sig-verify.js +107 -60
  40. package/dist/internal/crypto/sig-verify.js.map +1 -1
  41. package/dist/internal/crypto/signing.d.ts +1 -4
  42. package/dist/internal/crypto/signing.js +28 -29
  43. package/dist/internal/crypto/signing.js.map +1 -1
  44. package/dist/internal/crypto/webcrypto.js +1 -2
  45. package/dist/internal/crypto/webcrypto.js.map +1 -1
  46. package/dist/internal/shared/base64.js +1 -2
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +3 -6
  49. package/dist/internal/shared/dn.js +99 -53
  50. package/dist/internal/shared/dn.js.map +1 -1
  51. package/dist/internal/shared/idna-tables.js +7217 -0
  52. package/dist/internal/shared/idna-tables.js.map +1 -0
  53. package/dist/internal/shared/idna.js +296 -0
  54. package/dist/internal/shared/idna.js.map +1 -0
  55. package/dist/internal/shared/ip.d.ts +4 -7
  56. package/dist/internal/shared/ip.js +1 -2
  57. package/dist/internal/shared/ip.js.map +1 -1
  58. package/dist/internal/shared/mailbox.js +26 -0
  59. package/dist/internal/shared/mailbox.js.map +1 -0
  60. package/dist/internal/shared/punycode.js +101 -0
  61. package/dist/internal/shared/punycode.js.map +1 -0
  62. package/dist/internal/shared/rfc3454-tables.js +1 -2
  63. package/dist/internal/shared/rfc3454-tables.js.map +1 -1
  64. package/dist/internal/shared/rfc4518-tables.js +119 -0
  65. package/dist/internal/shared/rfc4518-tables.js.map +1 -0
  66. package/dist/internal/shared/uri-host.js +102 -0
  67. package/dist/internal/shared/uri-host.js.map +1 -0
  68. package/dist/internal/verify/name-constraints-engine.js +246 -131
  69. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  70. package/dist/internal/verify/policy-engine.js +6 -21
  71. package/dist/internal/verify/policy-engine.js.map +1 -1
  72. package/dist/internal/verify/verify-path.d.ts +1 -4
  73. package/dist/internal/verify/verify-path.js +267 -131
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +1 -2
  76. package/dist/internal/x509/directory-name.js.map +1 -1
  77. package/dist/internal/x509/extension-bits.js +2 -3
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +1 -4
  80. package/dist/internal/x509/extension-errors.js +1 -2
  81. package/dist/internal/x509/extension-errors.js.map +1 -1
  82. package/dist/internal/x509/extension-registry.js +107 -89
  83. package/dist/internal/x509/extension-registry.js.map +1 -1
  84. package/dist/internal/x509/general-name-profile.js +129 -0
  85. package/dist/internal/x509/general-name-profile.js.map +1 -0
  86. package/dist/internal/x509/general-name-tags.js +1 -2
  87. package/dist/internal/x509/general-name-tags.js.map +1 -1
  88. package/dist/internal/x509/general-name.js +128 -42
  89. package/dist/internal/x509/general-name.js.map +1 -1
  90. package/dist/internal/x509/name-fields.js +1 -2
  91. package/dist/internal/x509/name-fields.js.map +1 -1
  92. package/dist/internal/x509/or-address.js +217 -0
  93. package/dist/internal/x509/or-address.js.map +1 -0
  94. package/dist/keys/keys.d.ts +112 -97
  95. package/dist/keys/keys.js +211 -204
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -3
  98. package/dist/pem/pem.d.ts +14 -17
  99. package/dist/pem/pem.js +16 -17
  100. package/dist/pem/pem.js.map +1 -1
  101. package/dist/pem.js +1 -2
  102. package/dist/pkcs/pfx.d.ts +57 -32
  103. package/dist/pkcs/pfx.js +209 -173
  104. package/dist/pkcs/pfx.js.map +1 -1
  105. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  106. package/dist/pkcs/pkcs12-mac.js +266 -79
  107. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  108. package/dist/pkcs/pkcs7.d.ts +43 -37
  109. package/dist/pkcs/pkcs7.js +218 -217
  110. package/dist/pkcs/pkcs7.js.map +1 -1
  111. package/dist/pkcs.d.ts +4 -3
  112. package/dist/result/result.d.ts +27 -20
  113. package/dist/result/result.js +8 -3
  114. package/dist/result/result.js.map +1 -1
  115. package/dist/result.d.ts +2 -2
  116. package/dist/result.js +1 -2
  117. package/dist/revocation/chain.d.ts +101 -23
  118. package/dist/revocation/chain.js +436 -182
  119. package/dist/revocation/chain.js.map +1 -1
  120. package/dist/revocation/crl.d.ts +131 -67
  121. package/dist/revocation/crl.js +444 -323
  122. package/dist/revocation/crl.js.map +1 -1
  123. package/dist/revocation/ocsp.d.ts +94 -59
  124. package/dist/revocation/ocsp.js +331 -293
  125. package/dist/revocation/ocsp.js.map +1 -1
  126. package/dist/revocation/revocation.d.ts +47 -35
  127. package/dist/revocation/revocation.js +88 -57
  128. package/dist/revocation/revocation.js.map +1 -1
  129. package/dist/revocation.d.ts +3 -3
  130. package/dist/verify/identity.d.ts +16 -19
  131. package/dist/verify/identity.js +118 -89
  132. package/dist/verify/identity.js.map +1 -1
  133. package/dist/verify/name-constraints.d.ts +1 -4
  134. package/dist/verify/policy.d.ts +9 -7
  135. package/dist/verify/verify.d.ts +84 -46
  136. package/dist/verify/verify.js +300 -152
  137. package/dist/verify/verify.js.map +1 -1
  138. package/dist/verify.d.ts +2 -2
  139. package/dist/x509/certificate.d.ts +20 -21
  140. package/dist/x509/certificate.js +62 -46
  141. package/dist/x509/certificate.js.map +1 -1
  142. package/dist/x509/csr.d.ts +5 -7
  143. package/dist/x509/csr.js +10 -11
  144. package/dist/x509/csr.js.map +1 -1
  145. package/dist/x509/extensions.d.ts +154 -66
  146. package/dist/x509/extensions.js +317 -151
  147. package/dist/x509/extensions.js.map +1 -1
  148. package/dist/x509/fingerprint.d.ts +4 -7
  149. package/dist/x509/fingerprint.js +1 -2
  150. package/dist/x509/fingerprint.js.map +1 -1
  151. package/dist/x509/name-text.d.ts +7 -9
  152. package/dist/x509/name-text.js +18 -4
  153. package/dist/x509/name-text.js.map +1 -1
  154. package/dist/x509/name.d.ts +9 -11
  155. package/dist/x509/name.js +18 -19
  156. package/dist/x509/name.js.map +1 -1
  157. package/dist/x509/parse.d.ts +84 -69
  158. package/dist/x509/parse.js +421 -400
  159. package/dist/x509/parse.js.map +1 -1
  160. package/dist/x509.d.ts +2 -2
  161. package/package.json +76 -59
@@ -1 +1 @@
1
- {"version":3,"file":"oids.js","names":[],"sources":["../../../src/internal/asn1/oids.json"],"sourcesContent":[""],"mappings":""}
1
+ {"version":3,"file":"oids.js","names":["oids_default","\"arc\"","\"children\"","\"data\"","\"pss\"","\"ucl\"","\"pilot\"","\"pilotAttributeType\"","\"oids\"","\"userId\"","\"domainComponent\"","\"memberBody\"","\"us\"","\"rsadsi\"","\"pkcs\"","\"pkcs1\"","\"rsaEncryption\"","\"sha1WithRSAEncryption\"","\"mgf1\"","\"rsassaPss\"","\"sha256WithRSAEncryption\"","\"sha384WithRSAEncryption\"","\"sha512WithRSAEncryption\"","\"pkcs5\"","\"pbkdf2\"","\"pbes2\"","\"pbmac1\"","\"pkcs7\"","\"pkcs7Data\"","\"pkcs7SignedData\"","\"pkcs7EncryptedData\"","\"pkcs9\"","\"emailAddress\"","\"cmsContentType\"","\"cmsMessageDigest\"","\"extensionRequest\"","\"friendlyName\"","\"localKeyId\"","\"certTypes\"","\"x509CertificateBagType\"","\"pkcs12Bags\"","\"bagTypes\"","\"bags\"","\"pkcs12KeyBag\"","\"pkcs12CertBag\"","\"digestAlgorithm\"","\"hmacWithSHA1\"","\"hmacWithSHA256\"","\"hmacWithSHA384\"","\"hmacWithSHA512\"","\"ansiX962\"","\"keyType\"","\"ecPublicKey\"","\"curves\"","\"prime\"","\"prime256v1\"","\"signatures\"","\"ecdsaWithSHA1\"","\"sha2\"","\"ecdsaWithSHA224\"","\"ecdsaWithSHA256\"","\"ecdsaWithSHA384\"","\"ecdsaWithSHA512\"","\"identifiedOrganization\"","\"certicom\"","\"curve\"","\"secp384r1\"","\"secp521r1\"","\"edwardsCurveAlgs\"","\"x25519\"","\"x448\"","\"ed25519\"","\"ed448\"","\"dod\"","\"internet\"","\"security\"","\"mechanisms\"","\"pkix\"","\"extensions\"","\"authorityInfoAccess\"","\"policyQualifiers\"","\"cpsPolicyQualifier\"","\"userNoticePolicyQualifier\"","\"extendedKeyUsage\"","\"serverAuth\"","\"clientAuth\"","\"codeSigning\"","\"emailProtection\"","\"timeStamping\"","\"ocspSigning\"","\"otherNameForms\"","\"idOnDnsSrv\"","\"idOnSmtpUtf8Mailbox\"","\"accessMethods\"","\"ocspAccessMethod\"","\"caIssuersAccessMethod\"","\"ocsp\"","\"ocspBasicResponse\"","\"ocspNonce\"","\"ocspNoCheck\"","\"kerberosV5\"","\"idPkinitSan\"","\"private\"","\"enterprise\"","\"microsoft\"","\"msEnrollment\"","\"msPrincipalNameForms\"","\"ntPrincipalName\"","\"oiw\"","\"secsig\"","\"algorithms\"","\"sha1\"","\"ds\"","\"attributeType\"","\"commonName\"","\"surname\"","\"serialNumber\"","\"countryName\"","\"localityName\"","\"stateOrProvinceName\"","\"streetAddress\"","\"organizationName\"","\"organizationalUnitName\"","\"title\"","\"givenName\"","\"certificateExtension\"","\"subjectKeyIdentifier\"","\"keyUsage\"","\"subjectAltName\"","\"issuerAltName\"","\"basicConstraints\"","\"cRLNumber\"","\"cRLReason\"","\"invalidityDate\"","\"deltaCRLIndicator\"","\"issuingDistributionPoint\"","\"certificateIssuer\"","\"nameConstraints\"","\"cRLDistributionPoints\"","\"certificatePolicies\"","\"policyMappings\"","\"authorityKeyIdentifier\"","\"policyConstraints\"","\"freshestCRL\"","\"inhibitAnyPolicy\"","\"noRevAvail\"","\"anyPolicy\"","\"country\"","\"organization\"","\"gov\"","\"csor\"","\"nistAlgorithms\"","\"aes\"","\"aes128Cbc\"","\"aes192Cbc\"","\"aes256Cbc\"","\"hashes\"","\"sha256\"","\"sha384\"","\"sha512\""],"sources":["../../../src/internal/asn1/oids.json"],"sourcesContent":[""],"mappings":""}
@@ -1,5 +1,5 @@
1
1
  import e from "./oids.js";
2
- //#region src/internal/asn1/oids.ts
2
+ // src/internal/asn1/oids.ts
3
3
  /**
4
4
  * Centralized ASN.1 object identifier registry referenced by create, parse,
5
5
  * verify, and container modules.
@@ -70,7 +70,6 @@ function flattenOidTree(e) {
70
70
  * - hash algorithms.
71
71
  */
72
72
  const t = flattenOidTree(e);
73
- //#endregion
74
73
  export { t as OIDS, e as OID_GROUP_SPECS };
75
74
 
76
75
  //# sourceMappingURL=oids2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oids2.js","names":["OID_GROUP_SPECS"],"sources":["../../../src/internal/asn1/oids.ts"],"sourcesContent":["/**\n * Centralized ASN.1 object identifier registry referenced by create, parse,\n * verify, and container modules.\n *\n * All OIDs are dotted-decimal string constants keyed by their common short name.\n *\n * @module\n */\n\nimport OID_GROUP_SPECS from './oids.json' with { type: 'json' };\n\ntype OidLeaves = { readonly [name: string]: string };\ntype OidNode = {\n\treadonly arc: string;\n\treadonly oids?: OidLeaves;\n\treadonly children?: OidTree;\n};\ntype OidTree = { readonly [name: string]: OidNode };\ntype OidMap = { readonly [name: string]: string };\ntype MutableOidMap = { [name: string]: string };\ndeclare const oidNameBrand: unique symbol;\ntype OidValue<Name extends string, Value extends string> = Value & {\n\treadonly [oidNameBrand]?: Name;\n};\ntype JoinOidPrefix<Base extends string, Arc extends string> = Base extends ''\n\t? Arc\n\t: `${Base}.${Arc}`;\ntype OidsFromLeaves<Prefix extends string, Leaves extends OidLeaves> = {\n\treadonly [Name in keyof Leaves]: OidValue<Name & string, `${Prefix}.${Leaves[Name]}`>;\n};\ntype UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (\n\tvalue: infer Intersection,\n) => void\n\t? Intersection\n\t: never;\ntype OidsFromNode<Node extends OidNode, Base extends string = ''> = Node extends {\n\treadonly arc: infer Arc extends string;\n}\n\t? (Node extends { readonly oids: infer Leaves extends OidLeaves }\n\t\t\t? OidsFromLeaves<JoinOidPrefix<Base, Arc>, Leaves>\n\t\t\t: unknown) &\n\t\t\t(Node extends { readonly children: infer Children extends OidTree }\n\t\t\t\t? OidsFromTree<Children, JoinOidPrefix<Base, Arc>>\n\t\t\t\t: unknown)\n\t: never;\ntype OidsFromTree<Tree extends OidTree, Base extends string = ''> = UnionToIntersection<\n\tOidsFromNode<Tree[keyof Tree], Base>\n>;\ntype OidDocumentRoots<Document> = Omit<Document, '$schema'>;\ntype OidRegistry = OidsFromTree<OidDocumentRoots<typeof OID_GROUP_SPECS>>;\n\nfunction joinOidPrefix(basePrefix: string, arc: string): string {\n\tif (basePrefix === '') {\n\t\treturn arc;\n\t}\n\n\treturn `${basePrefix}.${arc}`;\n}\n\nfunction isOidNode(value: unknown): value is OidNode {\n\treturn typeof value === 'object' && value !== null && 'arc' in value;\n}\n\nfunction hasOidName(oids: OidMap, name: string): boolean {\n\treturn Object.hasOwn(oids, name);\n}\n\nfunction addOidNode(oids: MutableOidMap, node: OidNode, basePrefix: string): void {\n\tconst prefix = joinOidPrefix(basePrefix, node.arc);\n\n\tif (node.oids !== undefined) {\n\t\tfor (const [name, arc] of Object.entries(node.oids)) {\n\t\t\tconst path = joinOidPrefix(prefix, arc);\n\t\t\tif (hasOidName(oids, name)) {\n\t\t\t\tconst existingPath = oids[name];\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`Duplicate OID name \"${name}\" at ${path}; already assigned to ${existingPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\toids[name] = path;\n\t\t}\n\t}\n\n\tif (node.children !== undefined) {\n\t\taddOidTree(oids, node.children, prefix);\n\t}\n}\n\nfunction addOidTree(oids: MutableOidMap, tree: OidTree, basePrefix: string): void {\n\tfor (const node of Object.values(tree)) {\n\t\taddOidNode(oids, node, basePrefix);\n\t}\n}\n\nfunction addOidDocument(oids: MutableOidMap, document: typeof OID_GROUP_SPECS): void {\n\tfor (const value of Object.values(document)) {\n\t\tif (isOidNode(value)) {\n\t\t\taddOidNode(oids, value, '');\n\t\t}\n\t}\n}\n\nfunction collectOidNamesFromNode(names: Set<string>, node: OidNode): void {\n\tif (node.oids !== undefined) {\n\t\tfor (const name of Object.keys(node.oids)) {\n\t\t\tnames.add(name);\n\t\t}\n\t}\n\n\tif (node.children !== undefined) {\n\t\tfor (const child of Object.values(node.children)) {\n\t\t\tcollectOidNamesFromNode(names, child);\n\t\t}\n\t}\n}\n\nfunction collectOidNamesFromDocument(document: typeof OID_GROUP_SPECS): readonly string[] {\n\tconst names = new Set<string>();\n\tfor (const value of Object.values(document)) {\n\t\tif (isOidNode(value)) {\n\t\t\tcollectOidNamesFromNode(names, value);\n\t\t}\n\t}\n\treturn [...names];\n}\n\nfunction isOidRegistry(oids: OidMap, names: readonly string[]): oids is OidRegistry {\n\tfor (const name of names) {\n\t\tif (!hasOidName(oids, name)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction flattenOidTree(tree: typeof OID_GROUP_SPECS): OidRegistry {\n\tconst oids: MutableOidMap = Object.create(null);\n\taddOidDocument(oids, tree);\n\tconst names = collectOidNamesFromDocument(tree);\n\tif (!isOidRegistry(oids, names)) {\n\t\tconst missingNames = names.filter((name) => !hasOidName(oids, name));\n\t\tthrow new TypeError(`Incomplete OID registry; missing ${missingNames.join(', ')}`);\n\t}\n\treturn oids;\n}\n\n/**\n * Dotted-decimal OID constants.\n *\n * Includes:\n * - EKU purposes,\n * - PKCS algorithms,\n * - PKIX access methods,\n * - X.500 attributes,\n * - X.509v3 extensions, and\n * - hash algorithms.\n */\nconst OIDS: OidRegistry = flattenOidTree(OID_GROUP_SPECS);\n\nexport { OID_GROUP_SPECS, OIDS };\n"],"mappings":";;;;;;;;;;AAmDA,SAAS,cAAc,GAAoB,GAAqB;CAK/D,OAJI,MAAe,KACX,IAGD,GAAG,EAAW,GAAG;AACzB;AAEA,SAAS,UAAU,GAAkC;CACpD,OAAO,OAAO,KAAU,cAAY,KAAkB,SAAS;AAChE;AAEA,SAAS,WAAW,GAAc,GAAuB;CACxD,OAAO,OAAO,OAAO,GAAM,CAAI;AAChC;AAEA,SAAS,WAAW,GAAqB,GAAe,GAA0B;CACjF,IAAM,IAA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;CAClE,IAAM,IAAsB,OAAO,OAAO,IAAI;CAC9C,eAAe,GAAM,CAAI;CACzB,IAAM,IAAQ,4BAA4B,CAAI;CAC9C,IAAI,CAAC,cAAc,GAAM,CAAK,GAAG;EAChC,IAAM,IAAe,EAAM,QAAQ,MAAS,CAAC,WAAW,GAAM,CAAI,CAAC;EACnE,MAAU,UAAU,oCAAoC,EAAa,KAAK,IAAI,GAAG;CAClF;CACA,OAAO;AACR;;;;;;;;;;;;AAaA,MAAM,IAAoB,eAAeA,CAAe"}
1
+ {"version":3,"file":"oids2.js","names":["OID_GROUP_SPECS","oids_default","basePrefix","arc","value","oids","name","prefix","node","path","existingPath","tree","document","child","names","missingNames","OIDS"],"sources":["../../../src/internal/asn1/oids.ts"],"sourcesContent":["/**\n * Centralized ASN.1 object identifier registry referenced by create, parse,\n * verify, and container modules.\n *\n * All OIDs are dotted-decimal string constants keyed by their common short name.\n *\n * @module\n */\n\nimport OID_GROUP_SPECS from './oids.json' with { type: 'json' };\n\ntype OidLeaves = { readonly [name: string]: string };\ntype OidNode = {\n\treadonly arc: string;\n\treadonly oids?: OidLeaves;\n\treadonly children?: OidTree;\n};\ntype OidTree = { readonly [name: string]: OidNode };\ntype OidMap = { readonly [name: string]: string };\ntype MutableOidMap = { [name: string]: string };\ndeclare const oidNameBrand: unique symbol;\ntype OidValue<Name extends string, Value extends string> = Value & {\n\treadonly [oidNameBrand]?: Name;\n};\ntype JoinOidPrefix<Base extends string, Arc extends string> = Base extends ''\n\t? Arc\n\t: `${Base}.${Arc}`;\ntype OidsFromLeaves<Prefix extends string, Leaves extends OidLeaves> = {\n\treadonly [Name in keyof Leaves]: OidValue<Name & string, `${Prefix}.${Leaves[Name]}`>;\n};\ntype UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (\n\tvalue: infer Intersection,\n) => void\n\t? Intersection\n\t: never;\ntype OidsFromNode<Node extends OidNode, Base extends string = ''> = Node extends {\n\treadonly arc: infer Arc extends string;\n}\n\t? (Node extends { readonly oids: infer Leaves extends OidLeaves }\n\t\t\t? OidsFromLeaves<JoinOidPrefix<Base, Arc>, Leaves>\n\t\t\t: unknown) &\n\t\t\t(Node extends { readonly children: infer Children extends OidTree }\n\t\t\t\t? OidsFromTree<Children, JoinOidPrefix<Base, Arc>>\n\t\t\t\t: unknown)\n\t: never;\ntype OidsFromTree<Tree extends OidTree, Base extends string = ''> = UnionToIntersection<\n\tOidsFromNode<Tree[keyof Tree], Base>\n>;\ntype OidDocumentRoots<Document> = Omit<Document, '$schema'>;\ntype OidRegistry = OidsFromTree<OidDocumentRoots<typeof OID_GROUP_SPECS>>;\n\nfunction joinOidPrefix(basePrefix: string, arc: string): string {\n\tif (basePrefix === '') {\n\t\treturn arc;\n\t}\n\n\treturn `${basePrefix}.${arc}`;\n}\n\nfunction isOidNode(value: unknown): value is OidNode {\n\treturn typeof value === 'object' && value !== null && 'arc' in value;\n}\n\nfunction hasOidName(oids: OidMap, name: string): boolean {\n\treturn Object.hasOwn(oids, name);\n}\n\nfunction addOidNode(oids: MutableOidMap, node: OidNode, basePrefix: string): void {\n\tconst prefix = joinOidPrefix(basePrefix, node.arc);\n\n\tif (node.oids !== undefined) {\n\t\tfor (const [name, arc] of Object.entries(node.oids)) {\n\t\t\tconst path = joinOidPrefix(prefix, arc);\n\t\t\tif (hasOidName(oids, name)) {\n\t\t\t\tconst existingPath = oids[name];\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`Duplicate OID name \"${name}\" at ${path}; already assigned to ${existingPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\toids[name] = path;\n\t\t}\n\t}\n\n\tif (node.children !== undefined) {\n\t\taddOidTree(oids, node.children, prefix);\n\t}\n}\n\nfunction addOidTree(oids: MutableOidMap, tree: OidTree, basePrefix: string): void {\n\tfor (const node of Object.values(tree)) {\n\t\taddOidNode(oids, node, basePrefix);\n\t}\n}\n\nfunction addOidDocument(oids: MutableOidMap, document: typeof OID_GROUP_SPECS): void {\n\tfor (const value of Object.values(document)) {\n\t\tif (isOidNode(value)) {\n\t\t\taddOidNode(oids, value, '');\n\t\t}\n\t}\n}\n\nfunction collectOidNamesFromNode(names: Set<string>, node: OidNode): void {\n\tif (node.oids !== undefined) {\n\t\tfor (const name of Object.keys(node.oids)) {\n\t\t\tnames.add(name);\n\t\t}\n\t}\n\n\tif (node.children !== undefined) {\n\t\tfor (const child of Object.values(node.children)) {\n\t\t\tcollectOidNamesFromNode(names, child);\n\t\t}\n\t}\n}\n\nfunction collectOidNamesFromDocument(document: typeof OID_GROUP_SPECS): readonly string[] {\n\tconst names = new Set<string>();\n\tfor (const value of Object.values(document)) {\n\t\tif (isOidNode(value)) {\n\t\t\tcollectOidNamesFromNode(names, value);\n\t\t}\n\t}\n\treturn [...names];\n}\n\nfunction isOidRegistry(oids: OidMap, names: readonly string[]): oids is OidRegistry {\n\tfor (const name of names) {\n\t\tif (!hasOidName(oids, name)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction flattenOidTree(tree: typeof OID_GROUP_SPECS): OidRegistry {\n\tconst oids: MutableOidMap = Object.create(null);\n\taddOidDocument(oids, tree);\n\tconst names = collectOidNamesFromDocument(tree);\n\tif (!isOidRegistry(oids, names)) {\n\t\tconst missingNames = names.filter((name) => !hasOidName(oids, name));\n\t\tthrow new TypeError(`Incomplete OID registry; missing ${missingNames.join(', ')}`);\n\t}\n\treturn oids;\n}\n\n/**\n * Dotted-decimal OID constants.\n *\n * Includes:\n * - EKU purposes,\n * - PKCS algorithms,\n * - PKIX access methods,\n * - X.500 attributes,\n * - X.509v3 extensions, and\n * - hash algorithms.\n */\nconst OIDS: OidRegistry = flattenOidTree(OID_GROUP_SPECS);\n\nexport { OID_GROUP_SPECS, OIDS };\n"],"mappings":";;;;;;;;;;AAmDA,SAAS,cAAc,GAAoB,GAAqB;CAK/D,OAJIE,MAAe,KACXC,IAGD,GAAGD,EAAW,GAAGC;AACzB;AAEA,SAAS,UAAU,GAAkC;CACpD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,AAAI,UAAUR,CAAK,KAClB,wBAAwBU,GAAOV,CAAK;CAGtC,OAAO,CAAC,GAAGU,CAAK;AACjB;AAEA,SAAS,cAAc,GAAc,GAA+C;CACnF,KAAK,IAAMR,KAAQQ,GAClB,IAAI,CAAC,WAAWT,GAAMC,CAAI,GACzB,OAAO;CAGT,OAAO;AACR;AAEA,SAAS,eAAe,GAA2C;CAClE,IAAMD,IAAsB,OAAO,OAAO,IAAI;CAC9C,eAAeA,GAAMM,CAAI;CACzB,IAAMG,IAAQ,4BAA4BH,CAAI;CAC9C,IAAI,CAAC,cAAcN,GAAMS,CAAK,GAAG;EAChC,IAAMC,IAAeD,EAAM,QAAQ,MAAS,CAAC,WAAWT,GAAMC,CAAI,CAAC;EACnE,MAAU,UAAU,oCAAoCS,EAAa,KAAK,IAAI,GAAG;CAClF;CACA,OAAOV;AACR;;;;;;;;;;;;AAaA,MAAMW,IAAoB,eAAehB,CAAe"}
@@ -1,6 +1,6 @@
1
1
  import { OIDS as e } from "../asn1/oids2.js";
2
2
  import { parseRsaPssParameters as t } from "./rsa-pss.js";
3
- //#region src/internal/crypto/algorithm-names.ts
3
+ // src/internal/crypto/algorithm-names.ts
4
4
  /**
5
5
  * Human-readable algorithm labels for parsed OIDs.
6
6
  *
@@ -58,7 +58,6 @@ function describePublicKeyAlgorithm(t, n) {
58
58
  default: return `Unknown (${t})`;
59
59
  }
60
60
  }
61
- //#endregion
62
61
  export { describeHashAlgorithm, describePublicKeyAlgorithm, describeSignatureAlgorithm };
63
62
 
64
63
  //# sourceMappingURL=algorithm-names.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"algorithm-names.js","names":[],"sources":["../../../src/internal/crypto/algorithm-names.ts"],"sourcesContent":["/**\n * Human-readable algorithm labels for parsed OIDs.\n *\n * Shared by certificate, revocation, and PKCS parse surfaces so callers can\n * display meaningful algorithm names without memorizing dotted-decimal OIDs.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\n\n/** Convert a hash or message-digest OID into a human-readable name. */\nexport function describeHashAlgorithm(oid: string): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1:\n\t\t\treturn 'SHA-1';\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a signature AlgorithmIdentifier into a human-readable name. */\nexport function describeSignatureAlgorithm(\n\toid: string,\n\tparametersDer: Uint8Array | undefined,\n): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-1';\n\t\tcase OIDS.sha256WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-256';\n\t\tcase OIDS.sha384WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-384';\n\t\tcase OIDS.sha512WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-512';\n\t\tcase OIDS.rsassaPss: {\n\t\t\tconst parsed = parseRsaPssParameters(parametersDer);\n\t\t\treturn parsed.ok ? `RSA-PSS with ${parsed.value.hash}` : 'RSA-PSS';\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA1:\n\t\t\treturn 'ECDSA with SHA-1';\n\t\tcase OIDS.ecdsaWithSHA224:\n\t\t\treturn 'ECDSA with SHA-224';\n\t\tcase OIDS.ecdsaWithSHA256:\n\t\t\treturn 'ECDSA with SHA-256';\n\t\tcase OIDS.ecdsaWithSHA384:\n\t\t\treturn 'ECDSA with SHA-384';\n\t\tcase OIDS.ecdsaWithSHA512:\n\t\t\treturn 'ECDSA with SHA-512';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tcase OIDS.ed448:\n\t\t\treturn 'Ed448';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a SubjectPublicKeyInfo algorithm identifier into a human-readable name. */\nexport function describePublicKeyAlgorithm(oid: string, parametersOid: string | undefined): string {\n\tswitch (oid) {\n\t\tcase OIDS.rsaEncryption:\n\t\t\treturn 'RSA';\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn 'RSA-PSS';\n\t\tcase OIDS.ecPublicKey:\n\t\t\tswitch (parametersOid) {\n\t\t\t\tcase OIDS.prime256v1:\n\t\t\t\t\treturn 'EC P-256';\n\t\t\t\tcase OIDS.secp384r1:\n\t\t\t\t\treturn 'EC P-384';\n\t\t\t\tcase OIDS.secp521r1:\n\t\t\t\t\treturn 'EC P-521';\n\t\t\t\tdefault:\n\t\t\t\t\treturn 'EC';\n\t\t\t}\n\t\tcase OIDS.x25519:\n\t\t\treturn 'X25519';\n\t\tcase OIDS.x448:\n\t\t\treturn 'X448';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tcase OIDS.ed448:\n\t\t\treturn 'Ed448';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,sBAAsB,GAAqB;CAC1D,QAAQ,GAAR;EACC,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD;;AAGA,SAAgB,2BACf,GACA,GACS;CACT,QAAQ,GAAR;EACC,KAAK,EAAK,uBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,WAAW;GACpB,IAAM,IAAS,EAAsB,CAAa;GAClD,OAAO,EAAO,KAAK,gBAAgB,EAAO,MAAM,SAAS;EAC1D;EACA,KAAK,EAAK,eACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,SACT,OAAO;EACR,KAAK,EAAK,OACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD;;AAGA,SAAgB,2BAA2B,GAAa,GAA2C;CAClG,QAAQ,GAAR;EACC,KAAK,EAAK,eACT,OAAO;EACR,KAAK,EAAK,WACT,OAAO;EACR,KAAK,EAAK,aACT,QAAQ,GAAR;GACC,KAAK,EAAK,YACT,OAAO;GACR,KAAK,EAAK,WACT,OAAO;GACR,KAAK,EAAK,WACT,OAAO;GACR,SACC,OAAO;EACT;EACD,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,SACT,OAAO;EACR,KAAK,EAAK,OACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD"}
1
+ {"version":3,"file":"algorithm-names.js","names":["oid","OIDS","parsed","parseRsaPssParameters","parametersDer","parametersOid"],"sources":["../../../src/internal/crypto/algorithm-names.ts"],"sourcesContent":["/**\n * Human-readable algorithm labels for parsed OIDs.\n *\n * Shared by certificate, revocation, and PKCS parse surfaces so callers can\n * display meaningful algorithm names without memorizing dotted-decimal OIDs.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\n\n/** Convert a hash or message-digest OID into a human-readable name. */\nexport function describeHashAlgorithm(oid: string): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1:\n\t\t\treturn 'SHA-1';\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a signature AlgorithmIdentifier into a human-readable name. */\nexport function describeSignatureAlgorithm(\n\toid: string,\n\tparametersDer: Uint8Array | undefined,\n): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-1';\n\t\tcase OIDS.sha256WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-256';\n\t\tcase OIDS.sha384WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-384';\n\t\tcase OIDS.sha512WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-512';\n\t\tcase OIDS.rsassaPss: {\n\t\t\tconst parsed = parseRsaPssParameters(parametersDer);\n\t\t\treturn parsed.ok ? `RSA-PSS with ${parsed.value.hash}` : 'RSA-PSS';\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA1:\n\t\t\treturn 'ECDSA with SHA-1';\n\t\tcase OIDS.ecdsaWithSHA224:\n\t\t\treturn 'ECDSA with SHA-224';\n\t\tcase OIDS.ecdsaWithSHA256:\n\t\t\treturn 'ECDSA with SHA-256';\n\t\tcase OIDS.ecdsaWithSHA384:\n\t\t\treturn 'ECDSA with SHA-384';\n\t\tcase OIDS.ecdsaWithSHA512:\n\t\t\treturn 'ECDSA with SHA-512';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tcase OIDS.ed448:\n\t\t\treturn 'Ed448';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a SubjectPublicKeyInfo algorithm identifier into a human-readable name. */\nexport function describePublicKeyAlgorithm(oid: string, parametersOid: string | undefined): string {\n\tswitch (oid) {\n\t\tcase OIDS.rsaEncryption:\n\t\t\treturn 'RSA';\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn 'RSA-PSS';\n\t\tcase OIDS.ecPublicKey:\n\t\t\tswitch (parametersOid) {\n\t\t\t\tcase OIDS.prime256v1:\n\t\t\t\t\treturn 'EC P-256';\n\t\t\t\tcase OIDS.secp384r1:\n\t\t\t\t\treturn 'EC P-384';\n\t\t\t\tcase OIDS.secp521r1:\n\t\t\t\t\treturn 'EC P-521';\n\t\t\t\tdefault:\n\t\t\t\t\treturn 'EC';\n\t\t\t}\n\t\tcase OIDS.x25519:\n\t\t\treturn 'X25519';\n\t\tcase OIDS.x448:\n\t\t\treturn 'X448';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tcase OIDS.ed448:\n\t\t\treturn 'Ed448';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,sBAAsB,GAAqB;CAC1D,QAAQA,GAAR;EACC,KAAKC,EAAK,MACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,SACC,OAAO,YAAYD,EAAI;CACzB;AACD;;AAGA,SAAgB,2BACf,GACA,GACS;CACT,QAAQA,GAAR;EACC,KAAKC,EAAK,uBACT,OAAO;EACR,KAAKA,EAAK,yBACT,OAAO;EACR,KAAKA,EAAK,yBACT,OAAO;EACR,KAAKA,EAAK,yBACT,OAAO;EACR,KAAKA,EAAK,WAAW;GACpB,IAAMC,IAASC,EAAsBC,CAAa;GAClD,OAAOF,EAAO,KAAK,gBAAgBA,EAAO,MAAM,SAAS;EAC1D;EACA,KAAKD,EAAK,eACT,OAAO;EACR,KAAKA,EAAK,iBACT,OAAO;EACR,KAAKA,EAAK,iBACT,OAAO;EACR,KAAKA,EAAK,iBACT,OAAO;EACR,KAAKA,EAAK,iBACT,OAAO;EACR,KAAKA,EAAK,SACT,OAAO;EACR,KAAKA,EAAK,OACT,OAAO;EACR,SACC,OAAO,YAAYD,EAAI;CACzB;AACD;;AAGA,SAAgB,2BAA2B,GAAa,GAA2C;CAClG,QAAQA,GAAR;EACC,KAAKC,EAAK,eACT,OAAO;EACR,KAAKA,EAAK,WACT,OAAO;EACR,KAAKA,EAAK,aACT,QAAQI,GAAR;GACC,KAAKJ,EAAK,YACT,OAAO;GACR,KAAKA,EAAK,WACT,OAAO;GACR,KAAKA,EAAK,WACT,OAAO;GACR,SACC,OAAO;EACT;EACD,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,MACT,OAAO;EACR,KAAKA,EAAK,SACT,OAAO;EACR,KAAKA,EAAK,OACT,OAAO;EACR,SACC,OAAO,YAAYD,EAAI;CACzB;AACD"}
@@ -1,5 +1,5 @@
1
1
  import { integer as e, readSequenceChildren as t, sequence as n } from "../asn1/der.js";
2
- //#region src/internal/crypto/ecdsa.ts
2
+ // src/internal/crypto/ecdsa.ts
3
3
  /**
4
4
  * ECDSA signature encoding conversion between ASN.1 DER (r, s INTEGER) and the
5
5
  * fixed-width raw format used by WebCrypto.
@@ -11,7 +11,7 @@ function derEcdsaSignatureToRaw(e, n) {
11
11
  let r = t(e), i = r[0], a = r[1];
12
12
  if (i === void 0 || a === void 0 || r.length !== 2) throw Error("Malformed ECDSA DER signature");
13
13
  if (i.tag !== 2 || a.tag !== 2) throw Error("ECDSA DER signature must contain two INTEGERs");
14
- return concatFixedWidth(trimLeadingZero(i.value), trimLeadingZero(a.value), n);
14
+ return concatFixedWidth(derIntegerMagnitude(i.value), derIntegerMagnitude(a.value), n);
15
15
  }
16
16
  /** Convert a fixed-width raw `r || s` ECDSA signature to DER-encoded SEQUENCE of two INTEGERs. */
17
17
  function rawEcdsaSignatureToDer(t, r) {
@@ -53,13 +53,18 @@ function concatFixedWidth(e, t, n) {
53
53
  let r = new Uint8Array(n * 2);
54
54
  return r.set(e, n - e.length), r.set(t, r.length - t.length), r;
55
55
  }
56
- /** Strip leading zero bytes from a DER INTEGER value, keeping at least one byte. */
57
- function trimLeadingZero(e) {
58
- let t = 0;
59
- for (; t < e.length - 1 && e[t] === 0;) t += 1;
60
- return e.slice(t);
56
+ /** Validate a non-negative DER INTEGER and return its unsigned magnitude. */
57
+ function derIntegerMagnitude(e) {
58
+ let t = e[0];
59
+ if (t === void 0) throw Error("ECDSA DER signature INTEGER must not be empty");
60
+ if (t & 128) throw Error("ECDSA DER signature INTEGER must be non-negative");
61
+ if (t === 0 && e.length > 1) {
62
+ let t = e[1];
63
+ if (t === void 0 || !(t & 128)) throw Error("ECDSA DER signature INTEGER must use minimal encoding");
64
+ return e.slice(1);
65
+ }
66
+ return e;
61
67
  }
62
- //#endregion
63
68
  export { alternateEcdsaSignatureEncoding, concatFixedWidth, derEcdsaSignatureToRaw, ecdsaSignatureToDer, rawEcdsaSignatureToDer };
64
69
 
65
70
  //# sourceMappingURL=ecdsa.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ecdsa.js","names":[],"sources":["../../../src/internal/crypto/ecdsa.ts"],"sourcesContent":["/**\n * ECDSA signature encoding conversion between ASN.1 DER (r, s INTEGER) and the\n * fixed-width raw format used by WebCrypto.\n *\n * @module\n */\n\nimport { integer, readSequenceChildren, sequence } from '#micro509/internal/asn1/der';\n\n/** Convert a DER-encoded ECDSA signature (SEQUENCE of two INTEGERs) to fixed-width raw `r || s`. */\nexport function derEcdsaSignatureToRaw(signature: Uint8Array, partLength: number): Uint8Array {\n\tconst parts = readSequenceChildren(signature);\n\tconst r = parts[0];\n\tconst s = parts[1];\n\tif (r === undefined || s === undefined || parts.length !== 2) {\n\t\tthrow new Error('Malformed ECDSA DER signature');\n\t}\n\tif (r.tag !== 0x02 || s.tag !== 0x02) {\n\t\tthrow new Error('ECDSA DER signature must contain two INTEGERs');\n\t}\n\treturn concatFixedWidth(trimLeadingZero(r.value), trimLeadingZero(s.value), partLength);\n}\n\n/** Convert a fixed-width raw `r || s` ECDSA signature to DER-encoded SEQUENCE of two INTEGERs. */\nexport function rawEcdsaSignatureToDer(signature: Uint8Array, partLength: number): Uint8Array {\n\tif (signature.length !== partLength * 2) {\n\t\tthrow new Error('Unexpected ECDSA raw signature length');\n\t}\n\treturn sequence([integer(signature.slice(0, partLength)), integer(signature.slice(partLength))]);\n}\n\n/**\n * Normalize a WebCrypto ECDSA signature to DER.\n *\n * Spec-compliant WebCrypto always returns fixed-width raw `r || s`\n * (exactly `rawSignatureBytes` long), which needs conversion. Detection is\n * by length, never by sniffing the first byte: a raw signature whose `r`\n * happens to start with `0x30` (1-in-256 per signature) is\n * indistinguishable from DER by tag, and embedding it unconverted produces\n * a certificate/CRL that OpenSSL rejects with a signature failure.\n */\nexport function ecdsaSignatureToDer(signature: Uint8Array, rawSignatureBytes: number): Uint8Array {\n\tif (signature.length === rawSignatureBytes) {\n\t\treturn rawEcdsaSignatureToDer(signature, rawSignatureBytes / 2);\n\t}\n\treturn signature;\n}\n\n/**\n * Try the opposite ECDSA encoding: DER→raw or raw→DER.\n *\n * Returns `undefined` if conversion fails, letting callers retry verification\n * with the alternate encoding.\n */\nexport function alternateEcdsaSignatureEncoding(\n\tsignature: Uint8Array,\n\tpartLength: number,\n): Uint8Array | undefined {\n\t// Try DER→raw first if it looks like DER (starts with SEQUENCE tag)\n\tif (signature[0] === 0x30) {\n\t\ttry {\n\t\t\treturn derEcdsaSignatureToRaw(signature, partLength);\n\t\t} catch {\n\t\t\t// Fall through to try raw→DER\n\t\t}\n\t}\n\t// Try raw→DER\n\ttry {\n\t\treturn rawEcdsaSignatureToDer(signature, partLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Left-pad and concatenate `r` and `s` into a fixed-width `partLength * 2` byte buffer. */\nexport function concatFixedWidth(\n\tleft: Uint8Array,\n\tright: Uint8Array,\n\tpartLength: number,\n): Uint8Array {\n\tif (left.length > partLength || right.length > partLength) {\n\t\tthrow new Error('ECDSA signature integer too large');\n\t}\n\tconst out = new Uint8Array(partLength * 2);\n\tout.set(left, partLength - left.length);\n\tout.set(right, out.length - right.length);\n\treturn out;\n}\n\n/** Strip leading zero bytes from a DER INTEGER value, keeping at least one byte. */\nfunction trimLeadingZero(bytes: Uint8Array):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EAAM,MAAM,GACjC;AACR;;AAGA,SAAS,gBAAgB,GAA+B;CACvD,IAAI,IAAQ;CACZ,OAAO,IAAQ,EAAM,SAAS,KAAK,EAAM,OAAW,IACnD,KAAS;CAEV,OAAO,EAAM,MAAM,CAAK;AACzB"}
1
+ {"version":3,"file":"ecdsa.js","names":["parts","readSequenceChildren","signature","r","s","partLength","sequence","integer","rawSignatureBytes","left","right","out","first","bytes","second"],"sources":["../../../src/internal/crypto/ecdsa.ts"],"sourcesContent":["/**\n * ECDSA signature encoding conversion between ASN.1 DER (r, s INTEGER) and the\n * fixed-width raw format used by WebCrypto.\n *\n * @module\n */\n\nimport { integer, readSequenceChildren, sequence } from '#micro509/internal/asn1/der';\n\n/** Convert a DER-encoded ECDSA signature (SEQUENCE of two INTEGERs) to fixed-width raw `r || s`. */\nexport function derEcdsaSignatureToRaw(signature: Uint8Array, partLength: number): Uint8Array {\n\tconst parts = readSequenceChildren(signature);\n\tconst r = parts[0];\n\tconst s = parts[1];\n\tif (r === undefined || s === undefined || parts.length !== 2) {\n\t\tthrow new Error('Malformed ECDSA DER signature');\n\t}\n\tif (r.tag !== 0x02 || s.tag !== 0x02) {\n\t\tthrow new Error('ECDSA DER signature must contain two INTEGERs');\n\t}\n\treturn concatFixedWidth(derIntegerMagnitude(r.value), derIntegerMagnitude(s.value), partLength);\n}\n\n/** Convert a fixed-width raw `r || s` ECDSA signature to DER-encoded SEQUENCE of two INTEGERs. */\nexport function rawEcdsaSignatureToDer(signature: Uint8Array, partLength: number): Uint8Array {\n\tif (signature.length !== partLength * 2) {\n\t\tthrow new Error('Unexpected ECDSA raw signature length');\n\t}\n\treturn sequence([integer(signature.slice(0, partLength)), integer(signature.slice(partLength))]);\n}\n\n/**\n * Normalize a WebCrypto ECDSA signature to DER.\n *\n * Spec-compliant WebCrypto always returns fixed-width raw `r || s`\n * (exactly `rawSignatureBytes` long), which needs conversion. Detection is\n * by length, never by sniffing the first byte: a raw signature whose `r`\n * happens to start with `0x30` (1-in-256 per signature) is\n * indistinguishable from DER by tag, and embedding it unconverted produces\n * a certificate/CRL that OpenSSL rejects with a signature failure.\n */\nexport function ecdsaSignatureToDer(signature: Uint8Array, rawSignatureBytes: number): Uint8Array {\n\tif (signature.length === rawSignatureBytes) {\n\t\treturn rawEcdsaSignatureToDer(signature, rawSignatureBytes / 2);\n\t}\n\treturn signature;\n}\n\n/**\n * Try the opposite ECDSA encoding: DER→raw or raw→DER.\n *\n * Returns `undefined` if conversion fails, letting callers retry verification\n * with the alternate encoding.\n */\nexport function alternateEcdsaSignatureEncoding(\n\tsignature: Uint8Array,\n\tpartLength: number,\n): Uint8Array | undefined {\n\t// Try DER→raw first if it looks like DER (starts with SEQUENCE tag)\n\tif (signature[0] === 0x30) {\n\t\ttry {\n\t\t\treturn derEcdsaSignatureToRaw(signature, partLength);\n\t\t} catch {\n\t\t\t// Fall through to try raw→DER\n\t\t}\n\t}\n\t// Try raw→DER\n\ttry {\n\t\treturn rawEcdsaSignatureToDer(signature, partLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Left-pad and concatenate `r` and `s` into a fixed-width `partLength * 2` byte buffer. */\nexport function concatFixedWidth(\n\tleft: Uint8Array,\n\tright: Uint8Array,\n\tpartLength: number,\n): Uint8Array {\n\tif (left.length > partLength || right.length > partLength) {\n\t\tthrow new Error('ECDSA signature integer too large');\n\t}\n\tconst out = new Uint8Array(partLength * 2);\n\tout.set(left, partLength - left.length);\n\tout.set(right, out.length - right.length);\n\treturn out;\n}\n\n/** Validate a non-negative DER INTEGER and return its unsigned magnitude. */\nfunction derIntegerMagnitude(bytes: Uint8Array): Uint8Array {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error('ECDSA DER signature INTEGER must not be empty');\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error('ECDSA DER signature INTEGER must be non-negative');\n\t}\n\tif (first === 0 && bytes.length > 1) {\n\t\tconst second = bytes[1];\n\t\tif (second === undefined || (second &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,IAAaI,EAAK,MAAM,GACtCE,EAAI,IAAID,GAAOC,EAAI,SAASD,EAAM,MAAM,GACjCC;AACR;;AAGA,SAAS,oBAAoB,GAA+B;CAC3D,IAAMC,IAAQC,EAAM;CACpB,IAAID,MAAU,KAAA,GACb,MAAU,MAAM,+CAA+C;CAEhE,IAAKA,IAAQ,KACZ,MAAU,MAAM,kDAAkD;CAEnE,IAAIA,MAAU,KAAKC,EAAM,SAAS,GAAG;EACpC,IAAMC,IAASD,EAAM;EACrB,IAAIC,MAAW,KAAA,KAAA,EAAcA,IAAS,MACrC,MAAU,MAAM,uDAAuD;EAExE,OAAOD,EAAM,MAAM,CAAC;CACrB;CACA,OAAOA;AACR"}
@@ -1,4 +1,4 @@
1
- //#region src/internal/crypto/hash.ts
1
+ // src/internal/crypto/hash.ts
2
2
  /**
3
3
  * Synchronous digest implementations for MD5 and SHA-1, used where WebCrypto's
4
4
  * async API is impractical (e.g. `EVP_BytesToKey` key derivation, PKCS#12 MAC).
@@ -219,7 +219,6 @@ function sha1(e) {
219
219
  let l = /* @__PURE__ */ new Uint8Array(20), u = new DataView(l.buffer, l.byteOffset, l.byteLength);
220
220
  return u.setUint32(0, n, !1), u.setUint32(4, r, !1), u.setUint32(8, i, !1), u.setUint32(12, a, !1), u.setUint32(16, o, !1), l;
221
221
  }
222
- //#endregion
223
222
  export { md5, sha1 };
224
223
 
225
224
  //# sourceMappingURL=hash.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hash.js","names":[],"sources":["../../../src/internal/crypto/hash.ts"],"sourcesContent":["/**\n * Synchronous digest implementations for MD5 and SHA-1, used where WebCrypto's\n * async API is impractical (e.g. `EVP_BytesToKey` key derivation, PKCS#12 MAC).\n *\n * @module\n */\n\n// Shared Merkle–Damgård primitives\n\n/** Unsigned 32-bit left-rotate. */\nfunction rotl(x: number, n: number): number {\n\treturn ((x << n) | (x >>> (32 - n))) >>> 0;\n}\n\n/**\n * Merkle–Damgård padding: append 0x80, zero-pad to 56 mod 64,\n * append original bit-length as 64-bit integer.\n */\nfunction mdPad(data: Uint8Array, littleEndian: boolean): Uint8Array {\n\tconst bitLen = BigInt(data.length) * 8n;\n\tconst padded = new Uint8Array(Math.ceil((data.length + 1 + 8) / 64) * 64);\n\tpadded.set(data);\n\tpadded[data.length] = 0x80;\n\tconst view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\tview.setBigUint64(padded.length - 8, bitLen, littleEndian);\n\treturn padded;\n}\n\n/** Bounds-checked read from a readonly number table. */\nfunction tbl(arr: readonly number[], i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`table index ${i}`);\n\treturn v;\n}\n\n/** Bounds-checked read from a Uint32Array. */\nfunction w32(arr: Uint32Array, i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`word index ${i}`);\n\treturn v;\n}\n\n// MD5 (RFC 1321)\n\n/** Per-round left-rotate amounts for MD5 (RFC 1321 §3.4). */\nconst MD5_S = /* dprint-ignore */ [\n\t7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14,\n\t20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6,\n\t10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n] as const satisfies readonly number[];\n\n/** Pre-computed sine-derived constants for MD5 (RFC 1321 §3.4). */\nconst MD5_K = /* dprint-ignore */ [\n\t0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n\t0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n\t0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n\t0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n\t0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n\t0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n\t0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n\t0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,\n] as const satisfies readonly number[];\n\n/** Compute a 16-byte MD5 digest (RFC 1321). Used by `EVP_BytesToKey` key derivation. */\nexport function md5(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, true);\n\n\tlet [a0, b0, c0, d0] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];\n\n\tconst M = new Uint32Array(16);\n\n\tfor (let offset = 0; offset < padded.length; offset += 64) {\n\t\tconst view = new DataView(padded.buffer, padded.byteOffset + offset, 64);\n\t\tfor (let j = 0; j < 16; j++) {\n\t\t\tM[j] = view.getUint32(j * 4, true);\n\t\t}\n\n\t\tlet [A, B, C, D] = [a0, b0, c0, d0];\n\n\t\tfor (let i = 0; i < 64; i++) {\n\t\t\tlet F: number;\n\t\t\tlet g: number;\n\n\t\t\tif (i < 16) {\n\t\t\t\tF = ((B & C) | (~B & D)) >>> 0;\n\t\t\t\tg = i;\n\t\t\t} else if (i < 32) {\n\t\t\t\tF = ((D & B) | (~D & C)) >>> 0;\n\t\t\t\tg = (5 * i + 1) & 15;\n\t\t\t} else if (i < 48) {\n\t\t\t\tF = (B ^ C ^ D) >>> 0;\n\t\t\t\tg = (3 * i + 5) & 15;\n\t\t\t} else {\n\t\t\t\tF = (C ^ (B | ~D)) >>> 0;\n\t\t\t\tg = (7 * i) & 15;\n\t\t\t}\n\n\t\t\tF = (F + A + tbl(MD5_K, i) + w32(M, g)) >>> 0;\n\t\t\tconst oldD = D;\n\t\t\tD = C;\n\t\t\tC = B;\n\t\t\tB = (B + rotl(F, tbl(MD5_S, i))) >>> 0;\n\t\t\tA = oldD;\n\t\t}\n\n\t\ta0 = (a0 + A) >>> 0;\n\t\tb0 = (b0 + B) >>> 0;\n\t\tc0 = (c0 + C) >>> 0;\n\t\td0 = (d0 + D) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(16);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, a0, true);\n\tdv.setUint32(4, b0, true);\n\tdv.setUint32(8, c0, true);\n\tdv.setUint32(12, d0, true);\n\treturn out;\n}\n\n// SHA-1 (RFC 3174)\n\n/** Compute a 20-byte SHA-1 digest (RFC 3174). Used by PKCS#12 MAC verification. */\nexport function sha1(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, false);\n\n\tlet [h0, h1, h2, h3, h4] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n\tconst W = new Uint32Array(80);\n\tconst pv = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\n\tfor (let off = 0; off < padded.length; off += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tW[i] = pv.getUint32(off + i * 4, false);\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) {\n\t\t\tW[i] = rotl(w32(W, i - 3) ^ w32(W, i - 8) ^ w32(W, i - 14) ^ w32(W, i - 16), 1);\n\t\t}\n\n\t\tlet [a, b, c, d, e] = [h0, h1, h2, h3, h4];\n\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f: number;\n\t\t\tlet k: number;\n\n\t\t\tif (i <= 19) {\n\t\t\t\tf = ((b & c) | (~b & d)) >>> 0;\n\t\t\t\tk = 0x5a827999;\n\t\t\t} else if (i <= 39) {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0x6ed9eba1;\n\t\t\t} else if (i <= 59) {\n\t\t\t\tf = ((b & c) | (b & d) | (c & d)) >>> 0;\n\t\t\t\tk = 0x8f1bbcdc;\n\t\t\t} else {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0xca62c1d6;\n\t\t\t}\n\n\t\t\tconst temp = (rotl(a, 5) + f + e + k + w32(W, i)) >>> 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\n\t\th0 = (h0 + a) >>> 0;\n\t\th1 = (h1 + b) >>> 0;\n\t\th2 = (h2 + c) >>> 0;\n\t\th3 = (h3 + d) >>> 0;\n\t\th4 = (h4 + e) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(20);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, h0, false);\n\tdv.setUint32(4, h1, false);\n\tdv.setUint32(8, h2, false);\n\tdv.setUint32(12, h3, false);\n\tdv.setUint32(16, h4, false);\n\treturn out;\n}\n"],"mappings":";;;;;;;;AAUA,SAAS,KAAK,GAAW,GAAmB;CAC3C,QAAS,KAAK,IAAM,MAAO,KAAK,OAAS;AAC1C;;;;;AAMA,SAAS,MAAM,GAAkB,GAAmC;CACnE,IAAM,IAAS,OAAO,EAAK,MAAM,IAAI,IAC/B,IAAS,IAAI,WAAW,KAAK,MAAM,EAAK,SAAS,IAAI,KAAK,EAAE,IAAI,EAAE;CAKxE,OAJA,EAAO,IAAI,CAAI,GACf,EAAO,EAAK,UAAU,KAEtB,IADiB,SAAS,EAAO,QAAQ,EAAO,YAAY,EAAO,UAChE,CAAC,CAAC,aAAa,EAAO,SAAS,GAAG,GAAQ,CAAY,GAClD;AACR;;AAGA,SAAS,IAAI,GAAwB,GAAmB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IAAM,IAAK,MAAO;CACnB;CAEA,IAAM,oBAAM,IAAI,WAAW,EAAE,GACvB,IAAK,IAAI,SAAS,EAAI,QAAQ,EAAI,YAAY,EAAI,UAAU;CAMlE,OALA,EAAG,UAAU,GAAG,GAAI,EAAK,GACzB,EAAG,UAAU,GAAG,GAAI,EAAK,GACzB,EAAG,UAAU,GAAG,GAAI,EAAK,GACzB,EAAG,UAAU,IAAI,GAAI,EAAK,GAC1B,EAAG,UAAU,IAAI,GAAI,EAAK,GACnB;AACR"}
1
+ {"version":3,"file":"hash.js","names":["x","n","bitLen","data","padded","littleEndian","v","arr","i","MD5_S","MD5_K","a0","b0","c0","d0","M","offset","view","j","A","B","C","D","F","g","oldD","out","dv","h0","h1","h2","h3","h4","W","pv","off","a","b","c","e","f","k","temp"],"sources":["../../../src/internal/crypto/hash.ts"],"sourcesContent":["/**\n * Synchronous digest implementations for MD5 and SHA-1, used where WebCrypto's\n * async API is impractical (e.g. `EVP_BytesToKey` key derivation, PKCS#12 MAC).\n *\n * @module\n */\n\n// Shared Merkle–Damgård primitives\n\n/** Unsigned 32-bit left-rotate. */\nfunction rotl(x: number, n: number): number {\n\treturn ((x << n) | (x >>> (32 - n))) >>> 0;\n}\n\n/**\n * Merkle–Damgård padding: append 0x80, zero-pad to 56 mod 64,\n * append original bit-length as 64-bit integer.\n */\nfunction mdPad(data: Uint8Array, littleEndian: boolean): Uint8Array {\n\tconst bitLen = BigInt(data.length) * 8n;\n\tconst padded = new Uint8Array(Math.ceil((data.length + 1 + 8) / 64) * 64);\n\tpadded.set(data);\n\tpadded[data.length] = 0x80;\n\tconst view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\tview.setBigUint64(padded.length - 8, bitLen, littleEndian);\n\treturn padded;\n}\n\n/** Bounds-checked read from a readonly number table. */\nfunction tbl(arr: readonly number[], i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`table index ${i}`);\n\treturn v;\n}\n\n/** Bounds-checked read from a Uint32Array. */\nfunction w32(arr: Uint32Array, i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`word index ${i}`);\n\treturn v;\n}\n\n// MD5 (RFC 1321)\n\n/** Per-round left-rotate amounts for MD5 (RFC 1321 §3.4). */\nconst MD5_S = /* dprint-ignore */ [\n\t7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14,\n\t20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6,\n\t10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n] as const satisfies readonly number[];\n\n/** Pre-computed sine-derived constants for MD5 (RFC 1321 §3.4). */\nconst MD5_K = /* dprint-ignore */ [\n\t0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n\t0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n\t0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n\t0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n\t0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n\t0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n\t0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n\t0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,\n] as const satisfies readonly number[];\n\n/** Compute a 16-byte MD5 digest (RFC 1321). Used by `EVP_BytesToKey` key derivation. */\nexport function md5(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, true);\n\n\tlet [a0, b0, c0, d0] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];\n\n\tconst M = new Uint32Array(16);\n\n\tfor (let offset = 0; offset < padded.length; offset += 64) {\n\t\tconst view = new DataView(padded.buffer, padded.byteOffset + offset, 64);\n\t\tfor (let j = 0; j < 16; j++) {\n\t\t\tM[j] = view.getUint32(j * 4, true);\n\t\t}\n\n\t\tlet [A, B, C, D] = [a0, b0, c0, d0];\n\n\t\tfor (let i = 0; i < 64; i++) {\n\t\t\tlet F: number;\n\t\t\tlet g: number;\n\n\t\t\tif (i < 16) {\n\t\t\t\tF = ((B & C) | (~B & D)) >>> 0;\n\t\t\t\tg = i;\n\t\t\t} else if (i < 32) {\n\t\t\t\tF = ((D & B) | (~D & C)) >>> 0;\n\t\t\t\tg = (5 * i + 1) & 15;\n\t\t\t} else if (i < 48) {\n\t\t\t\tF = (B ^ C ^ D) >>> 0;\n\t\t\t\tg = (3 * i + 5) & 15;\n\t\t\t} else {\n\t\t\t\tF = (C ^ (B | ~D)) >>> 0;\n\t\t\t\tg = (7 * i) & 15;\n\t\t\t}\n\n\t\t\tF = (F + A + tbl(MD5_K, i) + w32(M, g)) >>> 0;\n\t\t\tconst oldD = D;\n\t\t\tD = C;\n\t\t\tC = B;\n\t\t\tB = (B + rotl(F, tbl(MD5_S, i))) >>> 0;\n\t\t\tA = oldD;\n\t\t}\n\n\t\ta0 = (a0 + A) >>> 0;\n\t\tb0 = (b0 + B) >>> 0;\n\t\tc0 = (c0 + C) >>> 0;\n\t\td0 = (d0 + D) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(16);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, a0, true);\n\tdv.setUint32(4, b0, true);\n\tdv.setUint32(8, c0, true);\n\tdv.setUint32(12, d0, true);\n\treturn out;\n}\n\n// SHA-1 (RFC 3174)\n\n/** Compute a 20-byte SHA-1 digest (RFC 3174). Used by PKCS#12 MAC verification. */\nexport function sha1(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, false);\n\n\tlet [h0, h1, h2, h3, h4] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n\tconst W = new Uint32Array(80);\n\tconst pv = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\n\tfor (let off = 0; off < padded.length; off += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tW[i] = pv.getUint32(off + i * 4, false);\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) {\n\t\t\tW[i] = rotl(w32(W, i - 3) ^ w32(W, i - 8) ^ w32(W, i - 14) ^ w32(W, i - 16), 1);\n\t\t}\n\n\t\tlet [a, b, c, d, e] = [h0, h1, h2, h3, h4];\n\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f: number;\n\t\t\tlet k: number;\n\n\t\t\tif (i <= 19) {\n\t\t\t\tf = ((b & c) | (~b & d)) >>> 0;\n\t\t\t\tk = 0x5a827999;\n\t\t\t} else if (i <= 39) {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0x6ed9eba1;\n\t\t\t} else if (i <= 59) {\n\t\t\t\tf = ((b & c) | (b & d) | (c & d)) >>> 0;\n\t\t\t\tk = 0x8f1bbcdc;\n\t\t\t} else {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0xca62c1d6;\n\t\t\t}\n\n\t\t\tconst temp = (rotl(a, 5) + f + e + k + w32(W, i)) >>> 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\n\t\th0 = (h0 + a) >>> 0;\n\t\th1 = (h1 + b) >>> 0;\n\t\th2 = (h2 + c) >>> 0;\n\t\th3 = (h3 + d) >>> 0;\n\t\th4 = (h4 + e) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(20);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, h0, false);\n\tdv.setUint32(4, h1, false);\n\tdv.setUint32(8, h2, false);\n\tdv.setUint32(12, h3, false);\n\tdv.setUint32(16, h4, false);\n\treturn out;\n}\n"],"mappings":";;;;;;;;AAUA,SAAS,KAAK,GAAW,GAAmB;CAC3C,QAASA,KAAKC,IAAMD,MAAO,KAAKC,OAAS;AAC1C;;;;;AAMA,SAAS,MAAM,GAAkB,GAAmC;CACnE,IAAMC,IAAS,OAAOC,EAAK,MAAM,IAAI,IAC/BC,IAAS,IAAI,WAAW,KAAK,MAAMD,EAAK,SAAS,IAAI,KAAK,EAAE,IAAI,EAAE;CAKxE,OAJAC,EAAO,IAAID,CAAI,GACf,EAAOA,EAAK,UAAU,KAEtB,IADiB,SAASC,EAAO,QAAQA,EAAO,YAAYA,EAAO,UAChE,CAAC,CAAC,aAAaA,EAAO,SAAS,GAAGF,GAAQG,CAAY,GAClDD;AACR;;AAGA,SAAS,IAAI,GAAwB,GAAmB;CACvD,IAAME,IAAIC,EAAIC;CACd,IAAIF,MAAM,KAAA,GAAW,MAAU,WAAW,eAAeE,GAAG;CAC5D,OAAOF;AACR;;AAGA,SAAS,IAAI,GAAkB,GAAmB;CACjD,IAAMA,IAAIC,EAAIC;CACd,IAAIF,MAAM,KAAA,GAAW,MAAU,WAAW,cAAcE,GAAG;CAC3D,OAAOF;AACR;;AAKA,MAAMG,IAA4B;CACjC;CAAG;CAAI;CAAI;CAAI;CAAG;CAAI;CAAI;CAAI;CAAG;CAAI;CAAI;CAAI;CAAG;CAAI;CAAI;CAAI;CAAG;CAAG;CAAI;CAAI;CAAG;CAAG;CAAI;CAAI;CAAG;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G,UAAU,GAAGE,GAAI,EAAK,GACzBF,EAAG,UAAU,GAAGG,GAAI,EAAK,GACzBH,EAAG,UAAU,IAAII,GAAI,EAAK,GAC1BJ,EAAG,UAAU,IAAIK,GAAI,EAAK,GACnBN;AACR"}
@@ -1,13 +1,23 @@
1
- //#region src/internal/crypto/pbes2.d.ts
1
+ /** Caller-supplied bound on password-based KDF work. */
2
+ export interface KdfLimitOptions {
3
+ /**
4
+ * Maximum KDF iteration count accepted from the input. Higher counts fail
5
+ * before any derivation runs. Defaults to `2_000_000` for PBKDF2 and
6
+ * `100_000` for the PKCS#12 KDF, which costs more per round. In a PFX the
7
+ * PBES2-encrypted entries share one budget of this size and the MAC has a
8
+ * separate budget of this size.
9
+ */
10
+ readonly maxKdfIterations?: number;
11
+ }
2
12
  /** AES-CBC key sizes supported by this PBES2 implementation. */
3
- type Pbes2EncryptionScheme = "AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC";
13
+ export type Pbes2EncryptionScheme = "AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC";
4
14
  /** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */
5
- type Pbes2Prf = "HMAC-SHA-1" | "HMAC-SHA-256";
15
+ export type Pbes2Prf = "HMAC-SHA-1" | "HMAC-SHA-256";
6
16
  /** Input for `encryptPbes2`. */
7
- interface Pbes2EncryptionOptions {
17
+ export interface Pbes2EncryptionOptions {
8
18
  /** Password fed to PBKDF2 for key derivation. */
9
19
  readonly password: string;
10
- /** PBKDF2 iteration count. Default: `100_000`. */
20
+ /** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */
11
21
  readonly iterations?: number;
12
22
  /** PBKDF2 salt. Default: 16 cryptographically random bytes. */
13
23
  readonly salt?: Uint8Array;
@@ -19,8 +29,8 @@ interface Pbes2EncryptionOptions {
19
29
  readonly prf?: Pbes2Prf;
20
30
  }
21
31
  /** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */
22
- interface Pbes2Parameters {
23
- /** PBKDF2 iteration count. */
32
+ export interface Pbes2Parameters {
33
+ /** PBKDF2 iteration count, an integer from 1 to 4294967295. */
24
34
  readonly iterations: number;
25
35
  /** PBKDF2 salt bytes. */
26
36
  readonly salt: Uint8Array;
@@ -31,8 +41,11 @@ interface Pbes2Parameters {
31
41
  /** PBKDF2 pseudo-random function. */
32
42
  readonly prf: Pbes2Prf;
33
43
  }
34
- /** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */
35
- declare function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters;
36
- //#endregion
37
- export { Pbes2EncryptionOptions, Pbes2EncryptionScheme, Pbes2Parameters, Pbes2Prf, parsePbes2AlgorithmIdentifier };
44
+ /**
45
+ * Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}.
46
+ *
47
+ * @throws if the encoding is malformed, names an unsupported KDF, PRF or cipher, or carries an
48
+ * iteration count outside 1 to 4294967295.
49
+ */
50
+ export declare function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters;
38
51
  //# sourceMappingURL=pbes2.d.ts.map
@@ -2,7 +2,7 @@ import { integerFromNumber as e, nullValue as t, objectIdentifier as n, octetStr
2
2
  import { decodeIntegerNumber as o, decodeObjectIdentifier as s, toArrayBuffer as c } from "../asn1/asn1.js";
3
3
  import { OIDS as l } from "../asn1/oids2.js";
4
4
  import { getCrypto as u } from "./webcrypto.js";
5
- //#region src/internal/crypto/pbes2.ts
5
+ // src/internal/crypto/pbes2.ts
6
6
  /**
7
7
  * PBES2 password-based encryption and decryption (RFC 8018).
8
8
  *
@@ -28,11 +28,45 @@ function wrongPasswordError(e) {
28
28
  function isWrongPasswordError(e) {
29
29
  return e instanceof Error && d in e;
30
30
  }
31
+ /** Upper bound on PBKDF2 iteration counts accepted from untrusted input. */
32
+ const f = 2e6, p = 1e5, m = Symbol("micro509.KdfIterationLimitError");
33
+ /** Thrown before key derivation when an encoded iteration count exceeds the caller's limit. */
34
+ function kdfIterationLimitError(e, t) {
35
+ return Object.assign(/* @__PURE__ */ Error(`KDF iteration count ${e} exceeds the remaining budget of ${t}`), {
36
+ name: "KdfIterationLimitError",
37
+ [m]: !0
38
+ });
39
+ }
40
+ /** Type guard: was derivation refused because the iteration count exceeds the limit? */
41
+ function isKdfIterationLimitError(e) {
42
+ return e instanceof Error && m in e;
43
+ }
44
+ /** Opens a budget from the caller's limit. Throws when that limit is not a positive integer. */
45
+ function createKdfBudget(e, t = f) {
46
+ let n = e?.maxKdfIterations ?? t;
47
+ if (!Number.isSafeInteger(n) || n < 1) throw RangeError(`Invalid maxKdfIterations: must be an integer >= 1, got ${n}`);
48
+ return { remaining: n };
49
+ }
50
+ /** Charges iterations against the budget, throwing before any derivation runs. */
51
+ function chargeKdfBudget(e, t) {
52
+ if (t > e.remaining) throw kdfIterationLimitError(t, e.remaining);
53
+ e.remaining -= t;
54
+ }
55
+ const h = 4294967295;
56
+ async function derivePbkdf2Bytes(e, t, n, r, i) {
57
+ assertPbkdf2IterationCount(n);
58
+ let a = await u().subtle.importKey("raw", c(e), "PBKDF2", !1, ["deriveBits"]);
59
+ return new Uint8Array(await u().subtle.deriveBits({
60
+ name: "PBKDF2",
61
+ salt: c(t),
62
+ iterations: n,
63
+ hash: r
64
+ }, a, i * 8));
65
+ }
31
66
  /** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */
32
67
  async function encryptPbes2(e, t) {
33
68
  let n = t.iterations ?? 1e5, r = t.salt ?? u().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), i = t.iv ?? u().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), a = t.cipher ?? "AES-256-CBC", o = t.prf ?? "HMAC-SHA-256";
34
- if (!Number.isInteger(n) || n < 1) throw RangeError(`Invalid iterations: must be an integer >= 1, got ${n}`);
35
- if (!(r instanceof Uint8Array) || r.length < 8) throw TypeError(`Invalid salt: must be Uint8Array with length >= 8, got length ${r.length}`);
69
+ if (assertPbkdf2IterationCount(n), !(r instanceof Uint8Array) || r.length < 8) throw TypeError(`Invalid salt: must be Uint8Array with length >= 8, got length ${r.length}`);
36
70
  if (!(i instanceof Uint8Array) || i.length !== 16) throw TypeError(`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${i.length}`);
37
71
  let s = await deriveAesKey(t.password, r, n, a, o, ["encrypt"]), l = new Uint8Array(await u().subtle.encrypt({
38
72
  name: "AES-CBC",
@@ -56,20 +90,31 @@ async function encryptPbes2(e, t) {
56
90
  }
57
91
  };
58
92
  }
59
- /** Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password. Throws on wrong password. */
60
- async function decryptPbes2(e, t, n) {
61
- let r = parsePbes2AlgorithmIdentifier(e), i = await deriveAesKey(n, r.salt, r.iterations, r.cipher, r.prf, ["decrypt"]);
93
+ /**
94
+ * Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password.
95
+ * Throws on wrong password, and before derivation when the encoded iteration
96
+ * count exceeds what `budget` still allows.
97
+ */
98
+ async function decryptPbes2(e, t, n, r = createKdfBudget(void 0)) {
99
+ let i = parsePbes2AlgorithmIdentifier(e);
100
+ chargeKdfBudget(r, i.iterations);
101
+ let a = await deriveAesKey(n, i.salt, i.iterations, i.cipher, i.prf, ["decrypt"]);
62
102
  try {
63
103
  return new Uint8Array(await u().subtle.decrypt({
64
104
  name: "AES-CBC",
65
- iv: c(r.iv)
66
- }, i, c(t)));
105
+ iv: c(i.iv)
106
+ }, a, c(t)));
67
107
  } catch {
68
108
  throw wrongPasswordError("Invalid password or encrypted content");
69
109
  }
70
110
  }
71
- /** DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters. */
111
+ /**
112
+ * DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters.
113
+ *
114
+ * @throws {RangeError} if `parameters.iterations` is not an integer from 1 to 4294967295.
115
+ */
72
116
  function encodePbes2AlgorithmIdentifier(i) {
117
+ assertPbkdf2IterationCount(i.iterations);
73
118
  let o = resolveEncryptionProfile(i.cipher), s = resolvePrfProfile(i.prf), c = [
74
119
  r(i.salt),
75
120
  e(i.iterations),
@@ -78,27 +123,36 @@ function encodePbes2AlgorithmIdentifier(i) {
78
123
  ];
79
124
  return a([n(l.pbes2), a([a([n(l.pbkdf2), a(c)]), a([n(o.oid), r(i.iv)])])]);
80
125
  }
81
- /** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */
126
+ /**
127
+ * Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}.
128
+ *
129
+ * @throws if the encoding is malformed, names an unsupported KDF, PRF or cipher, or carries an
130
+ * iteration count outside 1 to 4294967295.
131
+ */
82
132
  function parsePbes2AlgorithmIdentifier(e) {
83
133
  let { paramsDer: t, kdf: n, scheme: r } = parsePbes2OuterFields(e), { pbkdf2Der: a, pbkdf2Params: c } = parsePbes2KdfFields(t, n), l = c[0], u = c[1];
84
- if (l === void 0 || u === void 0 || l.tag !== 4) throw Error("Malformed PBKDF2 params");
85
- let d = c[2], f = d?.tag === 2, p = f ? c[3] : d, m = i(t.slice(r.start - r.headerLength, r.end)), h = m[0], g = m[1];
86
- if (h === void 0 || g === void 0 || g.tag !== 4) throw Error("Malformed encryption scheme");
87
- let _ = encryptionSchemeFromOid(s(h.value));
88
- if (_ === void 0) throw Error("Unsupported content encryption scheme");
134
+ if (l === void 0 || u === void 0 || l.tag !== 4 || u.tag !== 2) throw Error("Malformed PBKDF2 params");
135
+ let d = c[2], f = d?.tag === 2, p = f ? c[3] : d, m = t.slice(r.start - r.headerLength, r.end), g = i(m), _ = g[0], v = g[1];
136
+ if (_ === void 0 || v === void 0 || v.tag !== 4) throw Error("Malformed encryption scheme");
137
+ let y = encryptionSchemeFromOid(s(_.value));
138
+ if (y === void 0) throw Error("Unsupported content encryption scheme");
89
139
  if (d !== void 0 && !f && d.tag !== 48) throw Error("Malformed PBKDF2 params");
90
- if (f && o(d.value) !== _.keyLengthBytes) throw Error("Unsupported PBKDF2 key length");
91
- let v = parsePbkdf2Prf(a, p), y = o(u.value), b = new Uint8Array(l.value), x = new Uint8Array(g.value);
92
- if (y < 1) throw Error(`Invalid PBES2 iterations: must be >= 1, got ${y}`);
93
- if (x.length !== 16) throw Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${x.length}`);
140
+ if (f && o(d.value) !== y.keyLengthBytes) throw Error("Unsupported PBKDF2 key length");
141
+ let b = parsePbkdf2Prf(a, p), x = o(u.value), S = new Uint8Array(l.value), C = new Uint8Array(v.value);
142
+ if (x < 1) throw Error(`Invalid PBES2 iterations: must be >= 1, got ${x}`);
143
+ if (x > 4294967295) throw Error(`Invalid PBES2 iterations: must be <= ${h}, got ${x}`);
144
+ if (C.length !== 16) throw Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${C.length}`);
94
145
  return {
95
- salt: b,
96
- iterations: y,
97
- iv: x,
98
- cipher: _.name,
99
- prf: v
146
+ salt: S,
147
+ iterations: x,
148
+ iv: C,
149
+ cipher: y.name,
150
+ prf: b
100
151
  };
101
152
  }
153
+ function assertPbkdf2IterationCount(e) {
154
+ if (!Number.isInteger(e) || e < 1 || e > 4294967295) throw RangeError(`Invalid iterations: must be an integer from 1 to ${h}, got ${e}`);
155
+ }
102
156
  /** Extracts the KDF and encryption-scheme fields from a PBES2 AlgorithmIdentifier. */
103
157
  function parsePbes2OuterFields(e) {
104
158
  let t = i(e), n = t[0], r = t[1];
@@ -195,7 +249,6 @@ function resolvePrfProfile(e) {
195
249
  default: throw Error(`Unhandled Pbes2Prf: ${String(e)}`);
196
250
  }
197
251
  }
198
- //#endregion
199
- export { decryptPbes2, encodePbes2AlgorithmIdentifier, encryptPbes2, isWrongPasswordError, parsePbes2AlgorithmIdentifier, wrongPasswordError };
252
+ export { f as DEFAULT_MAX_KDF_ITERATIONS, p as DEFAULT_MAX_PKCS12_MAC_ITERATIONS, h as WEBCRYPTO_MAX_PBKDF2_ITERATIONS, chargeKdfBudget, createKdfBudget, decryptPbes2, derivePbkdf2Bytes, encodePbes2AlgorithmIdentifier, encryptPbes2, isKdfIterationLimitError, isWrongPasswordError, kdfIterationLimitError, parsePbes2AlgorithmIdentifier, wrongPasswordError };
200
253
 
201
254
  //# sourceMappingURL=pbes2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pbes2.js","names":["_exhaustive"],"sources":["../../../src/internal/crypto/pbes2.ts"],"sourcesContent":["/**\n * PBES2 password-based encryption and decryption (RFC 8018).\n *\n * Supports AES-CBC-128/192/256 with PBKDF2 using HMAC-SHA-1 or HMAC-SHA-256.\n * Used internally by encrypted PKCS#8 and PFX flows.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\n\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/**\n * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in\n * practice means the supplied password was wrong (or the ciphertext was\n * corrupted). Lets callers distinguish a bad password from malformed input.\n */\nexport function wrongPasswordError(message: string): Error {\n\treturn Object.assign(new Error(message), {\n\t\tname: 'WrongPasswordError',\n\t\t[wrongPasswordBrand]: true,\n\t});\n}\n\n/** Type guard: was decryption rejected for a wrong password / corrupt content? */\nexport function isWrongPasswordError(value: unknown): value is Error {\n\treturn value instanceof Error && wrongPasswordBrand in value;\n}\n\n/** AES-CBC key sizes supported by this PBES2 implementation. */\nexport type Pbes2EncryptionScheme = 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\n/** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */\nexport type Pbes2Prf = 'HMAC-SHA-1' | 'HMAC-SHA-256';\n\n/** Input for `encryptPbes2`. */\nexport interface Pbes2EncryptionOptions {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: Pbes2EncryptionScheme;\n\t/** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: Pbes2Prf;\n}\n\n/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */\nexport interface Pbes2Parameters {\n\t/** PBKDF2 iteration count. */\n\treadonly iterations: number;\n\t/** PBKDF2 salt bytes. */\n\treadonly salt: Uint8Array;\n\t/** AES-CBC initialization vector. */\n\treadonly iv: Uint8Array;\n\t/** AES-CBC key-size variant. */\n\treadonly cipher: Pbes2EncryptionScheme;\n\t/** PBKDF2 pseudo-random function. */\n\treadonly prf: Pbes2Prf;\n}\n\n/** Output of `encryptPbes2`: ciphertext plus the DER-encoded AlgorithmIdentifier. */\nexport interface Pbes2EncryptionResult {\n\t/** DER-encoded PBES2 AlgorithmIdentifier SEQUENCE (embeds KDF + cipher params). */\n\treadonly algorithmIdentifierDer: Uint8Array;\n\t/** AES-CBC ciphertext (includes PKCS#7 padding). */\n\treadonly encryptedData: Uint8Array;\n\t/** Resolved algorithm parameters used during encryption. */\n\treadonly parameters: Pbes2Parameters;\n}\n\n/** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */\nexport async function encryptPbes2(\n\tdata: Uint8Array,\n\toptions: Pbes2EncryptionOptions,\n): Promise<Pbes2EncryptionResult> {\n\tconst iterations = options.iterations ?? 100_000;\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst encryption = options.cipher ?? 'AES-256-CBC';\n\tconst prf = options.prf ?? 'HMAC-SHA-256';\n\n\t// Validate inputs before any WebCrypto calls\n\tif (!Number.isInteger(iterations) || iterations < 1) {\n\t\tthrow new RangeError(`Invalid iterations: must be an integer >= 1, got ${iterations}`);\n\t}\n\tif (!(salt instanceof Uint8Array) || salt.length < 8) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid salt: must be Uint8Array with length >= 8, got length ${salt.length}`,\n\t\t);\n\t}\n\tif (!(iv instanceof Uint8Array) || iv.length !== 16) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${iv.length}`,\n\t\t);\n\t}\n\n\tconst key = await deriveAesKey(options.password, salt, iterations, encryption, prf, ['encrypt']);\n\tconst encryptedData = 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(data),\n\t\t),\n\t);\n\treturn {\n\t\talgorithmIdentifierDer: encodePbes2AlgorithmIdentifier({\n\t\t\titerations,\n\t\t\tsalt,\n\t\t\tiv,\n\t\t\tcipher: encryption,\n\t\t\tprf,\n\t\t}),\n\t\tencryptedData,\n\t\tparameters: { iterations, salt, iv, cipher: encryption, prf },\n\t};\n}\n\n/** Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password. Throws on wrong password. */\nexport async function decryptPbes2(\n\talgorithmIdentifierDer: Uint8Array,\n\tencryptedData: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parameters = parsePbes2AlgorithmIdentifier(algorithmIdentifierDer);\n\tconst key = await deriveAesKey(\n\t\tpassword,\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\tparameters.cipher,\n\t\tparameters.prf,\n\t\t['decrypt'],\n\t);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(parameters.iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(encryptedData),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n}\n\n/** DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters. */\nexport function encodePbes2AlgorithmIdentifier(parameters: Pbes2Parameters): Uint8Array {\n\tconst encryption = resolveEncryptionProfile(parameters.cipher);\n\tconst prf = resolvePrfProfile(parameters.prf);\n\tconst pbkdf2Params = [\n\t\toctetString(parameters.salt),\n\t\tintegerFromNumber(parameters.iterations),\n\t\t// keyLength is OPTIONAL (kept); prf AlgorithmIdentifier DEFAULT\n\t\t// algid-hmacWithSHA1, which X.690 §11.5 forbids encoding.\n\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t...(parameters.prf === 'HMAC-SHA-1'\n\t\t\t? []\n\t\t\t: [sequence([objectIdentifier(prf.oid), nullValue()])]),\n\t];\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([objectIdentifier(OIDS.pbkdf2), sequence(pbkdf2Params)]),\n\t\t\tsequence([objectIdentifier(encryption.oid), octetString(parameters.iv)]),\n\t\t]),\n\t]);\n}\n\n/** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */\nexport function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters {\n\tconst { paramsDer, kdf, scheme } = parsePbes2OuterFields(algorithmIdentifierDer);\n\tconst { pbkdf2Der, pbkdf2Params } = parsePbes2KdfFields(paramsDer, kdf);\n\t// RFC 8018 A.2 PBKDF2-params: SEQUENCE { salt CHOICE { specified OCTET STRING,\n\t// otherSource AlgorithmIdentifier }, iterationCount INTEGER, keyLength INTEGER\n\t// OPTIONAL, prf AlgorithmIdentifier DEFAULT algid-hmacWithSHA1 }. Only the\n\t// `specified` salt alternative is accepted.\n\tconst salt = pbkdf2Params[0];\n\tconst iterations = pbkdf2Params[1];\n\tif (salt === undefined || iterations === undefined || salt.tag !== 0x04) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tconst keyLengthElement = pbkdf2Params[2];\n\tconst hasExplicitKeyLength = keyLengthElement?.tag === 0x02;\n\tconst prfElement = hasExplicitKeyLength ? pbkdf2Params[3] : keyLengthElement;\n\tconst schemeDer = paramsDer.slice(scheme.start - scheme.headerLength, scheme.end);\n\tconst schemeChildren = readSequenceChildren(schemeDer);\n\tconst schemeOid = schemeChildren[0];\n\tconst iv = schemeChildren[1];\n\tif (schemeOid === undefined || iv === undefined || iv.tag !== 0x04) {\n\t\tthrow new Error('Malformed encryption scheme');\n\t}\n\tconst encryption = encryptionSchemeFromOid(decodeObjectIdentifier(schemeOid.value));\n\tif (encryption === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\tif (keyLengthElement !== undefined && !hasExplicitKeyLength && keyLengthElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tif (\n\t\thasExplicitKeyLength &&\n\t\tdecodeIntegerNumber(keyLengthElement.value) !== encryption.keyLengthBytes\n\t) {\n\t\tthrow new Error('Unsupported PBKDF2 key length');\n\t}\n\tconst prf = parsePbkdf2Prf(pbkdf2Der, prfElement);\n\n\t// Validate parsed parameters before returning\n\tconst iterationsValue = decodeIntegerNumber(iterations.value);\n\tconst saltValue = new Uint8Array(salt.value);\n\tconst ivValue = new Uint8Array(iv.value);\n\n\tif (iterationsValue < 1) {\n\t\tthrow new Error(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${ivValue.length}`);\n\t}\n\n\treturn {\n\t\tsalt: saltValue,\n\t\titerations: iterationsValue,\n\t\tiv: ivValue,\n\t\tcipher: encryption.name,\n\t\tprf,\n\t};\n}\n\n/** Extracts the KDF and encryption-scheme fields from a PBES2 AlgorithmIdentifier. */\nfunction parsePbes2OuterFields(algorithmIdentifierDer: Uint8Array): {\n\treadonly paramsDer: Uint8Array;\n\treadonly kdf: ReturnType<typeof readSequenceChildren>[number];\n\treadonly scheme: ReturnType<typeof readSequenceChildren>[number];\n} {\n\tconst topLevel = readSequenceChildren(algorithmIdentifierDer);\n\tconst oid = topLevel[0];\n\tconst params = topLevel[1];\n\tif (oid === undefined || params === undefined) {\n\t\tthrow new Error('Malformed PBES2 algorithm identifier');\n\t}\n\tif (decodeObjectIdentifier(oid.value) !== OIDS.pbes2) {\n\t\tthrow new Error('Unsupported encryption algorithm');\n\t}\n\tconst paramsDer = algorithmIdentifierDer.slice(params.start - params.headerLength, params.end);\n\tconst pbes2Params = readSequenceChildren(paramsDer);\n\tconst kdf = pbes2Params[0];\n\tconst scheme = pbes2Params[1];\n\tif (kdf === undefined || scheme === undefined) {\n\t\tthrow new Error('Malformed PBES2 params');\n\t}\n\treturn { paramsDer, kdf, scheme };\n}\n\nfunction parsePbes2KdfFields(\n\tparamsDer: Uint8Array,\n\tkdf: ReturnType<typeof readSequenceChildren>[number],\n): {\n\treadonly pbkdf2Der: Uint8Array;\n\treadonly pbkdf2Params: ReturnType<typeof readSequenceChildren>;\n} {\n\tconst kdfDer = paramsDer.slice(kdf.start - kdf.headerLength, kdf.end);\n\tconst kdfChildren = readSequenceChildren(kdfDer);\n\tconst kdfOid = kdfChildren[0];\n\tconst kdfParams = kdfChildren[1];\n\tif (kdfOid === undefined || kdfParams === undefined) {\n\t\tthrow new Error('Malformed KDF params');\n\t}\n\tif (decodeObjectIdentifier(kdfOid.value) !== OIDS.pbkdf2) {\n\t\tthrow new Error('Unsupported KDF');\n\t}\n\tconst pbkdf2Der = kdfDer.slice(kdfParams.start - kdfParams.headerLength, kdfParams.end);\n\treturn { pbkdf2Der, pbkdf2Params: readSequenceChildren(pbkdf2Der) };\n}\n\n/** Derives an AES-CBC `CryptoKey` from a password via PBKDF2. */\nasync function deriveAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tencryptionName: Pbes2EncryptionScheme,\n\tprfName: Pbes2Prf,\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst encryption = resolveEncryptionProfile(encryptionName);\n\tconst prf = resolvePrfProfile(prfName);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t);\n\treturn getCrypto().subtle.deriveKey(\n\t\t{\n\t\t\tname: 'PBKDF2',\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\titerations,\n\t\t\thash: prf.hash,\n\t\t},\n\t\tpasswordKey,\n\t\t{ name: 'AES-CBC', length: encryption.keyLengthBits },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Parses the optional PRF AlgorithmIdentifier from PBKDF2 params. Absent means HMAC-SHA-1. */\nfunction parsePbkdf2Prf(\n\tpbkdf2Der: Uint8Array,\n\telement: ReturnType<typeof readSequenceChildren>[number] | undefined,\n): Pbes2Prf {\n\tif (element === undefined) {\n\t\treturn 'HMAC-SHA-1';\n\t}\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prfDer = readSequenceChildren(\n\t\tpbkdf2Der.slice(element.start - element.headerLength, element.end),\n\t);\n\tconst oid = prfDer[0];\n\tif (oid === undefined) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prf = prfFromOid(decodeObjectIdentifier(oid.value));\n\tif (prf === undefined) {\n\t\tthrow new Error('Unsupported PBKDF2 PRF');\n\t}\n\treturn prf;\n}\n\n/** Maps an AES-CBC OID to the encryption profile, or `undefined` if unsupported. */\nfunction encryptionSchemeFromOid(oid: string):\n\t| {\n\t\t\treadonly name: Pbes2EncryptionScheme;\n\t\t\treadonly oid: string;\n\t\t\treadonly keyLengthBits: 128 | 192 | 256;\n\t\t\treadonly keyLengthBytes: 16 | 24 | 32;\n\t }\n\t| undefined {\n\tswitch (oid) {\n\t\tcase OIDS.aes128Cbc:\n\t\t\treturn { name: 'AES-128-CBC', oid, keyLengthBits: 128, keyLengthBytes: 16 };\n\t\tcase OIDS.aes192Cbc:\n\t\t\treturn { name: 'AES-192-CBC', oid, keyLengthBits: 192, keyLengthBytes: 24 };\n\t\tcase OIDS.aes256Cbc:\n\t\t\treturn { name: 'AES-256-CBC', oid, keyLengthBits: 256, keyLengthBytes: 32 };\n\t}\n\treturn undefined;\n}\n\n/** Maps an HMAC OID to the PRF name, or `undefined` if unsupported. */\nfunction prfFromOid(oid: string): Pbes2Prf | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.hmacWithSHA1:\n\t\t\treturn 'HMAC-SHA-1';\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t}\n\treturn undefined;\n}\n\n/** Looks up the full encryption profile for a scheme name. Throws if unsupported. */\nfunction resolveEncryptionProfile(name: Pbes2EncryptionScheme): {\n\treadonly name: Pbes2EncryptionScheme;\n\treadonly oid: string;\n\treadonly keyLengthBits: 128 | 192 | 256;\n\treadonly keyLengthBytes: 16 | 24 | 32;\n} {\n\tconst profile = encryptionSchemeFromOid(\n\t\tname === 'AES-128-CBC'\n\t\t\t? OIDS.aes128Cbc\n\t\t\t: name === 'AES-192-CBC'\n\t\t\t\t? OIDS.aes192Cbc\n\t\t\t\t: OIDS.aes256Cbc,\n\t);\n\tif (profile === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\treturn profile;\n}\n\n/** Looks up OID and WebCrypto hash name for a PRF. */\nfunction resolvePrfProfile(name: Pbes2Prf): {\n\treadonly oid: string;\n\treadonly hash: 'SHA-1' | 'SHA-256';\n} {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-1':\n\t\t\treturn { oid: OIDS.hmacWithSHA1, hash: 'SHA-1' };\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn { oid: OIDS.hmacWithSHA256, hash: 'SHA-256' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled Pbes2Prf: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,MAAM,IAAqB,OAAO,6BAA6B;;;;;;AAO/D,SAAgB,mBAAmB,GAAwB;CAC1D,OAAO,OAAO,OAAW,MAAM,CAAO,GAAG;EACxC,MAAM;GACL,IAAqB;CACvB,CAAC;AACF;;AAGA,SAAgB,qBAAqB,GAAgC;CACpE,OAAO,aAAiB,SAAS,KAAsB;AACxD;;AAiDA,eAAsB,aACrB,GACA,GACiC;CACjC,IAAM,IAAa,EAAQ,cAAc,KACnC,IAAO,EAAQ,QAAQ,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC,GACrE,IAAK,EAAQ,MAAM,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC,GACjE,IAAa,EAAQ,UAAU,eAC/B,IAAM,EAAQ,OAAO;CAG3B,IAAI,CAAC,OAAO,UAAU,CAAU,KAAK,IAAa,GACjD,MAAU,WAAW,oDAAoD,GAAY;CAEtF,IAAI,EAAE,aAAgB,eAAe,EAAK,SAAS,GAClD,MAAU,UACT,iEAAiE,EAAK,QACvE;CAED,IAAI,EAAE,aAAc,eAAe,EAAG,WAAW,IAChD,MAAU,UACT,kEAAkE,EAAG,QACtE;CAGD,IAAM,IAAM,MAAM,aAAa,EAAQ,UAAU,GAAM,GAAY,GAAY,GAAK,CAAC,SAAS,CAAC,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AX_PKCS12_MAC_ITERATIONS","kdfIterationLimitBrand","iterations","remaining","limit","options","defaultLimit","budget","WEBCRYPTO_MAX_PBKDF2_ITERATIONS","passwordKey","getCrypto","toArrayBuffer","password","salt","length","iv","encryption","prf","key","encryptedData","data","parameters","algorithmIdentifierDer","pbkdf2Params","octetString","integerFromNumber","sequence","objectIdentifier","nullValue","OIDS","paramsDer","kdf","keyLengthElement","hasExplicitKeyLength","prfElement","schemeDer","scheme","schemeChildren","readSequenceChildren","schemeOid","decodeObjectIdentifier","decodeIntegerNumber","pbkdf2Der","iterationsValue","saltValue","ivValue","topLevel","oid","params","pbes2Params","kdfDer","kdfChildren","kdfOid","kdfParams","encryptionName","prfName","usages","element","profile","name"],"sources":["../../../src/internal/crypto/pbes2.ts"],"sourcesContent":["/**\n * PBES2 password-based encryption and decryption (RFC 8018).\n *\n * Supports AES-CBC-128/192/256 with PBKDF2 using HMAC-SHA-1 or HMAC-SHA-256.\n * Used internally by encrypted PKCS#8 and PFX flows.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\n\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/**\n * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in\n * practice means the supplied password was wrong (or the ciphertext was\n * corrupted). Lets callers distinguish a bad password from malformed input.\n */\nexport function wrongPasswordError(message: string): Error {\n\treturn Object.assign(new Error(message), {\n\t\tname: 'WrongPasswordError',\n\t\t[wrongPasswordBrand]: true,\n\t});\n}\n\n/** Type guard: was decryption rejected for a wrong password / corrupt content? */\nexport function isWrongPasswordError(value: unknown): value is Error {\n\treturn value instanceof Error && wrongPasswordBrand in value;\n}\n\n/** Upper bound on PBKDF2 iteration counts accepted from untrusted input. */\nexport const DEFAULT_MAX_KDF_ITERATIONS = 2_000_000;\n\n/**\n * Upper bound on PKCS#12 KDF iteration counts accepted from untrusted input.\n * RFC 7292 Appendix B hashes once per round, and each round is a separate\n * WebCrypto digest call, so a round costs more than a PBKDF2 round.\n */\nexport const DEFAULT_MAX_PKCS12_MAC_ITERATIONS = 100_000;\n\nconst kdfIterationLimitBrand = Symbol('micro509.KdfIterationLimitError');\n\n/** Thrown before key derivation when an encoded iteration count exceeds the caller's limit. */\nexport function kdfIterationLimitError(iterations: number, remaining: number): Error {\n\treturn Object.assign(\n\t\tnew Error(`KDF iteration count ${iterations} exceeds the remaining budget of ${remaining}`),\n\t\t{ name: 'KdfIterationLimitError', [kdfIterationLimitBrand]: true },\n\t);\n}\n\n/** Type guard: was derivation refused because the iteration count exceeds the limit? */\nexport function isKdfIterationLimitError(value: unknown): value is Error {\n\treturn value instanceof Error && kdfIterationLimitBrand in value;\n}\n\n/** Caller-supplied bound on password-based KDF work. */\nexport interface KdfLimitOptions {\n\t/**\n\t * Maximum KDF iteration count accepted from the input. Higher counts fail\n\t * before any derivation runs. Defaults to `2_000_000` for PBKDF2 and\n\t * `100_000` for the PKCS#12 KDF, which costs more per round. In a PFX the\n\t * PBES2-encrypted entries share one budget of this size and the MAC has a\n\t * separate budget of this size.\n\t */\n\treadonly maxKdfIterations?: number;\n}\n\n/**\n * KDF iterations one operation may still spend. A container decrypting many\n * entries shares a single budget, so entries that each sit under the ceiling\n * cannot sum past it.\n */\nexport interface KdfBudget {\n\t/** Iterations still available. */\n\tremaining: number;\n}\n\n/** Opens a budget from the caller's limit. Throws when that limit is not a positive integer. */\nexport function createKdfBudget(\n\toptions: KdfLimitOptions | undefined,\n\tdefaultLimit: number = DEFAULT_MAX_KDF_ITERATIONS,\n): KdfBudget {\n\tconst limit = options?.maxKdfIterations ?? defaultLimit;\n\tif (!Number.isSafeInteger(limit) || limit < 1) {\n\t\tthrow new RangeError(`Invalid maxKdfIterations: must be an integer >= 1, got ${limit}`);\n\t}\n\treturn { remaining: limit };\n}\n\n/** Charges iterations against the budget, throwing before any derivation runs. */\nexport function chargeKdfBudget(budget: KdfBudget, iterations: number): void {\n\tif (iterations > budget.remaining) {\n\t\tthrow kdfIterationLimitError(iterations, budget.remaining);\n\t}\n\tbudget.remaining -= iterations;\n}\n\nexport const WEBCRYPTO_MAX_PBKDF2_ITERATIONS = 0xffff_ffff;\n\nexport type Pbkdf2Hash = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';\n\nexport async function derivePbkdf2Bytes(\n\tpassword: Uint8Array,\n\tsalt: Uint8Array,\n\titerations: number,\n\thash: Pbkdf2Hash,\n\tlength: number,\n): Promise<Uint8Array> {\n\tassertPbkdf2IterationCount(iterations);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveBits'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.deriveBits(\n\t\t\t{ name: 'PBKDF2', salt: toArrayBuffer(salt), iterations, hash },\n\t\t\tpasswordKey,\n\t\t\tlength * 8,\n\t\t),\n\t);\n}\n\n/** AES-CBC key sizes supported by this PBES2 implementation. */\nexport type Pbes2EncryptionScheme = 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\n/** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */\nexport type Pbes2Prf = 'HMAC-SHA-1' | 'HMAC-SHA-256';\n\n/** Input for `encryptPbes2`. */\nexport interface Pbes2EncryptionOptions {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: Pbes2EncryptionScheme;\n\t/** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: Pbes2Prf;\n}\n\n/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */\nexport interface Pbes2Parameters {\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. */\n\treadonly iterations: number;\n\t/** PBKDF2 salt bytes. */\n\treadonly salt: Uint8Array;\n\t/** AES-CBC initialization vector. */\n\treadonly iv: Uint8Array;\n\t/** AES-CBC key-size variant. */\n\treadonly cipher: Pbes2EncryptionScheme;\n\t/** PBKDF2 pseudo-random function. */\n\treadonly prf: Pbes2Prf;\n}\n\n/** Output of `encryptPbes2`: ciphertext plus the DER-encoded AlgorithmIdentifier. */\nexport interface Pbes2EncryptionResult {\n\t/** DER-encoded PBES2 AlgorithmIdentifier SEQUENCE (embeds KDF + cipher params). */\n\treadonly algorithmIdentifierDer: Uint8Array;\n\t/** AES-CBC ciphertext (includes PKCS#7 padding). */\n\treadonly encryptedData: Uint8Array;\n\t/** Resolved algorithm parameters used during encryption. */\n\treadonly parameters: Pbes2Parameters;\n}\n\n/** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */\nexport async function encryptPbes2(\n\tdata: Uint8Array,\n\toptions: Pbes2EncryptionOptions,\n): Promise<Pbes2EncryptionResult> {\n\tconst iterations = options.iterations ?? 100_000;\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst encryption = options.cipher ?? 'AES-256-CBC';\n\tconst prf = options.prf ?? 'HMAC-SHA-256';\n\n\t// Validate inputs before any WebCrypto calls\n\tassertPbkdf2IterationCount(iterations);\n\tif (!(salt instanceof Uint8Array) || salt.length < 8) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid salt: must be Uint8Array with length >= 8, got length ${salt.length}`,\n\t\t);\n\t}\n\tif (!(iv instanceof Uint8Array) || iv.length !== 16) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${iv.length}`,\n\t\t);\n\t}\n\n\tconst key = await deriveAesKey(options.password, salt, iterations, encryption, prf, ['encrypt']);\n\tconst encryptedData = 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(data),\n\t\t),\n\t);\n\treturn {\n\t\talgorithmIdentifierDer: encodePbes2AlgorithmIdentifier({\n\t\t\titerations,\n\t\t\tsalt,\n\t\t\tiv,\n\t\t\tcipher: encryption,\n\t\t\tprf,\n\t\t}),\n\t\tencryptedData,\n\t\tparameters: { iterations, salt, iv, cipher: encryption, prf },\n\t};\n}\n\n/**\n * Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password.\n * Throws on wrong password, and before derivation when the encoded iteration\n * count exceeds what `budget` still allows.\n */\nexport async function decryptPbes2(\n\talgorithmIdentifierDer: Uint8Array,\n\tencryptedData: Uint8Array,\n\tpassword: string,\n\tbudget: KdfBudget = createKdfBudget(undefined),\n): Promise<Uint8Array> {\n\tconst parameters = parsePbes2AlgorithmIdentifier(algorithmIdentifierDer);\n\tchargeKdfBudget(budget, parameters.iterations);\n\tconst key = await deriveAesKey(\n\t\tpassword,\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\tparameters.cipher,\n\t\tparameters.prf,\n\t\t['decrypt'],\n\t);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(parameters.iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(encryptedData),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n}\n\n/**\n * DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters.\n *\n * @throws {RangeError} if `parameters.iterations` is not an integer from 1 to 4294967295.\n */\nexport function encodePbes2AlgorithmIdentifier(parameters: Pbes2Parameters): Uint8Array {\n\tassertPbkdf2IterationCount(parameters.iterations);\n\tconst encryption = resolveEncryptionProfile(parameters.cipher);\n\tconst prf = resolvePrfProfile(parameters.prf);\n\tconst pbkdf2Params = [\n\t\toctetString(parameters.salt),\n\t\tintegerFromNumber(parameters.iterations),\n\t\t// keyLength is OPTIONAL (kept); prf AlgorithmIdentifier DEFAULT\n\t\t// algid-hmacWithSHA1, which X.690 §11.5 forbids encoding under DER.\n\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t...(parameters.prf === 'HMAC-SHA-1'\n\t\t\t? []\n\t\t\t: [sequence([objectIdentifier(prf.oid), nullValue()])]),\n\t];\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([objectIdentifier(OIDS.pbkdf2), sequence(pbkdf2Params)]),\n\t\t\tsequence([objectIdentifier(encryption.oid), octetString(parameters.iv)]),\n\t\t]),\n\t]);\n}\n\n/**\n * Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}.\n *\n * @throws if the encoding is malformed, names an unsupported KDF, PRF or cipher, or carries an\n * iteration count outside 1 to 4294967295.\n */\nexport function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters {\n\tconst { paramsDer, kdf, scheme } = parsePbes2OuterFields(algorithmIdentifierDer);\n\tconst { pbkdf2Der, pbkdf2Params } = parsePbes2KdfFields(paramsDer, kdf);\n\t// RFC 8018 A.2 PBKDF2-params: SEQUENCE { salt CHOICE { specified OCTET STRING,\n\t// otherSource AlgorithmIdentifier }, iterationCount INTEGER (1..MAX), keyLength\n\t// INTEGER (1..MAX) OPTIONAL, prf AlgorithmIdentifier DEFAULT algid-hmacWithSHA1 }.\n\t// Only the `specified` salt alternative is accepted.\n\tconst salt = pbkdf2Params[0];\n\tconst iterations = pbkdf2Params[1];\n\tif (\n\t\tsalt === undefined ||\n\t\titerations === undefined ||\n\t\tsalt.tag !== 0x04 ||\n\t\titerations.tag !== 0x02\n\t) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tconst keyLengthElement = pbkdf2Params[2];\n\tconst hasExplicitKeyLength = keyLengthElement?.tag === 0x02;\n\tconst prfElement = hasExplicitKeyLength ? pbkdf2Params[3] : keyLengthElement;\n\tconst schemeDer = paramsDer.slice(scheme.start - scheme.headerLength, scheme.end);\n\tconst schemeChildren = readSequenceChildren(schemeDer);\n\tconst schemeOid = schemeChildren[0];\n\tconst iv = schemeChildren[1];\n\tif (schemeOid === undefined || iv === undefined || iv.tag !== 0x04) {\n\t\tthrow new Error('Malformed encryption scheme');\n\t}\n\tconst encryption = encryptionSchemeFromOid(decodeObjectIdentifier(schemeOid.value));\n\tif (encryption === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\tif (keyLengthElement !== undefined && !hasExplicitKeyLength && keyLengthElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tif (\n\t\thasExplicitKeyLength &&\n\t\tdecodeIntegerNumber(keyLengthElement.value) !== encryption.keyLengthBytes\n\t) {\n\t\tthrow new Error('Unsupported PBKDF2 key length');\n\t}\n\tconst prf = parsePbkdf2Prf(pbkdf2Der, prfElement);\n\n\t// Validate parsed parameters before returning\n\tconst iterationsValue = decodeIntegerNumber(iterations.value);\n\tconst saltValue = new Uint8Array(salt.value);\n\tconst ivValue = new Uint8Array(iv.value);\n\n\tif (iterationsValue < 1) {\n\t\tthrow new Error(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (iterationsValue > WEBCRYPTO_MAX_PBKDF2_ITERATIONS) {\n\t\tthrow new Error(\n\t\t\t`Invalid PBES2 iterations: must be <= ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterationsValue}`,\n\t\t);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${ivValue.length}`);\n\t}\n\n\treturn {\n\t\tsalt: saltValue,\n\t\titerations: iterationsValue,\n\t\tiv: ivValue,\n\t\tcipher: encryption.name,\n\t\tprf,\n\t};\n}\n\nfunction assertPbkdf2IterationCount(iterations: number): void {\n\tif (\n\t\t!Number.isInteger(iterations) ||\n\t\titerations < 1 ||\n\t\titerations > WEBCRYPTO_MAX_PBKDF2_ITERATIONS\n\t) {\n\t\tthrow new RangeError(\n\t\t\t`Invalid iterations: must be an integer from 1 to ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterations}`,\n\t\t);\n\t}\n}\n\n/** Extracts the KDF and encryption-scheme fields from a PBES2 AlgorithmIdentifier. */\nfunction parsePbes2OuterFields(algorithmIdentifierDer: Uint8Array): {\n\treadonly paramsDer: Uint8Array;\n\treadonly kdf: ReturnType<typeof readSequenceChildren>[number];\n\treadonly scheme: ReturnType<typeof readSequenceChildren>[number];\n} {\n\tconst topLevel = readSequenceChildren(algorithmIdentifierDer);\n\tconst oid = topLevel[0];\n\tconst params = topLevel[1];\n\tif (oid === undefined || params === undefined) {\n\t\tthrow new Error('Malformed PBES2 algorithm identifier');\n\t}\n\tif (decodeObjectIdentifier(oid.value) !== OIDS.pbes2) {\n\t\tthrow new Error('Unsupported encryption algorithm');\n\t}\n\tconst paramsDer = algorithmIdentifierDer.slice(params.start - params.headerLength, params.end);\n\tconst pbes2Params = readSequenceChildren(paramsDer);\n\tconst kdf = pbes2Params[0];\n\tconst scheme = pbes2Params[1];\n\tif (kdf === undefined || scheme === undefined) {\n\t\tthrow new Error('Malformed PBES2 params');\n\t}\n\treturn { paramsDer, kdf, scheme };\n}\n\nfunction parsePbes2KdfFields(\n\tparamsDer: Uint8Array,\n\tkdf: ReturnType<typeof readSequenceChildren>[number],\n): {\n\treadonly pbkdf2Der: Uint8Array;\n\treadonly pbkdf2Params: ReturnType<typeof readSequenceChildren>;\n} {\n\tconst kdfDer = paramsDer.slice(kdf.start - kdf.headerLength, kdf.end);\n\tconst kdfChildren = readSequenceChildren(kdfDer);\n\tconst kdfOid = kdfChildren[0];\n\tconst kdfParams = kdfChildren[1];\n\tif (kdfOid === undefined || kdfParams === undefined) {\n\t\tthrow new Error('Malformed KDF params');\n\t}\n\tif (decodeObjectIdentifier(kdfOid.value) !== OIDS.pbkdf2) {\n\t\tthrow new Error('Unsupported KDF');\n\t}\n\tconst pbkdf2Der = kdfDer.slice(kdfParams.start - kdfParams.headerLength, kdfParams.end);\n\treturn { pbkdf2Der, pbkdf2Params: readSequenceChildren(pbkdf2Der) };\n}\n\n/** Derives an AES-CBC `CryptoKey` from a password via PBKDF2. */\nasync function deriveAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tencryptionName: Pbes2EncryptionScheme,\n\tprfName: Pbes2Prf,\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst encryption = resolveEncryptionProfile(encryptionName);\n\tconst prf = resolvePrfProfile(prfName);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t);\n\treturn getCrypto().subtle.deriveKey(\n\t\t{\n\t\t\tname: 'PBKDF2',\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\titerations,\n\t\t\thash: prf.hash,\n\t\t},\n\t\tpasswordKey,\n\t\t{ name: 'AES-CBC', length: encryption.keyLengthBits },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Parses the optional PRF AlgorithmIdentifier from PBKDF2 params. Absent means HMAC-SHA-1. */\nfunction parsePbkdf2Prf(\n\tpbkdf2Der: Uint8Array,\n\telement: ReturnType<typeof readSequenceChildren>[number] | undefined,\n): Pbes2Prf {\n\tif (element === undefined) {\n\t\treturn 'HMAC-SHA-1';\n\t}\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prfDer = readSequenceChildren(\n\t\tpbkdf2Der.slice(element.start - element.headerLength, element.end),\n\t);\n\tconst oid = prfDer[0];\n\tif (oid === undefined) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prf = prfFromOid(decodeObjectIdentifier(oid.value));\n\tif (prf === undefined) {\n\t\tthrow new Error('Unsupported PBKDF2 PRF');\n\t}\n\treturn prf;\n}\n\n/** Maps an AES-CBC OID to the encryption profile, or `undefined` if unsupported. */\nfunction encryptionSchemeFromOid(oid: string):\n\t| {\n\t\t\treadonly name: Pbes2EncryptionScheme;\n\t\t\treadonly oid: string;\n\t\t\treadonly keyLengthBits: 128 | 192 | 256;\n\t\t\treadonly keyLengthBytes: 16 | 24 | 32;\n\t }\n\t| undefined {\n\tswitch (oid) {\n\t\tcase OIDS.aes128Cbc:\n\t\t\treturn { name: 'AES-128-CBC', oid, keyLengthBits: 128, keyLengthBytes: 16 };\n\t\tcase OIDS.aes192Cbc:\n\t\t\treturn { name: 'AES-192-CBC', oid, keyLengthBits: 192, keyLengthBytes: 24 };\n\t\tcase OIDS.aes256Cbc:\n\t\t\treturn { name: 'AES-256-CBC', oid, keyLengthBits: 256, keyLengthBytes: 32 };\n\t}\n\treturn undefined;\n}\n\n/** Maps an HMAC OID to the PRF name, or `undefined` if unsupported. */\nfunction prfFromOid(oid: string): Pbes2Prf | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.hmacWithSHA1:\n\t\t\treturn 'HMAC-SHA-1';\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t}\n\treturn undefined;\n}\n\n/** Looks up the full encryption profile for a scheme name. Throws if unsupported. */\nfunction resolveEncryptionProfile(name: Pbes2EncryptionScheme): {\n\treadonly name: Pbes2EncryptionScheme;\n\treadonly oid: string;\n\treadonly keyLengthBits: 128 | 192 | 256;\n\treadonly keyLengthBytes: 16 | 24 | 32;\n} {\n\tconst profile = encryptionSchemeFromOid(\n\t\tname === 'AES-128-CBC'\n\t\t\t? OIDS.aes128Cbc\n\t\t\t: name === 'AES-192-CBC'\n\t\t\t\t? OIDS.aes192Cbc\n\t\t\t\t: OIDS.aes256Cbc,\n\t);\n\tif (profile === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\treturn profile;\n}\n\n/** Looks up OID and WebCrypto hash name for a PRF. */\nfunction resolvePrfProfile(name: Pbes2Prf): {\n\treadonly oid: string;\n\treadonly hash: 'SHA-1' | 'SHA-256';\n} {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-1':\n\t\t\treturn { oid: OIDS.hmacWithSHA1, hash: 'SHA-1' };\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn { oid: OIDS.hmacWithSHA256, hash: 'SHA-256' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled Pbes2Prf: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,MAAMC,IAAqB,OAAO,6BAA6B;;;;;;AAO/D,SAAgB,mBAAmB,GAAwB;CAC1D,OAAO,OAAO,OAAW,MAAMC,CAAO,GAAG;EACxC,MAAM;GACLD,IAAqB;CACvB,CAAC;AACF;;AAGA,SAAgB,qBAAqB,GAAgC;CACpE,OAAOE,aAAiB,SAASF,KAAsBE;AACxD;;AAGA,MAAaC,IAA6B,KAO7BC,IAAoC,KAE3CC,IAAyB,OAAO,iCAAiC;;AAGvE,SAAgB,uBAAuB,GAAoB,GAA0B;CACpF,OAAO,OAAO,OACb,gBAAI,MAAM,uBAAuBC,EAAW,mCAAmCC,GAAW,GAC1F;E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