micro509 0.12.0 → 0.14.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.
- package/README.md +78 -30
- package/dist/crypto/crypto.d.ts +73 -0
- package/dist/crypto/crypto.js +74 -0
- package/dist/crypto/crypto.js.map +1 -0
- package/dist/crypto.d.ts +4 -0
- package/dist/crypto.js +2 -0
- package/dist/der/der.d.ts +127 -0
- package/dist/der/der.js +171 -0
- package/dist/der/der.js.map +1 -0
- package/dist/der.d.ts +4 -0
- package/dist/der.js +4 -0
- package/dist/index.d.ts +13 -9
- package/dist/index.js +17 -15
- package/dist/internal/asn1/asn1.d.ts +20 -0
- package/dist/internal/asn1/asn1.js +80 -37
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/der.d.ts +173 -0
- package/dist/internal/asn1/der.js +116 -38
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +7 -1
- package/dist/internal/asn1/oids2.js +9 -2
- package/dist/internal/asn1/oids2.js.map +1 -1
- package/dist/internal/crypto/algorithm-names.js +4 -0
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +38 -0
- package/dist/internal/crypto/pbes2.js +9 -10
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js +2 -0
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +31 -0
- package/dist/internal/crypto/sig-verify.js +10 -8
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/shared/base64.js +7 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +16 -0
- package/dist/internal/shared/dn.js +149 -12
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/ip.d.ts +69 -0
- package/dist/internal/shared/ip.js +18 -1
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/rfc3454-tables.js +1782 -0
- package/dist/internal/shared/rfc3454-tables.js.map +1 -0
- package/dist/internal/verify/name-constraints-engine.js +47 -15
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +85 -94
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +7 -0
- package/dist/internal/verify/verify-path.js +49 -45
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +24 -0
- package/dist/internal/x509/directory-name.js.map +1 -0
- package/dist/internal/x509/extension-bits.js +14 -11
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +6 -0
- package/dist/internal/x509/extension-errors.js +20 -0
- package/dist/internal/x509/extension-errors.js.map +1 -0
- package/dist/internal/x509/extension-registry.js +113 -55
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-tags.js +28 -0
- package/dist/internal/x509/general-name-tags.js.map +1 -0
- package/dist/internal/x509/general-name.js +97 -0
- package/dist/internal/x509/general-name.js.map +1 -0
- package/dist/internal/x509/name-fields.js +20 -10
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/keys/keys.d.ts +16 -2
- package/dist/keys/keys.js +311 -170
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +3 -2
- package/dist/keys.js +3 -2
- package/dist/pem/pem.d.ts +3 -2
- package/dist/pem/pem.js +112 -30
- package/dist/pem/pem.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.js +3 -3
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +85 -21
- package/dist/pkcs/pkcs7.js +261 -186
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +2 -2
- package/dist/result/result.d.ts +18 -10
- package/dist/result/result.js +20 -12
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +2 -2
- package/dist/result.js +2 -2
- package/dist/revocation/chain.js +154 -103
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +13 -2
- package/dist/revocation/crl.js +415 -236
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +58 -17
- package/dist/revocation/ocsp.js +186 -174
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +4 -4
- package/dist/revocation/revocation.js +48 -30
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +4 -4
- package/dist/revocation.js +5 -5
- package/dist/verify/identity.d.ts +2 -1
- package/dist/verify/identity.js +2 -1
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/policy.d.ts +6 -1
- package/dist/verify/verify.d.ts +18 -3
- package/dist/verify/verify.js +66 -41
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +2 -1
- package/dist/verify.js +4 -3
- package/dist/x509/certificate.d.ts +36 -13
- package/dist/x509/certificate.js +36 -19
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +6 -3
- package/dist/x509/extensions.d.ts +59 -22
- package/dist/x509/extensions.js +384 -117
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/name-text.js +2 -0
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +8 -5
- package/dist/x509/name.js +17 -12
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +104 -18
- package/dist/x509/parse.js +127 -163
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +8 -5
- package/dist/x509.js +10 -8
- package/package.json +52 -34
|
@@ -59,8 +59,15 @@ function flattenOidTree(e) {
|
|
|
59
59
|
return t;
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
|
-
* Dotted-decimal OID constants
|
|
63
|
-
*
|
|
62
|
+
* Dotted-decimal OID constants.
|
|
63
|
+
*
|
|
64
|
+
* Includes:
|
|
65
|
+
* - EKU purposes,
|
|
66
|
+
* - PKCS algorithms,
|
|
67
|
+
* - PKIX access methods,
|
|
68
|
+
* - X.500 attributes,
|
|
69
|
+
* - X.509v3 extensions, and
|
|
70
|
+
* - hash algorithms.
|
|
64
71
|
*/
|
|
65
72
|
const t = flattenOidTree(e);
|
|
66
73
|
//#endregion
|
|
@@ -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
|
|
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,IAAS,cAAc,GAAY,EAAK,GAAG;CAEjD,IAAI,EAAK,SAAS,KAAA,GACjB,KAAK,IAAM,CAAC,GAAM,MAAQ,OAAO,QAAQ,EAAK,IAAI,GAAG;EACpD,IAAM,IAAO,cAAc,GAAQ,CAAG;EACtC,IAAI,WAAW,GAAM,CAAI,GAAG;GAC3B,IAAM,IAAe,EAAK;GAC1B,MAAU,UACT,uBAAuB,EAAK,OAAO,EAAK,wBAAwB,GACjE;EACD;EACA,EAAK,KAAQ;CACd;CAGD,AAAI,EAAK,aAAa,KAAA,KACrB,WAAW,GAAM,EAAK,UAAU,CAAM;AAExC;AAEA,SAAS,WAAW,GAAqB,GAAe,GAA0B;CACjF,KAAK,IAAM,KAAQ,OAAO,OAAO,CAAI,GACpC,WAAW,GAAM,GAAM,CAAU;AAEnC;AAEA,SAAS,eAAe,GAAqB,GAAwC;CACpF,KAAK,IAAM,KAAS,OAAO,OAAO,CAAQ,GACzC,AAAI,UAAU,CAAK,KAClB,WAAW,GAAM,GAAO,EAAE;AAG7B;AAEA,SAAS,wBAAwB,GAAoB,GAAqB;CACzE,IAAI,EAAK,SAAS,KAAA,GACjB,KAAK,IAAM,KAAQ,OAAO,KAAK,EAAK,IAAI,GACvC,EAAM,IAAI,CAAI;CAIhB,IAAI,EAAK,aAAa,KAAA,GACrB,KAAK,IAAM,KAAS,OAAO,OAAO,EAAK,QAAQ,GAC9C,wBAAwB,GAAO,CAAK;AAGvC;AAEA,SAAS,4BAA4B,GAAqD;CACzF,IAAM,oBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAM,KAAS,OAAO,OAAO,CAAQ,GACzC,AAAI,UAAU,CAAK,KAClB,wBAAwB,GAAO,CAAK;CAGtC,OAAO,CAAC,GAAG,CAAK;AACjB;AAEA,SAAS,cAAc,GAAc,GAA+C;CACnF,KAAK,IAAM,KAAQ,GAClB,IAAI,CAAC,WAAW,GAAM,CAAI,GACzB,OAAO;CAGT,OAAO;AACR;AAEA,SAAS,eAAe,GAA2C;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"}
|
|
@@ -36,6 +36,7 @@ function describeSignatureAlgorithm(n, r) {
|
|
|
36
36
|
case e.ecdsaWithSHA384: return "ECDSA with SHA-384";
|
|
37
37
|
case e.ecdsaWithSHA512: return "ECDSA with SHA-512";
|
|
38
38
|
case e.ed25519: return "Ed25519";
|
|
39
|
+
case e.ed448: return "Ed448";
|
|
39
40
|
default: return `Unknown (${n})`;
|
|
40
41
|
}
|
|
41
42
|
}
|
|
@@ -50,7 +51,10 @@ function describePublicKeyAlgorithm(t, n) {
|
|
|
50
51
|
case e.secp521r1: return "EC P-521";
|
|
51
52
|
default: return "EC";
|
|
52
53
|
}
|
|
54
|
+
case e.x25519: return "X25519";
|
|
55
|
+
case e.x448: return "X448";
|
|
53
56
|
case e.ed25519: return "Ed25519";
|
|
57
|
+
case e.ed448: return "Ed448";
|
|
54
58
|
default: return `Unknown (${t})`;
|
|
55
59
|
}
|
|
56
60
|
}
|
|
@@ -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\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.ed25519:\n\t\t\treturn 'Ed25519';\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,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,SACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD"}
|
|
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"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/internal/crypto/pbes2.d.ts
|
|
2
|
+
/** AES-CBC key sizes supported by this PBES2 implementation. */
|
|
3
|
+
type Pbes2EncryptionScheme = "AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC";
|
|
4
|
+
/** 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";
|
|
6
|
+
/** Input for `encryptPbes2`. */
|
|
7
|
+
interface Pbes2EncryptionOptions {
|
|
8
|
+
/** Password fed to PBKDF2 for key derivation. */
|
|
9
|
+
readonly password: string;
|
|
10
|
+
/** PBKDF2 iteration count. Default: `100_000`. */
|
|
11
|
+
readonly iterations?: number;
|
|
12
|
+
/** PBKDF2 salt. Default: 16 cryptographically random bytes. */
|
|
13
|
+
readonly salt?: Uint8Array;
|
|
14
|
+
/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */
|
|
15
|
+
readonly iv?: Uint8Array;
|
|
16
|
+
/** AES-CBC cipher. Default: `'AES-256-CBC'`. */
|
|
17
|
+
readonly cipher?: Pbes2EncryptionScheme;
|
|
18
|
+
/** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */
|
|
19
|
+
readonly prf?: Pbes2Prf;
|
|
20
|
+
}
|
|
21
|
+
/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */
|
|
22
|
+
interface Pbes2Parameters {
|
|
23
|
+
/** PBKDF2 iteration count. */
|
|
24
|
+
readonly iterations: number;
|
|
25
|
+
/** PBKDF2 salt bytes. */
|
|
26
|
+
readonly salt: Uint8Array;
|
|
27
|
+
/** AES-CBC initialization vector. */
|
|
28
|
+
readonly iv: Uint8Array;
|
|
29
|
+
/** AES-CBC key-size variant. */
|
|
30
|
+
readonly cipher: Pbes2EncryptionScheme;
|
|
31
|
+
/** PBKDF2 pseudo-random function. */
|
|
32
|
+
readonly prf: Pbes2Prf;
|
|
33
|
+
}
|
|
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 };
|
|
38
|
+
//# sourceMappingURL=pbes2.d.ts.map
|
|
@@ -11,14 +11,13 @@ import { getCrypto as u } from "./webcrypto.js";
|
|
|
11
11
|
*
|
|
12
12
|
* @module
|
|
13
13
|
*/
|
|
14
|
+
/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */
|
|
15
|
+
const d = Symbol("micro509.WrongPasswordError");
|
|
14
16
|
/**
|
|
15
17
|
* Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in
|
|
16
18
|
* practice means the supplied password was wrong (or the ciphertext was
|
|
17
19
|
* corrupted). Lets callers distinguish a bad password from malformed input.
|
|
18
20
|
*/
|
|
19
|
-
/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */
|
|
20
|
-
const d = Symbol("micro509.WrongPasswordError");
|
|
21
|
-
/** Builds the branded `Error` (no class) thrown when decryption fails — a wrong password or corrupt content. */
|
|
22
21
|
function wrongPasswordError(e) {
|
|
23
22
|
return Object.assign(Error(e), {
|
|
24
23
|
name: "WrongPasswordError",
|
|
@@ -71,13 +70,13 @@ async function decryptPbes2(e, t, n) {
|
|
|
71
70
|
}
|
|
72
71
|
/** DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters. */
|
|
73
72
|
function encodePbes2AlgorithmIdentifier(i) {
|
|
74
|
-
let o = resolveEncryptionProfile(i.cipher), s = resolvePrfProfile(i.prf)
|
|
75
|
-
return a([n(l.pbes2), a([a([n(l.pbkdf2), a([
|
|
73
|
+
let o = resolveEncryptionProfile(i.cipher), s = resolvePrfProfile(i.prf), c = [
|
|
76
74
|
r(i.salt),
|
|
77
75
|
e(i.iterations),
|
|
78
76
|
e(o.keyLengthBytes),
|
|
79
|
-
a([n(s.oid), t()])
|
|
80
|
-
]
|
|
77
|
+
...i.prf === "HMAC-SHA-1" ? [] : [a([n(s.oid), t()])]
|
|
78
|
+
];
|
|
79
|
+
return a([n(l.pbes2), a([a([n(l.pbkdf2), a(c)]), a([n(o.oid), r(i.iv)])])]);
|
|
81
80
|
}
|
|
82
81
|
/** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */
|
|
83
82
|
function parsePbes2AlgorithmIdentifier(e) {
|
|
@@ -90,9 +89,8 @@ function parsePbes2AlgorithmIdentifier(e) {
|
|
|
90
89
|
if (d !== void 0 && !f && d.tag !== 48) throw Error("Malformed PBKDF2 params");
|
|
91
90
|
if (f && o(d.value) !== _.keyLengthBytes) throw Error("Unsupported PBKDF2 key length");
|
|
92
91
|
let v = parsePbkdf2Prf(a, p), y = o(u.value), b = new Uint8Array(l.value), x = new Uint8Array(g.value);
|
|
93
|
-
if (y < 1) throw
|
|
94
|
-
if (
|
|
95
|
-
if (x.length !== 16) throw RangeError(`Invalid PBES2 IV: must be exactly 16 bytes, got ${x.length}`);
|
|
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}`);
|
|
96
94
|
return {
|
|
97
95
|
salt: b,
|
|
98
96
|
iterations: y,
|
|
@@ -194,6 +192,7 @@ function resolvePrfProfile(e) {
|
|
|
194
192
|
oid: l.hmacWithSHA256,
|
|
195
193
|
hash: "SHA-256"
|
|
196
194
|
};
|
|
195
|
+
default: throw Error(`Unhandled Pbes2Prf: ${String(e)}`);
|
|
197
196
|
}
|
|
198
197
|
}
|
|
199
198
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pbes2.js","names":[],"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/**\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 */\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/** Builds the branded `Error` (no class) thrown when decryption fails — a wrong password or corrupt content. */\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\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.pbkdf2),\n\t\t\t\tsequence([\n\t\t\t\t\toctetString(parameters.salt),\n\t\t\t\t\tintegerFromNumber(parameters.iterations),\n\t\t\t\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t\t\t\tsequence([objectIdentifier(prf.oid), nullValue()]),\n\t\t\t\t]),\n\t\t\t]),\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// PBKDF2 params: SEQUENCE { salt OCTET STRING, iterationCount INTEGER, [keyLength INTEGER], [prf AlgorithmIdentifier] }\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 RangeError(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (saltValue.length < 8) {\n\t\tthrow new RangeError(`Invalid PBES2 salt: must be >= 8 bytes, got ${saltValue.length}`);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new RangeError(`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}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,MAAM,IAAqB,OAAO,6BAA6B;;AAG/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,GACzF,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ER,IAAI,EAAQ,QAAQ,IACnB,MAAU,MAAM,sBAAsB;CAKvC,IAAM,IAHS,EACd,EAAU,MAAM,EAAQ,QAAQ,EAAQ,cAAc,EAAQ,GAAG,CAEjD,CAAC,CAAC;CACnB,IAAI,MAAQ,KAAA,GACX,MAAU,MAAM,sBAAsB;CAEvC,IAAM,IAAM,WAAW,EAAuB,EAAI,KAAK,CAAC;CACxD,IAAI,MAAQ,KAAA,GACX,MAAU,MAAM,wBAAwB;CAEzC,OAAO;AACR;;AAGA,SAAS,wBAAwB,GAOpB;CACZ,QAAQ,GAAR;EACC,KAAK,EAAK,WACT,OAAO;GAAE,MAAM;GAAe;GAAK,eAAe;GAAK,gBAAgB;EAAG;EAC3E,KAAK,EAAK,WACT,OAAO;GAAE,MAAM;GAAe;GAAK,eAAe;GAAK,gBAAgB;EAAG;EAC3E,KAAK,EAAK,WACT,OAAO;GAAE,MAAM;GAAe;GAAK,eAAe;GAAK,gBAAgB;EAAG;CAC5E;AAED;;AAGA,SAAS,WAAW,GAAmC;CACtD,QAAQ,GAAR;EACC,KAAK,EAAK,cACT,OAAO;EACR,KAAK,EAAK,gBACT,OAAO;CACT;AAED;;AAGA,SAAS,yBAAyB,GAKhC;CACD,IAAM,IAAU,wBACf,MAAS,gBACN,EAAK,YACL,MAAS,gBACR,EAAK,YACL,EAAK,SACV;CACA,IAAI,MAAY,KAAA,GACf,MAAU,MAAM,uCAAuC;CAExD,OAAO;AACR;;AAGA,SAAS,kBAAkB,GAGzB;CACD,QAAQ,GAAR;EACC,KAAK,cACJ,OAAO;GAAE,KAAK,EAAK;GAAc,MAAM;EAAQ;EAChD,KAAK,gBACJ,OAAO;GAAE,KAAK,EAAK;GAAgB,MAAM;EAAU;CACrD;AACD"}
|
|
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":";;;;;;;;;;;;;;AA0B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,eAAe;GAAK,gBAAgB;EAAG;EAC3E,KAAK,EAAK,WACT,OAAO;GAAE,MAAM;GAAe;GAAK,eAAe;GAAK,gBAAgB;EAAG;EAC3E,KAAK,EAAK,WACT,OAAO;GAAE,MAAM;GAAe;GAAK,eAAe;GAAK,gBAAgB;EAAG;CAC5E;AAED;;AAGA,SAAS,WAAW,GAAmC;CACtD,QAAQ,GAAR;EACC,KAAK,EAAK,cACT,OAAO;EACR,KAAK,EAAK,gBACT,OAAO;CACT;AAED;;AAGA,SAAS,yBAAyB,GAKhC;CACD,IAAM,IAAU,wBACf,MAAS,gBACN,EAAK,YACL,MAAS,gBACR,EAAK,YACL,EAAK,SACV;CACA,IAAI,MAAY,KAAA,GACf,MAAU,MAAM,uCAAuC;CAExD,OAAO;AACR;;AAGA,SAAS,kBAAkB,GAGzB;CACD,QAAQ,GAAR;EACC,KAAK,cACJ,OAAO;GAAE,KAAK,EAAK;GAAc,MAAM;EAAQ;EAChD,KAAK,gBACJ,OAAO;GAAE,KAAK,EAAK;GAAgB,MAAM;EAAU;EACpD,SAEC,MAAU,MAAM,uBAAuB,OAAOA,CAAW,GAAG;CAE9D;AACD"}
|
|
@@ -22,6 +22,7 @@ function rsaPssParametersForHash(e) {
|
|
|
22
22
|
saltLength: 64,
|
|
23
23
|
trailerField: 1
|
|
24
24
|
};
|
|
25
|
+
default: throw Error(`Unhandled RsaPssHash: ${String(e)}`);
|
|
25
26
|
}
|
|
26
27
|
}
|
|
27
28
|
/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */
|
|
@@ -153,6 +154,7 @@ function hashOidForName(e) {
|
|
|
153
154
|
case "SHA-256": return u.sha256;
|
|
154
155
|
case "SHA-384": return u.sha384;
|
|
155
156
|
case "SHA-512": return u.sha512;
|
|
157
|
+
default: throw Error(`Unhandled RsaPssHash: ${String(e)}`);
|
|
156
158
|
}
|
|
157
159
|
}
|
|
158
160
|
/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsa-pss.js","names":[],"sources":["../../../src/internal/crypto/rsa-pss.ts"],"sourcesContent":["/**\n * RSA-PSS `AlgorithmIdentifier` parameter parsing, validation, and encoding.\n *\n * Only the three hash-matched profiles (SHA-256/384/512 with MGF1 and matching salt\n * length) are accepted; SHA-1 defaults and mismatched MGF hashes are rejected.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\trequireElement,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\n\n/** Hash algorithm accepted for RSA-PSS signatures in this library. */\nexport type RsaPssHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/**\n * One of the three supported RSA-PSS parameter profiles.\n *\n * Hash, MGF1 hash, and salt length are always matched (e.g. SHA-256 / SHA-256 / 32).\n */\nexport type RsaPssParameters =\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-256';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-256';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 32;\n\t\t\t/** Trailer field (always 0xBC per RFC 3447). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-384';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-384';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 48;\n\t\t\t/** Trailer field (always 0xBC per RFC 3447). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-512';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-512';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 64;\n\t\t\t/** Trailer field (always 0xBC per RFC 3447). */\n\t\t\treadonly trailerField: 1;\n\t };\n\n/** Machine-readable reason why an RSA-PSS parameter set is not supported. */\nexport type UnsupportedRsaPssParametersReason =\n\t| 'default_hash_sha1'\n\t| 'unsupported_hash'\n\t| 'unsupported_mgf_algorithm'\n\t| 'unsupported_mgf_hash'\n\t| 'mgf_hash_mismatch'\n\t| 'unsupported_salt_length'\n\t| 'unsupported_trailer_field';\n\n/** Success branch of {@linkcode ParsedRsaPssParametersResult}. */\nexport interface ParsedRsaPssParametersSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The validated RSA-PSS parameter profile. */\n\treadonly value: RsaPssParameters;\n}\n\n/** Failure: valid ASN.1 but an unsupported parameter combination. */\nexport interface ParsedRsaPssParametersUnsupported {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_rsa_pss_parameters';\n\t/** Which specific parameter is unsupported. */\n\treadonly reason: UnsupportedRsaPssParametersReason;\n}\n\n/** Failure: the DER encoding is structurally invalid. */\nexport interface ParsedRsaPssParametersMalformed {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'malformed_rsa_pss_parameters';\n\t/** Human-readable description of the structural defect. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode parseRsaPssParameters}: success, unsupported, or malformed. */\nexport type ParsedRsaPssParametersResult =\n\t| ParsedRsaPssParametersSuccess\n\t| ParsedRsaPssParametersUnsupported\n\t| ParsedRsaPssParametersMalformed;\n\n/** Parsed MGF AlgorithmIdentifier from an RSA-PSS parameter SEQUENCE. */\ninterface ParsedMaskGenAlgorithm {\n\t/** OID of the mask generation function (expected: id-mgf1). */\n\treadonly oid: string;\n\t/** OID of the hash algorithm used by MGF1, if present. */\n\treadonly hashOid?: string;\n}\n\ninterface MutableRsaPssParameterState {\n\thashOid: string;\n\tmaskGenAlgorithm: ParsedMaskGenAlgorithm;\n\tsaltLength: number;\n\ttrailerField: number;\n\tsawHash: boolean;\n\tsawMaskGen: boolean;\n\tsawSaltLength: boolean;\n\tsawTrailerField: boolean;\n}\n\n/** RFC 3447 default salt length when hash is SHA-1 (used to detect the unsupported default). */\nconst SHA1_SALT_LENGTH = 20;\n\n/** Return the canonical {@linkcode RsaPssParameters} profile for a given hash algorithm. */\nexport function rsaPssParametersForHash(hash: RsaPssHash): RsaPssParameters {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-256',\n\t\t\t\tmgfHash: 'SHA-256',\n\t\t\t\tsaltLength: 32,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-384':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-384',\n\t\t\t\tmgfHash: 'SHA-384',\n\t\t\t\tsaltLength: 48,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-512':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-512',\n\t\t\t\tmgfHash: 'SHA-512',\n\t\t\t\tsaltLength: 64,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t}\n}\n\n/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */\nexport function encodeRsaPssParameters(parameters: RsaPssParameters): Uint8Array {\n\tconst hashOid = hashOidForName(parameters.hash);\n\tconst hashAlgorithmIdentifier = encodeHashAlgorithmIdentifier(hashOid);\n\treturn sequence([\n\t\texplicitContext(0, hashAlgorithmIdentifier),\n\t\texplicitContext(\n\t\t\t1,\n\t\t\tsequence([objectIdentifier(OIDS.mgf1), encodeHashAlgorithmIdentifier(hashOid)]),\n\t\t),\n\t\texplicitContext(2, integerFromNumber(parameters.saltLength)),\n\t\t...(parameters.trailerField === 1\n\t\t\t? []\n\t\t\t: [explicitContext(3, integerFromNumber(parameters.trailerField))]),\n\t]);\n}\n\n/**\n * Parse and validate DER-encoded RSASSA-PSS-params.\n *\n * Returns a typed result: success with a supported profile, unsupported with\n * a reason code, or malformed with an error message.\n */\nexport function parseRsaPssParameters(\n\tparametersDer: Uint8Array | undefined,\n): ParsedRsaPssParametersResult {\n\tif (parametersDer === undefined) {\n\t\treturn unsupportedResult('default_hash_sha1');\n\t}\n\n\ttry {\n\t\tconst element = readRootElement(parametersDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (element.tag !== 0x30) {\n\t\t\tthrow new Error('RSA-PSS parameters must be a SEQUENCE');\n\t\t}\n\t\tconst state = parseRsaPssParameterFields(parametersDer, element);\n\t\treturn validateRsaPssParameterProfile(state);\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'malformed_rsa_pss_parameters',\n\t\t\treason: error instanceof Error ? error.message : 'Malformed RSA-PSS parameters',\n\t\t};\n\t}\n}\n\n/** Parses the optional context-specific RSA-PSS fields into their defaulted state. */\nfunction parseRsaPssParameterFields(\n\tparametersDer: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): MutableRsaPssParameterState {\n\tconst state: MutableRsaPssParameterState = {\n\t\thashOid: OIDS.sha1,\n\t\tmaskGenAlgorithm: { oid: OIDS.mgf1, hashOid: OIDS.sha1 },\n\t\tsaltLength: SHA1_SALT_LENGTH,\n\t\ttrailerField: 1,\n\t\tsawHash: false,\n\t\tsawMaskGen: false,\n\t\tsawSaltLength: false,\n\t\tsawTrailerField: false,\n\t};\n\tfor (const child of childrenOf(parametersDer, element)) {\n\t\tparseRsaPssParameterField(parametersDer, child, state);\n\t}\n\treturn state;\n}\n\nfunction parseRsaPssParameterField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\tstate: MutableRsaPssParameterState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0:\n\t\t\tif (state.sawHash) throw new Error('RSA-PSS parameters contain duplicate hashAlgorithm');\n\t\t\tstate.hashOid = parseHashAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'hashAlgorithm'),\n\t\t\t\t'hashAlgorithm',\n\t\t\t);\n\t\t\tstate.sawHash = true;\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tif (state.sawMaskGen)\n\t\t\t\tthrow new Error('RSA-PSS parameters contain duplicate maskGenAlgorithm');\n\t\t\tstate.maskGenAlgorithm = parseMaskGenAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'maskGenAlgorithm'),\n\t\t\t);\n\t\t\tstate.sawMaskGen = true;\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tstate.saltLength = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawSaltLength,\n\t\t\t\t'saltLength',\n\t\t\t\t'RSA-PSS saltLength',\n\t\t\t);\n\t\t\tstate.sawSaltLength = true;\n\t\t\treturn;\n\t\tcase 0xa3:\n\t\t\tstate.trailerField = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawTrailerField,\n\t\t\t\t'trailerField',\n\t\t\t\t'RSA-PSS trailerField',\n\t\t\t);\n\t\t\tstate.sawTrailerField = true;\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`RSA-PSS parameters contain unexpected field tag 0x${child.tag.toString(16)}`,\n\t\t\t);\n\t}\n}\n\nfunction parseUniqueRsaPssIntegerField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\talreadySeen: boolean,\n\tfieldName: string,\n\tintegerLabel: string,\n): number {\n\tif (alreadySeen) throw new Error(`RSA-PSS parameters contain duplicate ${fieldName}`);\n\treturn parseExplicitInteger(parametersDer, child, fieldName, integerLabel);\n}\n\nfunction validateRsaPssParameterProfile(\n\tstate: MutableRsaPssParameterState,\n): ParsedRsaPssParametersResult {\n\tconst supportedHash = hashNameFromOid(state.hashOid);\n\tif (supportedHash === undefined) {\n\t\treturn state.hashOid === OIDS.sha1\n\t\t\t? unsupportedResult('default_hash_sha1')\n\t\t\t: unsupportedResult('unsupported_hash');\n\t}\n\tif (state.maskGenAlgorithm.oid !== OIDS.mgf1)\n\t\treturn unsupportedResult('unsupported_mgf_algorithm');\n\tconst mgfHash = hashNameFromOid(state.maskGenAlgorithm.hashOid);\n\tif (mgfHash === undefined) return unsupportedResult('unsupported_mgf_hash');\n\tif (mgfHash !== supportedHash) return unsupportedResult('mgf_hash_mismatch');\n\tconst supported = rsaPssParametersForHash(supportedHash);\n\tif (state.saltLength !== supported.saltLength)\n\t\treturn unsupportedResult('unsupported_salt_length');\n\tif (state.trailerField !== 1) return unsupportedResult('unsupported_trailer_field');\n\treturn { ok: true, value: supported };\n}\n\n/** Unwrap an explicit context tag and assert it contains exactly one child element. */\nfunction requireSingleExplicitChild(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): ReturnType<typeof readRootElement> {\n\tconst children = childrenOf(source, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error(`RSA-PSS ${label} must wrap exactly one value`);\n\t}\n\treturn requireElement(children[0], `RSA-PSS ${label}`);\n}\n\n/** Extract a non-negative integer from an explicit context-tagged wrapper. */\nfunction parseExplicitInteger(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n\tintegerLabel: string,\n): number {\n\tconst integerElement = requireSingleExplicitChild(source, element, label);\n\tif (integerElement.tag !== 0x02) {\n\t\tthrow new Error(`RSA-PSS ${label} must be an INTEGER`);\n\t}\n\treturn decodeNonNegativeIntegerNumber(integerElement.value, integerLabel);\n}\n\n/** Parse an AlgorithmIdentifier SEQUENCE and return the algorithm OID. */\nfunction parseHashAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): string {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`RSA-PSS ${label} must be a SEQUENCE`);\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tconst oid = requireElement(children[0], `${label} OID`);\n\tif (oid.tag !== 0x06) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tif (children.length === 2 && requireElement(children[1], `${label} parameters`).tag !== 0x05) {\n\t\tthrow new Error(`RSA-PSS ${label} AlgorithmIdentifier parameters must be NULL when present`);\n\t}\n\treturn decodeObjectIdentifier(oid.value);\n}\n\n/** Parse an MGF AlgorithmIdentifier SEQUENCE into OID and optional inner hash OID. */\nfunction parseMaskGenAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): ParsedMaskGenAlgorithm {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('RSA-PSS maskGenAlgorithm must be a SEQUENCE');\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oidElement = requireElement(children[0], 'maskGenAlgorithm OID');\n\tif (oidElement.tag !== 0x06) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oid = decodeObjectIdentifier(oidElement.value);\n\tif (oid !== OIDS.mgf1) {\n\t\treturn { oid };\n\t}\n\tconst parameters = requireElement(children[1], 'maskGenAlgorithm parameters');\n\treturn { oid, hashOid: parseHashAlgorithmIdentifier(source, parameters, 'MGF1 hashAlgorithm') };\n}\n\n/** DER-encode a hash AlgorithmIdentifier as `SEQUENCE { OID, NULL }`. */\nfunction encodeHashAlgorithmIdentifier(oid: string): Uint8Array {\n\treturn sequence([objectIdentifier(oid), nullValue()]);\n}\n\n/** Map a hash algorithm name to its ASN.1 OID string. */\nfunction hashOidForName(hash: RsaPssHash): string {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn OIDS.sha256;\n\t\tcase 'SHA-384':\n\t\t\treturn OIDS.sha384;\n\t\tcase 'SHA-512':\n\t\t\treturn OIDS.sha512;\n\t}\n}\n\n/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */\nfunction hashNameFromOid(oid: string | undefined): RsaPssHash | undefined {\n\tswitch (oid) {\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 undefined;\n\t}\n}\n\n/** Build an unsupported-parameters failure result. */\nfunction unsupportedResult(\n\treason: UnsupportedRsaPssParametersReason,\n): ParsedRsaPssParametersUnsupported {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_rsa_pss_parameters',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;AAqIA,SAAgB,wBAAwB,GAAoC;CAC3E,QAAQ,GAAR;EACC,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;CACF;AACD;;AAGA,SAAgB,uBAAuB,GAA0C;CAChF,IAAM,IAAU,eAAe,EAAW,IAAI;CAE9C,OAAO,EAAS;EACf,EAAgB,GAFe,8BAA8B,CAE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AS,eAAe,GAA0B;CACjD,QAAQ,GAAR;EACC,KAAK,WACJ,OAAO,EAAK;EACb,KAAK,WACJ,OAAO,EAAK;EACb,KAAK,WACJ,OAAO,EAAK;CACd;AACD;;AAGA,SAAS,gBAAgB,GAAiD;CACzE,QAAQ,GAAR;EACC,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC;CACF;AACD;;AAGA,SAAS,kBACR,GACoC;CACpC,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"rsa-pss.js","names":["_exhaustive"],"sources":["../../../src/internal/crypto/rsa-pss.ts"],"sourcesContent":["/**\n * RSA-PSS `AlgorithmIdentifier` parameter parsing, validation, and encoding.\n *\n * Only the three hash-matched profiles (SHA-256/384/512 with MGF1 and matching salt\n * length) are accepted; SHA-1 defaults and mismatched MGF hashes are rejected.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\trequireElement,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\n\n/** Hash algorithm accepted for RSA-PSS signatures in this library. */\nexport type RsaPssHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/**\n * One of the three supported RSA-PSS parameter profiles.\n *\n * Hash, MGF1 hash, and salt length are always matched (e.g. SHA-256 / SHA-256 / 32).\n */\nexport type RsaPssParameters =\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-256';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-256';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 32;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-384';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-384';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 48;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-512';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-512';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 64;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t };\n\n/** Machine-readable reason why an RSA-PSS parameter set is not supported. */\nexport type UnsupportedRsaPssParametersReason =\n\t| 'default_hash_sha1'\n\t| 'unsupported_hash'\n\t| 'unsupported_mgf_algorithm'\n\t| 'unsupported_mgf_hash'\n\t| 'mgf_hash_mismatch'\n\t| 'unsupported_salt_length'\n\t| 'unsupported_trailer_field';\n\n/** Success branch of {@linkcode ParsedRsaPssParametersResult}. */\nexport interface ParsedRsaPssParametersSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The validated RSA-PSS parameter profile. */\n\treadonly value: RsaPssParameters;\n}\n\n/** Failure: valid ASN.1 but an unsupported parameter combination. */\nexport interface ParsedRsaPssParametersUnsupported {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_rsa_pss_parameters';\n\t/** Which specific parameter is unsupported. */\n\treadonly reason: UnsupportedRsaPssParametersReason;\n}\n\n/** Failure: the DER encoding is structurally invalid. */\nexport interface ParsedRsaPssParametersMalformed {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'malformed_rsa_pss_parameters';\n\t/** Human-readable description of the structural defect. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode parseRsaPssParameters}: success, unsupported, or malformed. */\nexport type ParsedRsaPssParametersResult =\n\t| ParsedRsaPssParametersSuccess\n\t| ParsedRsaPssParametersUnsupported\n\t| ParsedRsaPssParametersMalformed;\n\n/** Parsed MGF AlgorithmIdentifier from an RSA-PSS parameter SEQUENCE. */\ninterface ParsedMaskGenAlgorithm {\n\t/** OID of the mask generation function (expected: id-mgf1). */\n\treadonly oid: string;\n\t/** OID of the hash algorithm used by MGF1, if present. */\n\treadonly hashOid?: string;\n}\n\ninterface MutableRsaPssParameterState {\n\thashOid: string;\n\tmaskGenAlgorithm: ParsedMaskGenAlgorithm;\n\tsaltLength: number;\n\ttrailerField: number;\n\tsawHash: boolean;\n\tsawMaskGen: boolean;\n\tsawSaltLength: boolean;\n\tsawTrailerField: boolean;\n}\n\n/** RFC 8017 Appendix A.2.3 default salt length when hash is SHA-1. */\nconst SHA1_SALT_LENGTH = 20;\n\n/** Return the canonical {@linkcode RsaPssParameters} profile for a given hash algorithm. */\nexport function rsaPssParametersForHash(hash: RsaPssHash): RsaPssParameters {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-256',\n\t\t\t\tmgfHash: 'SHA-256',\n\t\t\t\tsaltLength: 32,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-384':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-384',\n\t\t\t\tmgfHash: 'SHA-384',\n\t\t\t\tsaltLength: 48,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-512':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-512',\n\t\t\t\tmgfHash: 'SHA-512',\n\t\t\t\tsaltLength: 64,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */\nexport function encodeRsaPssParameters(parameters: RsaPssParameters): Uint8Array {\n\tconst hashOid = hashOidForName(parameters.hash);\n\tconst hashAlgorithmIdentifier = encodeHashAlgorithmIdentifier(hashOid);\n\treturn sequence([\n\t\texplicitContext(0, hashAlgorithmIdentifier),\n\t\texplicitContext(\n\t\t\t1,\n\t\t\tsequence([objectIdentifier(OIDS.mgf1), encodeHashAlgorithmIdentifier(hashOid)]),\n\t\t),\n\t\texplicitContext(2, integerFromNumber(parameters.saltLength)),\n\t\t...(parameters.trailerField === 1\n\t\t\t? []\n\t\t\t: [explicitContext(3, integerFromNumber(parameters.trailerField))]),\n\t]);\n}\n\n/**\n * Parse and validate DER-encoded RSASSA-PSS-params.\n *\n * Returns a typed result: success with a supported profile, unsupported with\n * a reason code, or malformed with an error message.\n */\nexport function parseRsaPssParameters(\n\tparametersDer: Uint8Array | undefined,\n): ParsedRsaPssParametersResult {\n\tif (parametersDer === undefined) {\n\t\treturn unsupportedResult('default_hash_sha1');\n\t}\n\n\ttry {\n\t\tconst element = readRootElement(parametersDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (element.tag !== 0x30) {\n\t\t\tthrow new Error('RSA-PSS parameters must be a SEQUENCE');\n\t\t}\n\t\tconst state = parseRsaPssParameterFields(parametersDer, element);\n\t\treturn validateRsaPssParameterProfile(state);\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'malformed_rsa_pss_parameters',\n\t\t\treason: error instanceof Error ? error.message : 'Malformed RSA-PSS parameters',\n\t\t};\n\t}\n}\n\n/** Parses the optional context-specific RSA-PSS fields into their defaulted state. */\nfunction parseRsaPssParameterFields(\n\tparametersDer: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): MutableRsaPssParameterState {\n\tconst state: MutableRsaPssParameterState = {\n\t\thashOid: OIDS.sha1,\n\t\tmaskGenAlgorithm: { oid: OIDS.mgf1, hashOid: OIDS.sha1 },\n\t\tsaltLength: SHA1_SALT_LENGTH,\n\t\ttrailerField: 1,\n\t\tsawHash: false,\n\t\tsawMaskGen: false,\n\t\tsawSaltLength: false,\n\t\tsawTrailerField: false,\n\t};\n\tfor (const child of childrenOf(parametersDer, element)) {\n\t\tparseRsaPssParameterField(parametersDer, child, state);\n\t}\n\treturn state;\n}\n\nfunction parseRsaPssParameterField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\tstate: MutableRsaPssParameterState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0:\n\t\t\tif (state.sawHash) throw new Error('RSA-PSS parameters contain duplicate hashAlgorithm');\n\t\t\tstate.hashOid = parseHashAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'hashAlgorithm'),\n\t\t\t\t'hashAlgorithm',\n\t\t\t);\n\t\t\tstate.sawHash = true;\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tif (state.sawMaskGen)\n\t\t\t\tthrow new Error('RSA-PSS parameters contain duplicate maskGenAlgorithm');\n\t\t\tstate.maskGenAlgorithm = parseMaskGenAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'maskGenAlgorithm'),\n\t\t\t);\n\t\t\tstate.sawMaskGen = true;\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tstate.saltLength = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawSaltLength,\n\t\t\t\t'saltLength',\n\t\t\t\t'RSA-PSS saltLength',\n\t\t\t);\n\t\t\tstate.sawSaltLength = true;\n\t\t\treturn;\n\t\tcase 0xa3:\n\t\t\tstate.trailerField = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawTrailerField,\n\t\t\t\t'trailerField',\n\t\t\t\t'RSA-PSS trailerField',\n\t\t\t);\n\t\t\tstate.sawTrailerField = true;\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`RSA-PSS parameters contain unexpected field tag 0x${child.tag.toString(16)}`,\n\t\t\t);\n\t}\n}\n\nfunction parseUniqueRsaPssIntegerField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\talreadySeen: boolean,\n\tfieldName: string,\n\tintegerLabel: string,\n): number {\n\tif (alreadySeen) throw new Error(`RSA-PSS parameters contain duplicate ${fieldName}`);\n\treturn parseExplicitInteger(parametersDer, child, fieldName, integerLabel);\n}\n\nfunction validateRsaPssParameterProfile(\n\tstate: MutableRsaPssParameterState,\n): ParsedRsaPssParametersResult {\n\tconst supportedHash = hashNameFromOid(state.hashOid);\n\tif (supportedHash === undefined) {\n\t\treturn state.hashOid === OIDS.sha1\n\t\t\t? unsupportedResult('default_hash_sha1')\n\t\t\t: unsupportedResult('unsupported_hash');\n\t}\n\tif (state.maskGenAlgorithm.oid !== OIDS.mgf1)\n\t\treturn unsupportedResult('unsupported_mgf_algorithm');\n\tconst mgfHash = hashNameFromOid(state.maskGenAlgorithm.hashOid);\n\tif (mgfHash === undefined) return unsupportedResult('unsupported_mgf_hash');\n\tif (mgfHash !== supportedHash) return unsupportedResult('mgf_hash_mismatch');\n\tconst supported = rsaPssParametersForHash(supportedHash);\n\tif (state.saltLength !== supported.saltLength)\n\t\treturn unsupportedResult('unsupported_salt_length');\n\tif (state.trailerField !== 1) return unsupportedResult('unsupported_trailer_field');\n\treturn { ok: true, value: supported };\n}\n\n/** Unwrap an explicit context tag and assert it contains exactly one child element. */\nfunction requireSingleExplicitChild(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): ReturnType<typeof readRootElement> {\n\tconst children = childrenOf(source, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error(`RSA-PSS ${label} must wrap exactly one value`);\n\t}\n\treturn requireElement(children[0], `RSA-PSS ${label}`);\n}\n\n/** Extract a non-negative integer from an explicit context-tagged wrapper. */\nfunction parseExplicitInteger(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n\tintegerLabel: string,\n): number {\n\tconst integerElement = requireSingleExplicitChild(source, element, label);\n\tif (integerElement.tag !== 0x02) {\n\t\tthrow new Error(`RSA-PSS ${label} must be an INTEGER`);\n\t}\n\treturn decodeNonNegativeIntegerNumber(integerElement.value, integerLabel);\n}\n\n/** Parse an AlgorithmIdentifier SEQUENCE and return the algorithm OID. */\nfunction parseHashAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): string {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`RSA-PSS ${label} must be a SEQUENCE`);\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tconst oid = requireElement(children[0], `${label} OID`);\n\tif (oid.tag !== 0x06) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tif (children.length === 2 && requireElement(children[1], `${label} parameters`).tag !== 0x05) {\n\t\tthrow new Error(`RSA-PSS ${label} AlgorithmIdentifier parameters must be NULL when present`);\n\t}\n\treturn decodeObjectIdentifier(oid.value);\n}\n\n/** Parse an MGF AlgorithmIdentifier SEQUENCE into OID and optional inner hash OID. */\nfunction parseMaskGenAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): ParsedMaskGenAlgorithm {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('RSA-PSS maskGenAlgorithm must be a SEQUENCE');\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oidElement = requireElement(children[0], 'maskGenAlgorithm OID');\n\tif (oidElement.tag !== 0x06) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oid = decodeObjectIdentifier(oidElement.value);\n\tif (oid !== OIDS.mgf1) {\n\t\treturn { oid };\n\t}\n\tconst parameters = requireElement(children[1], 'maskGenAlgorithm parameters');\n\treturn { oid, hashOid: parseHashAlgorithmIdentifier(source, parameters, 'MGF1 hashAlgorithm') };\n}\n\n/** DER-encode a hash AlgorithmIdentifier as `SEQUENCE { OID, NULL }`. */\nfunction encodeHashAlgorithmIdentifier(oid: string): Uint8Array {\n\treturn sequence([objectIdentifier(oid), nullValue()]);\n}\n\n/** Map a hash algorithm name to its ASN.1 OID string. */\nfunction hashOidForName(hash: RsaPssHash): string {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn OIDS.sha256;\n\t\tcase 'SHA-384':\n\t\t\treturn OIDS.sha384;\n\t\tcase 'SHA-512':\n\t\t\treturn OIDS.sha512;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */\nfunction hashNameFromOid(oid: string | undefined): RsaPssHash | undefined {\n\tswitch (oid) {\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 undefined;\n\t}\n}\n\n/** Build an unsupported-parameters failure result. */\nfunction unsupportedResult(\n\treason: UnsupportedRsaPssParametersReason,\n): ParsedRsaPssParametersUnsupported {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_rsa_pss_parameters',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;AAqIA,SAAgB,wBAAwB,GAAoC;CAC3E,QAAQ,GAAR;EACC,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,SAEC,MAAU,MAAM,yBAAyB,OAAOA,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAgB,uBAAuB,GAA0C;CAChF,IAAM,IAAU,eAAe,EAAW,IAAI;CAE9C,OAAO,EAAS;EACf,EAAgB,GAFe,8BAA8B,CAEpB,CAAC;EAC1C,EACC,GACA,EAAS,CAAC,EAAiB,EAAK,IAAI,GAAG,8BAA8B,CAAO,CAAC,CAAC,CAC/E;EACA,EAAgB,GAAG,EAAkB,EAAW,UAAU,CAAC;EAC3D,GAAI,EAAW,iBAAiB,IAC7B,CAAC,IACD,CAAC,EAAgB,GAAG,EAAkB,EAAW,YAAY,CAAC,CAAC;CACnE,CAAC;AACF;;;;;;;AAQA,SAAgB,sBACf,GAC+B;CAC/B,IAAI,MAAkB,KAAA,GACrB,OAAO,kBAAkB,mBAAmB;CAG7C,IAAI;EACH,IAAM,IAAU,EAAgB,GAAe,EAAE,UAAA,GAAgC,CAAC;EAClF,IAAI,EAAQ,QAAQ,IACnB,MAAU,MAAM,uCAAuC;EAGxD,OAAO,+BADO,2BAA2B,GAAe,CACd,CAAC;CAC5C,SAAS,GAAO;EACf,OAAO;GACN,IAAI;GACJ,MAAM;GACN,QAAQ,aAAiB,QAAQ,EAAM,UAAU;EAClD;CACD;AACD;;AAGA,SAAS,2B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AO,EAAuB,EAAI,KAAK;AACxC;;AAGA,SAAS,gCACR,GACA,GACyB;CACzB,IAAI,EAAQ,QAAQ,IACnB,MAAU,MAAM,6CAA6C;CAE9D,IAAM,IAAW,EAAW,GAAQ,CAAO;CAC3C,IAAI,EAAS,WAAW,KAAK,EAAS,SAAS,GAC9C,MAAU,MAAM,wDAAwD;CAEzE,IAAM,IAAa,EAAe,EAAS,IAAI,sBAAsB;CACrE,IAAI,EAAW,QAAQ,GACtB,MAAU,MAAM,wDAAwD;CAEzE,IAAM,IAAM,EAAuB,EAAW,KAAK;CAKnD,OAJI,MAAQ,EAAK,OAIV;EAAE;EAAK,SAAS,6BAA6B,GADjC,EAAe,EAAS,IAAI,6BACsB,GAAG,oBAAoB;CAAE,IAHtF,EAAE,OAAI;AAIf;;AAGA,SAAS,8BAA8B,GAAyB;CAC/D,OAAO,EAAS,CAAC,EAAiB,CAAG,GAAG,EAAU,CAAC,CAAC;AACrD;;AAGA,SAAS,eAAe,GAA0B;CACjD,QAAQ,GAAR;EACC,KAAK,WACJ,OAAO,EAAK;EACb,KAAK,WACJ,OAAO,EAAK;EACb,KAAK,WACJ,OAAO,EAAK;EACb,SAEC,MAAU,MAAM,yBAAyB,OAAOA,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAS,gBAAgB,GAAiD;CACzE,QAAQ,GAAR;EACC,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC;CACF;AACD;;AAGA,SAAS,kBACR,GACoC;CACpC,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region src/internal/crypto/sig-verify.d.ts
|
|
2
|
+
/** Failure: the signature algorithm or its parameters are not supported. */
|
|
3
|
+
interface VerifySignatureConfigFailure {
|
|
4
|
+
/** Discriminant for the failure branch. */
|
|
5
|
+
readonly ok: false;
|
|
6
|
+
/** Machine-readable failure code. */
|
|
7
|
+
readonly code: "unsupported_signature_algorithm_parameters";
|
|
8
|
+
/** Human-readable explanation of why the algorithm is unsupported. */
|
|
9
|
+
readonly reason: string;
|
|
10
|
+
}
|
|
11
|
+
/** Failure: signature verification could not run to completion. */
|
|
12
|
+
interface VerifySignedDataFailure {
|
|
13
|
+
/** Discriminant for the failure branch. */
|
|
14
|
+
readonly ok: false;
|
|
15
|
+
/** Machine-readable failure code. */
|
|
16
|
+
readonly code: "verification_error";
|
|
17
|
+
/** Human-readable explanation of the verification failure. */
|
|
18
|
+
readonly reason: string;
|
|
19
|
+
}
|
|
20
|
+
/** Success branch of {@linkcode VerifySignedDataResult}. */
|
|
21
|
+
interface VerifySignedDataSuccess {
|
|
22
|
+
/** Discriminant for the success branch. */
|
|
23
|
+
readonly ok: true;
|
|
24
|
+
/** Whether the cryptographic signature is valid for the given data and key. */
|
|
25
|
+
readonly valid: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** Result of a full signature verification: validity, unsupported params, or a runtime verification failure. */
|
|
28
|
+
type VerifySignedDataResult = VerifySignedDataSuccess | VerifySignatureConfigFailure | VerifySignedDataFailure;
|
|
29
|
+
//#endregion
|
|
30
|
+
export { VerifySignatureConfigFailure, VerifySignedDataFailure, VerifySignedDataResult, VerifySignedDataSuccess };
|
|
31
|
+
//# sourceMappingURL=sig-verify.d.ts.map
|
|
@@ -16,15 +16,15 @@ import { alternateEcdsaSignatureEncoding as o } from "./ecdsa.js";
|
|
|
16
16
|
function getVerifySignatureConfigResult(e, t, r, i, a = "issuer") {
|
|
17
17
|
switch (e) {
|
|
18
18
|
case n.sha256WithRSAEncryption: {
|
|
19
|
-
let e =
|
|
19
|
+
let e = requireDerNullOrAbsentSignatureAlgorithmParameters(t, "SHA-256 with RSA");
|
|
20
20
|
return e === void 0 ? requireRsaPublicKey(r, "SHA-256", "pkcs1-v1_5", a) : e;
|
|
21
21
|
}
|
|
22
22
|
case n.sha384WithRSAEncryption: {
|
|
23
|
-
let e =
|
|
23
|
+
let e = requireDerNullOrAbsentSignatureAlgorithmParameters(t, "SHA-384 with RSA");
|
|
24
24
|
return e === void 0 ? requireRsaPublicKey(r, "SHA-384", "pkcs1-v1_5", a) : e;
|
|
25
25
|
}
|
|
26
26
|
case n.sha512WithRSAEncryption: {
|
|
27
|
-
let e =
|
|
27
|
+
let e = requireDerNullOrAbsentSignatureAlgorithmParameters(t, "SHA-512 with RSA");
|
|
28
28
|
return e === void 0 ? requireRsaPublicKey(r, "SHA-512", "pkcs1-v1_5", a) : e;
|
|
29
29
|
}
|
|
30
30
|
case n.rsassaPss: return requireRsaPssVerifyConfig(t, r, a);
|
|
@@ -140,13 +140,15 @@ function requireRsaPssVerifyConfig(e, t, n) {
|
|
|
140
140
|
let r = a(e);
|
|
141
141
|
return r.ok ? requireRsaPublicKey(t, r.value.hash, "pss", n, r.value.saltLength) : unsupported("RSA-PSS", r.reason);
|
|
142
142
|
}
|
|
143
|
-
|
|
144
|
-
|
|
143
|
+
/** RFC 4055 §5 requires generators to encode NULL and implementations to accept absent parameters too. */
|
|
144
|
+
function requireDerNullOrAbsentSignatureAlgorithmParameters(t, n) {
|
|
145
|
+
if (t === void 0) return;
|
|
146
|
+
let r = "signature AlgorithmIdentifier parameters must be DER NULL or absent";
|
|
145
147
|
try {
|
|
146
|
-
let
|
|
147
|
-
return
|
|
148
|
+
let i = e(t);
|
|
149
|
+
return i.tag !== 5 || i.length !== 0 || i.end !== t.length ? unsupported(n, r) : void 0;
|
|
148
150
|
} catch {
|
|
149
|
-
return unsupported(n,
|
|
151
|
+
return unsupported(n, r);
|
|
150
152
|
}
|
|
151
153
|
}
|
|
152
154
|
function requireAbsentSignatureAlgorithmParameters(e, t) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sig-verify.js","names":[],"sources":["../../../src/internal/crypto/sig-verify.ts"],"sourcesContent":["/**\n * Signature-verification helpers that resolve parsed algorithm OIDs into WebCrypto\n * verification configuration for higher-level validators.\n *\n * @module\n */\n\nimport { toArrayBuffer } from '#micro509/internal/asn1/asn1';\nimport { readElement } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { alternateEcdsaSignatureEncoding } from '#micro509/internal/crypto/ecdsa';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { PublicKeyImportInput, RsaHash, RsaSignatureScheme } from '#micro509/keys/keys';\nimport { importSpkiDerOrThrow } from '#micro509/keys/keys';\n\nexport {\n\talternateEcdsaSignatureEncoding,\n\tconcatFixedWidth,\n\tderEcdsaSignatureToRaw,\n\trawEcdsaSignatureToDer,\n} from '#micro509/internal/crypto/ecdsa';\n\n/** Resolved WebCrypto parameters needed to verify a signature. */\nexport interface VerifySignatureConfig {\n\t/** Algorithm descriptor for importing the signer's public key via {@linkcode importSpkiDer}. */\n\treadonly importAlgorithm: PublicKeyImportInput;\n\t/** WebCrypto `verify()` algorithm parameter. */\n\treadonly verifyParams: Algorithm | EcdsaParams | RsaPssParams;\n\t/** When set, raw ECDSA signatures are this many bytes and may need DER/raw conversion. */\n\treadonly ecdsaRawSignatureBytes?: number;\n}\n\n/** Failure: the signature algorithm or its parameters are not supported. */\nexport interface VerifySignatureConfigFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_signature_algorithm_parameters';\n\t/** Human-readable explanation of why the algorithm is unsupported. */\n\treadonly reason: string;\n}\n\n/** Failure: signature verification could not run to completion. */\nexport interface VerifySignedDataFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'verification_error';\n\t/** Human-readable explanation of the verification failure. */\n\treadonly reason: string;\n}\n\n/** Success branch of {@linkcode VerifySignatureConfigResult}. */\nexport interface VerifySignatureConfigSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The resolved verification configuration. */\n\treadonly value: VerifySignatureConfig;\n}\n\n/** Result of resolving signature algorithm OIDs into a {@linkcode VerifySignatureConfig}. */\nexport type VerifySignatureConfigResult =\n\t| VerifySignatureConfigSuccess\n\t| VerifySignatureConfigFailure;\n\n/** Success branch of {@linkcode VerifySignedDataResult}. */\nexport interface VerifySignedDataSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** Whether the cryptographic signature is valid for the given data and key. */\n\treadonly valid: boolean;\n}\n\n/** Result of a full signature verification: validity, unsupported params, or a runtime verification failure. */\nexport type VerifySignedDataResult =\n\t| VerifySignedDataSuccess\n\t| VerifySignatureConfigFailure\n\t| VerifySignedDataFailure;\n\n/**\n * Resolve algorithm OIDs into a {@linkcode VerifySignatureConfig}.\n *\n * Throws on unsupported algorithms. Use {@linkcode getVerifySignatureConfigResult} for\n * a non-throwing variant.\n */\nexport function getVerifySignatureConfig(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfig {\n\tconst result = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tcontext,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.value;\n}\n\n/** Non-throwing variant of {@linkcode getVerifySignatureConfig} — returns a typed result union. */\nexport function getVerifySignatureConfigResult(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tswitch (signatureAlgorithmOid) {\n\t\tcase OIDS.sha256WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-256 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-256', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha384WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-384 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-384', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha512WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-512 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-512', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn requireRsaPssVerifyConfig(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\tpublicKeyAlgorithmOid,\n\t\t\t\tcontext,\n\t\t\t);\n\t\tcase OIDS.ecdsaWithSHA256: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-256',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-256', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA384: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-384',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-384', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA512: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-512',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-512', context);\n\t\t}\n\t\tcase OIDS.ed25519: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'Ed25519',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\tif (publicKeyAlgorithmOid !== OIDS.ed25519) {\n\t\t\t\treturn unsupported('Ed25519', `requires Ed25519 ${context} public key`);\n\t\t\t}\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ed25519' },\n\t\t\t\tverifyParams: { name: 'Ed25519' },\n\t\t\t});\n\t\t}\n\t\tdefault:\n\t\t\treturn unsupported(signatureAlgorithmOid, 'unrecognized signature algorithm OID');\n\t}\n}\n\n/** Validate that the public key OID is `rsaEncryption` and return an RSA verification config result. */\nexport function requireRsaPublicKey(\n\talgorithmOid: string,\n\thash: RsaHash,\n\tscheme: RsaSignatureScheme = 'pkcs1-v1_5',\n\tcontext = 'issuer',\n\tsaltLength?: number,\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.rsaEncryption) {\n\t\treturn unsupported('RSA', `requires RSA ${context} public key`);\n\t}\n\tconst verifyParams: Algorithm | RsaPssParams =\n\t\tscheme === 'pss'\n\t\t\t? { name: 'RSA-PSS', saltLength: saltLength ?? 0 }\n\t\t\t: { name: 'RSASSA-PKCS1-v1_5' };\n\treturn ok({ importAlgorithm: { kind: 'rsa', hash, scheme }, verifyParams });\n}\n\n/** Validate that the public key OID is `ecPublicKey`, resolve the curve, and return an ECDSA verification config result. */\nexport function requireEcPublicKey(\n\talgorithmOid: string,\n\tparametersOid: string | undefined,\n\thash: string,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.ecPublicKey) {\n\t\treturn unsupported('ECDSA', `requires EC ${context} public key`);\n\t}\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-256' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 64,\n\t\t\t});\n\t\tcase OIDS.secp384r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-384' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 96,\n\t\t\t});\n\t\tcase OIDS.secp521r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-521' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 132,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn unsupported('ECDSA', `unsupported EC curve OID: ${parametersOid ?? 'missing'}`);\n\t}\n}\n\n/** Return the raw ECDSA signature byte count (r + s) for a given curve OID, if supported. */\nexport function curveBytes(parametersOid: string | undefined): number | undefined {\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn 64;\n\t\tcase OIDS.secp384r1:\n\t\t\treturn 96;\n\t\tcase OIDS.secp521r1:\n\t\t\treturn 132;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Verify a signature against the signer's SPKI and the signed TBS bytes.\n *\n * Throws on unsupported algorithms. Use {@linkcode verifySignedDataDetailed} for\n * a non-throwing variant.\n */\nexport async function verifySignedData(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n): Promise<boolean> {\n\tconst result = await verifySignedDataDetailed(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tsubjectPublicKeyInfoDer,\n\t\tsignature,\n\t\tsignedData,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.valid;\n}\n\n/**\n * Non-throwing variant of {@linkcode verifySignedData} — returns a typed\n * {@linkcode VerifySignedDataResult} instead of throwing on unsupported algorithms\n * or runtime verification failures.\n *\n * Tries both DER and raw ECDSA encodings when the first attempt fails.\n */\nexport async function verifySignedDataDetailed(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n): Promise<VerifySignedDataResult> {\n\tconst config = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t);\n\tif (!config.ok) {\n\t\treturn config;\n\t}\n\ttry {\n\t\tconst key = await importSpkiDerOrThrow(subjectPublicKeyInfoDer, config.value.importAlgorithm);\n\t\tconst subtle = getCrypto().subtle;\n\t\tconst signatureView = toArrayBuffer(signature);\n\t\tconst dataView = toArrayBuffer(signedData);\n\t\tif (await subtle.verify(config.value.verifyParams, key, signatureView, dataView)) {\n\t\t\treturn { ok: true, valid: true };\n\t\t}\n\t\tif (config.value.ecdsaRawSignatureBytes !== undefined) {\n\t\t\tconst alternate = alternateEcdsaSignatureEncoding(\n\t\t\t\tsignature,\n\t\t\t\tconfig.value.ecdsaRawSignatureBytes / 2,\n\t\t\t);\n\t\t\tif (alternate !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalid: await subtle.verify(\n\t\t\t\t\t\tconfig.value.verifyParams,\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\ttoArrayBuffer(alternate),\n\t\t\t\t\t\tdataView,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn { ok: true, valid: false };\n\t} catch (error) {\n\t\treturn verificationError(\n\t\t\terror instanceof Error ? error.message : 'signature verification failed',\n\t\t);\n\t}\n}\n\n/** Parse RSA-PSS algorithm parameters and build a verification config, or return failure. */\nfunction requireRsaPssVerifyConfig(\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tcontext: string,\n): VerifySignatureConfigResult {\n\tconst parameters = parseRsaPssParameters(signatureAlgorithmParametersDer);\n\tif (!parameters.ok) {\n\t\treturn unsupported('RSA-PSS', parameters.reason);\n\t}\n\treturn requireRsaPublicKey(\n\t\tpublicKeyAlgorithmOid,\n\t\tparameters.value.hash,\n\t\t'pss',\n\t\tcontext,\n\t\tparameters.value.saltLength,\n\t);\n}\n\nfunction requireDerNullSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer === undefined) {\n\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be DER NULL');\n\t}\n\ttry {\n\t\tconst element = readElement(parametersDer);\n\t\tif (element.tag !== 0x05 || element.length !== 0 || element.end !== parametersDer.length) {\n\t\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be DER NULL');\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be DER NULL');\n\t}\n}\n\nfunction requireAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer !== undefined) {\n\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be absent');\n\t}\n\treturn undefined;\n}\n\n/** Wrap a config in a success result. */\nfunction ok(value: VerifySignatureConfig): VerifySignatureConfigSuccess {\n\treturn { ok: true, value };\n}\n\n/** Build an unsupported-algorithm failure result. */\nfunction unsupported(algorithm: string, reason: string): VerifySignatureConfigFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_signature_algorithm_parameters',\n\t\treason: `${algorithm} parameters unsupported: ${reason}`,\n\t};\n}\n\nfunction verificationError(reason: string): VerifySignedDataFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'verification_error',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2GA,SAAgB,+BACf,GACA,GACA,GACA,GACA,IAAU,UACoB;CAC9B,QAAQ,GAAR;EACC,KAAK,EAAK,yBAAyB;GAClC,IAAM,IAAa,2CAClB,GACA,kBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,oBAAoB,GAAuB,WAAW,cAAc,CAAO,IAF1E;EAGT;EACA,KAAK,EAAK,yBAAyB;GAClC,IAAM,IAAa,2CAClB,GACA,kBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,oBAAoB,GAAuB,WAAW,cAAc,CAAO,IAF1E;EAGT;EACA,KAAK,EAAK,yBAAyB;GAClC,IAAM,IAAa,2CAClB,GACA,kBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,oBAAoB,GAAuB,WAAW,cAAc,CAAO,IAF1E;EAGT;EACA,KAAK,EAAK,WACT,O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,CAA+B;CAIxE,OAHK,EAAW,KAGT,oBACN,GACA,EAAW,MAAM,MACjB,OACA,GACA,EAAW,MAAM,UAClB,IARQ,YAAY,WAAW,EAAW,MAAM;AASjD;AAEA,SAAS,2CACR,GACA,GAC2C;CAC3C,IAAI,MAAkB,KAAA,GACrB,OAAO,YAAY,GAAW,2DAA2D;CAE1F,IAAI;EACH,IAAM,IAAU,EAAY,CAAa;EAIzC,OAHI,EAAQ,QAAQ,KAAQ,EAAQ,WAAW,KAAK,EAAQ,QAAQ,EAAc,SAC1E,YAAY,GAAW,2DAA2D,IAE1F;CACD,QAAQ;EACP,OAAO,YAAY,GAAW,2DAA2D;CAC1F;AACD;AAEA,SAAS,0CACR,GACA,GAC2C;CAC3C,IAAI,MAAkB,KAAA,GACrB,OAAO,YAAY,GAAW,yDAAyD;AAGzF;;AAGA,SAAS,GAAG,GAA4D;CACvE,OAAO;EAAE,IAAI;EAAM;CAAM;AAC1B;;AAGA,SAAS,YAAY,GAAmB,GAA8C;CACrF,OAAO;EACN,IAAI;EACJ,MAAM;EACN,QAAQ,GAAG,EAAU,2BAA2B;CACjD;AACD;AAEA,SAAS,kBAAkB,GAAyC;CACnE,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"sig-verify.js","names":[],"sources":["../../../src/internal/crypto/sig-verify.ts"],"sourcesContent":["/**\n * Signature-verification helpers that resolve parsed algorithm OIDs into WebCrypto\n * verification configuration for higher-level validators.\n *\n * @module\n */\n\nimport { toArrayBuffer } from '#micro509/internal/asn1/asn1';\nimport { readElement } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { alternateEcdsaSignatureEncoding } from '#micro509/internal/crypto/ecdsa';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { PublicKeyImportInput, RsaHash, RsaSignatureScheme } from '#micro509/keys/keys';\nimport { importSpkiDerOrThrow } from '#micro509/keys/keys';\n\nexport {\n\talternateEcdsaSignatureEncoding,\n\tconcatFixedWidth,\n\tderEcdsaSignatureToRaw,\n\trawEcdsaSignatureToDer,\n} from '#micro509/internal/crypto/ecdsa';\n\n/** Resolved WebCrypto parameters needed to verify a signature. */\nexport interface VerifySignatureConfig {\n\t/** Algorithm descriptor for importing the signer's public key via {@linkcode importSpkiDer}. */\n\treadonly importAlgorithm: PublicKeyImportInput;\n\t/** WebCrypto `verify()` algorithm parameter. */\n\treadonly verifyParams: Algorithm | EcdsaParams | RsaPssParams;\n\t/** When set, raw ECDSA signatures are this many bytes and may need DER/raw conversion. */\n\treadonly ecdsaRawSignatureBytes?: number;\n}\n\n/** Failure: the signature algorithm or its parameters are not supported. */\nexport interface VerifySignatureConfigFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_signature_algorithm_parameters';\n\t/** Human-readable explanation of why the algorithm is unsupported. */\n\treadonly reason: string;\n}\n\n/** Failure: signature verification could not run to completion. */\nexport interface VerifySignedDataFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'verification_error';\n\t/** Human-readable explanation of the verification failure. */\n\treadonly reason: string;\n}\n\n/** Success branch of {@linkcode VerifySignatureConfigResult}. */\nexport interface VerifySignatureConfigSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The resolved verification configuration. */\n\treadonly value: VerifySignatureConfig;\n}\n\n/** Result of resolving signature algorithm OIDs into a {@linkcode VerifySignatureConfig}. */\nexport type VerifySignatureConfigResult =\n\t| VerifySignatureConfigSuccess\n\t| VerifySignatureConfigFailure;\n\n/** Success branch of {@linkcode VerifySignedDataResult}. */\nexport interface VerifySignedDataSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** Whether the cryptographic signature is valid for the given data and key. */\n\treadonly valid: boolean;\n}\n\n/** Result of a full signature verification: validity, unsupported params, or a runtime verification failure. */\nexport type VerifySignedDataResult =\n\t| VerifySignedDataSuccess\n\t| VerifySignatureConfigFailure\n\t| VerifySignedDataFailure;\n\n/**\n * Resolve algorithm OIDs into a {@linkcode VerifySignatureConfig}.\n *\n * Throws on unsupported algorithms. Use {@linkcode getVerifySignatureConfigResult} for\n * a non-throwing variant.\n */\nexport function getVerifySignatureConfig(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfig {\n\tconst result = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tcontext,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.value;\n}\n\n/** Non-throwing variant of {@linkcode getVerifySignatureConfig} — returns a typed result union. */\nexport function getVerifySignatureConfigResult(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tswitch (signatureAlgorithmOid) {\n\t\tcase OIDS.sha256WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-256 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-256', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha384WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-384 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-384', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha512WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-512 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-512', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn requireRsaPssVerifyConfig(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\tpublicKeyAlgorithmOid,\n\t\t\t\tcontext,\n\t\t\t);\n\t\tcase OIDS.ecdsaWithSHA256: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-256',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-256', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA384: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-384',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-384', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA512: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-512',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-512', context);\n\t\t}\n\t\tcase OIDS.ed25519: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'Ed25519',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\tif (publicKeyAlgorithmOid !== OIDS.ed25519) {\n\t\t\t\treturn unsupported('Ed25519', `requires Ed25519 ${context} public key`);\n\t\t\t}\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ed25519' },\n\t\t\t\tverifyParams: { name: 'Ed25519' },\n\t\t\t});\n\t\t}\n\t\tdefault:\n\t\t\treturn unsupported(signatureAlgorithmOid, 'unrecognized signature algorithm OID');\n\t}\n}\n\n/** Validate that the public key OID is `rsaEncryption` and return an RSA verification config result. */\nexport function requireRsaPublicKey(\n\talgorithmOid: string,\n\thash: RsaHash,\n\tscheme: RsaSignatureScheme = 'pkcs1-v1_5',\n\tcontext = 'issuer',\n\tsaltLength?: number,\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.rsaEncryption) {\n\t\treturn unsupported('RSA', `requires RSA ${context} public key`);\n\t}\n\tconst verifyParams: Algorithm | RsaPssParams =\n\t\tscheme === 'pss'\n\t\t\t? { name: 'RSA-PSS', saltLength: saltLength ?? 0 }\n\t\t\t: { name: 'RSASSA-PKCS1-v1_5' };\n\treturn ok({ importAlgorithm: { kind: 'rsa', hash, scheme }, verifyParams });\n}\n\n/** Validate that the public key OID is `ecPublicKey`, resolve the curve, and return an ECDSA verification config result. */\nexport function requireEcPublicKey(\n\talgorithmOid: string,\n\tparametersOid: string | undefined,\n\thash: string,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.ecPublicKey) {\n\t\treturn unsupported('ECDSA', `requires EC ${context} public key`);\n\t}\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-256' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 64,\n\t\t\t});\n\t\tcase OIDS.secp384r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-384' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 96,\n\t\t\t});\n\t\tcase OIDS.secp521r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-521' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 132,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn unsupported('ECDSA', `unsupported EC curve OID: ${parametersOid ?? 'missing'}`);\n\t}\n}\n\n/** Return the raw ECDSA signature byte count (r + s) for a given curve OID, if supported. */\nexport function curveBytes(parametersOid: string | undefined): number | undefined {\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn 64;\n\t\tcase OIDS.secp384r1:\n\t\t\treturn 96;\n\t\tcase OIDS.secp521r1:\n\t\t\treturn 132;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Verify a signature against the signer's SPKI and the signed TBS bytes.\n *\n * Throws on unsupported algorithms. Use {@linkcode verifySignedDataDetailed} for\n * a non-throwing variant.\n */\nexport async function verifySignedData(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n): Promise<boolean> {\n\tconst result = await verifySignedDataDetailed(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tsubjectPublicKeyInfoDer,\n\t\tsignature,\n\t\tsignedData,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.valid;\n}\n\n/**\n * Non-throwing variant of {@linkcode verifySignedData} — returns a typed\n * {@linkcode VerifySignedDataResult} instead of throwing on unsupported algorithms\n * or runtime verification failures.\n *\n * Tries both DER and raw ECDSA encodings when the first attempt fails.\n */\nexport async function verifySignedDataDetailed(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n): Promise<VerifySignedDataResult> {\n\tconst config = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t);\n\tif (!config.ok) {\n\t\treturn config;\n\t}\n\ttry {\n\t\tconst key = await importSpkiDerOrThrow(subjectPublicKeyInfoDer, config.value.importAlgorithm);\n\t\tconst subtle = getCrypto().subtle;\n\t\tconst signatureView = toArrayBuffer(signature);\n\t\tconst dataView = toArrayBuffer(signedData);\n\t\tif (await subtle.verify(config.value.verifyParams, key, signatureView, dataView)) {\n\t\t\treturn { ok: true, valid: true };\n\t\t}\n\t\tif (config.value.ecdsaRawSignatureBytes !== undefined) {\n\t\t\tconst alternate = alternateEcdsaSignatureEncoding(\n\t\t\t\tsignature,\n\t\t\t\tconfig.value.ecdsaRawSignatureBytes / 2,\n\t\t\t);\n\t\t\tif (alternate !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalid: await subtle.verify(\n\t\t\t\t\t\tconfig.value.verifyParams,\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\ttoArrayBuffer(alternate),\n\t\t\t\t\t\tdataView,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn { ok: true, valid: false };\n\t} catch (error) {\n\t\treturn verificationError(\n\t\t\terror instanceof Error ? error.message : 'signature verification failed',\n\t\t);\n\t}\n}\n\n/** Parse RSA-PSS algorithm parameters and build a verification config, or return failure. */\nfunction requireRsaPssVerifyConfig(\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tcontext: string,\n): VerifySignatureConfigResult {\n\tconst parameters = parseRsaPssParameters(signatureAlgorithmParametersDer);\n\tif (!parameters.ok) {\n\t\treturn unsupported('RSA-PSS', parameters.reason);\n\t}\n\treturn requireRsaPublicKey(\n\t\tpublicKeyAlgorithmOid,\n\t\tparameters.value.hash,\n\t\t'pss',\n\t\tcontext,\n\t\tparameters.value.saltLength,\n\t);\n}\n\n/** RFC 4055 §5 requires generators to encode NULL and implementations to accept absent parameters too. */\nfunction requireDerNullOrAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer === undefined) {\n\t\treturn undefined;\n\t}\n\tconst reason = 'signature AlgorithmIdentifier parameters must be DER NULL or absent';\n\ttry {\n\t\tconst element = readElement(parametersDer);\n\t\tif (element.tag !== 0x05 || element.length !== 0 || element.end !== parametersDer.length) {\n\t\t\treturn unsupported(algorithm, reason);\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn unsupported(algorithm, reason);\n\t}\n}\n\nfunction requireAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer !== undefined) {\n\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be absent');\n\t}\n\treturn undefined;\n}\n\n/** Wrap a config in a success result. */\nfunction ok(value: VerifySignatureConfig): VerifySignatureConfigSuccess {\n\treturn { ok: true, value };\n}\n\n/** Build an unsupported-algorithm failure result. */\nfunction unsupported(algorithm: string, reason: string): VerifySignatureConfigFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_signature_algorithm_parameters',\n\t\treason: `${algorithm} parameters unsupported: ${reason}`,\n\t};\n}\n\nfunction verificationError(reason: string): VerifySignedDataFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'verification_error',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2GA,SAAgB,+BACf,GACA,GACA,GACA,GACA,IAAU,UACoB;CAC9B,QAAQ,GAAR;EACC,KAAK,EAAK,yBAAyB;GAClC,IAAM,IAAa,mDAClB,GACA,kBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,oBAAoB,GAAuB,WAAW,cAAc,CAAO,IAF1E;EAGT;EACA,KAAK,EAAK,yBAAyB;GAClC,IAAM,IAAa,mDAClB,GACA,kBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,oBAAoB,GAAuB,WAAW,cAAc,CAAO,IAF1E;EAGT;EACA,KAAK,EAAK,yBAAyB;GAClC,IAAM,IAAa,mDAClB,GACA,kBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,oBAAoB,GAAuB,WAAW,cAAc,CAAO,IAF1E;EAGT;EACA,KAAK,EAAK,WACT,OAAO,0BACN,GACA,GACA,CACD;EACD,KAAK,EAAK,iBAAiB;GAC1B,IAAM,IAAa,0CAClB,GACA,oBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,mBAAmB,GAAuB,GAAwB,WAAW,CAAO,IAFnF;EAGT;EACA,KAAK,EAAK,iBAAiB;GAC1B,IAAM,IAAa,0CAClB,GACA,oBACD;GAIA,OAHI,MAAe,KAAA,IAGZ,mBAAmB,G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Q,KAAQ,EAAQ,WAAW,KAAK,EAAQ,QAAQ,EAAc,SAC1E,YAAY,GAAW,CAAM,IAErC;CACD,QAAQ;EACP,OAAO,YAAY,GAAW,CAAM;CACrC;AACD;AAEA,SAAS,0CACR,GACA,GAC2C;CAC3C,IAAI,MAAkB,KAAA,GACrB,OAAO,YAAY,GAAW,yDAAyD;AAGzF;;AAGA,SAAS,GAAG,GAA4D;CACvE,OAAO;EAAE,IAAI;EAAM;CAAM;AAC1B;;AAGA,SAAS,YAAY,GAAmB,GAA8C;CACrF,OAAO;EACN,IAAI;EACJ,MAAM;EACN,QAAQ,GAAG,EAAU,2BAA2B;CACjD;AACD;AAEA,SAAS,kBAAkB,GAAyC;CACnE,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
@@ -9,7 +9,13 @@ function base64Encode(e) {
|
|
|
9
9
|
function base64Decode(e) {
|
|
10
10
|
let t = atob(e), n = new Uint8Array(t.length);
|
|
11
11
|
for (let e = 0; e < t.length; e++) n[e] = t.charCodeAt(e);
|
|
12
|
-
return n;
|
|
12
|
+
return assertCanonicalFinalQuantum(e, n), n;
|
|
13
|
+
}
|
|
14
|
+
/** RFC 4648 §4 completes a final quantum with pad characters and bits of value zero. */
|
|
15
|
+
function assertCanonicalFinalQuantum(e, t) {
|
|
16
|
+
let n = e.replace(/[\t\n\f\r ]/g, "");
|
|
17
|
+
if (n.length % 4 != 0) throw Error("Base64 final quantum is missing its padding");
|
|
18
|
+
if (n.length !== 0 && base64Encode(t.slice(t.length - ((t.length - 1) % 3 + 1))) !== n.slice(-4)) throw Error("Base64 final quantum has non-zero pad bits");
|
|
13
19
|
}
|
|
14
20
|
//#endregion
|
|
15
21
|
export { base64Decode, base64Encode };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base64.js","names":[],"sources":["../../../src/internal/shared/base64.ts"],"sourcesContent":["/** Encode raw bytes as standard base64 without line breaks. */\nexport function base64Encode(bytes: Uint8Array): string {\n\tconst parts: string[] = [];\n\tfor (const byte of bytes) {\n\t\tparts.push(String.fromCharCode(byte));\n\t}\n\treturn btoa(parts.join(''));\n}\n\n/** Decode a standard base64 string into raw bytes. */\nexport function base64Decode(value: string): Uint8Array {\n\tconst binary = atob(value);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n"],"mappings":";;AACA,SAAgB,aAAa,GAA2B;CACvD,IAAM,IAAkB,CAAC;CACzB,KAAK,IAAM,KAAQ,GAClB,EAAM,KAAK,OAAO,aAAa,CAAI,CAAC;CAErC,OAAO,KAAK,EAAM,KAAK,EAAE,CAAC;AAC3B;;AAGA,SAAgB,aAAa,GAA2B;CACvD,IAAM,IAAS,KAAK,CAAK,GACnB,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAClC,EAAM,KAAK,EAAO,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"base64.js","names":[],"sources":["../../../src/internal/shared/base64.ts"],"sourcesContent":["/** Encode raw bytes as standard base64 without line breaks. */\nexport function base64Encode(bytes: Uint8Array): string {\n\tconst parts: string[] = [];\n\tfor (const byte of bytes) {\n\t\tparts.push(String.fromCharCode(byte));\n\t}\n\treturn btoa(parts.join(''));\n}\n\n/** Decode a standard base64 string into raw bytes. */\nexport function base64Decode(value: string): Uint8Array {\n\tconst binary = atob(value);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\tassertCanonicalFinalQuantum(value, bytes);\n\treturn bytes;\n}\n\n/** RFC 4648 §4 completes a final quantum with pad characters and bits of value zero. */\nfunction assertCanonicalFinalQuantum(value: string, bytes: Uint8Array): void {\n\tconst compact = value.replace(/[\\t\\n\\f\\r ]/g, '');\n\tif (compact.length % 4 !== 0) {\n\t\tthrow new Error('Base64 final quantum is missing its padding');\n\t}\n\tif (compact.length === 0) {\n\t\treturn;\n\t}\n\tconst finalQuantum = bytes.slice(bytes.length - (((bytes.length - 1) % 3) + 1));\n\tif (base64Encode(finalQuantum) !== compact.slice(-4)) {\n\t\tthrow new Error('Base64 final quantum has non-zero pad bits');\n\t}\n}\n"],"mappings":";;AACA,SAAgB,aAAa,GAA2B;CACvD,IAAM,IAAkB,CAAC;CACzB,KAAK,IAAM,KAAQ,GAClB,EAAM,KAAK,OAAO,aAAa,CAAI,CAAC;CAErC,OAAO,KAAK,EAAM,KAAK,EAAE,CAAC;AAC3B;;AAGA,SAAgB,aAAa,GAA2B;CACvD,IAAM,IAAS,KAAK,CAAK,GACnB,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAClC,EAAM,KAAK,EAAO,WAAW,CAAC;CAG/B,OADA,4BAA4B,GAAO,CAAK,GACjC;AACR;;AAGA,SAAS,4BAA4B,GAAe,GAAyB;CAC5E,IAAM,IAAU,EAAM,QAAQ,gBAAgB,EAAE;CAChD,IAAI,EAAQ,SAAS,KAAM,GAC1B,MAAU,MAAM,6CAA6C;CAE1D,MAAQ,WAAW,KAInB,aADiB,EAAM,MAAM,EAAM,WAAY,EAAM,SAAS,KAAK,IAAK,EAChD,CAAC,MAAM,EAAQ,MAAM,EAAE,GAClD,MAAU,MAAM,4CAA4C;AAE9D"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ParsedName } from "../../x509/parse.js";
|
|
2
|
+
//#region src/internal/shared/dn.d.ts
|
|
3
|
+
/** RFC 5280 [§7.1](https://datatracker.ietf.org/doc/html/rfc5280#section-7.1) semantic equality: same RDN count, each pair matches attribute-by-attribute. */
|
|
4
|
+
declare function compareDistinguishedNames(left: ParsedName, right: ParsedName): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Produces a deterministic string key for a parsed DN, suitable as a Map key.
|
|
7
|
+
* Semantically equal DNs (per RFC 5280 [§7.1](https://datatracker.ietf.org/doc/html/rfc5280#section-7.1)) produce identical keys.
|
|
8
|
+
*
|
|
9
|
+
* Format: RDNs joined by `,`, attributes within each RDN sorted by OID then by prepared value, joined by `+`.
|
|
10
|
+
*/
|
|
11
|
+
declare function canonicalDnKey(name: ParsedName): string;
|
|
12
|
+
/** True when `subject` equals or is subordinate to `constraint` (RDN prefix match). */
|
|
13
|
+
declare function isWithinDirectoryNameSubtree(subject: ParsedName, constraint: ParsedName): boolean;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree };
|
|
16
|
+
//# sourceMappingURL=dn.d.ts.map
|