micro509 0.7.0 → 0.7.2

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 CHANGED
@@ -8,9 +8,11 @@
8
8
 
9
9
  [![NPM](https://img.shields.io/npm/v/micro509?logo=npm&labelColor=CB3837&color=black)][npm]
10
10
  [![JSR](https://img.shields.io/jsr/v/@kjanat/micro509?logoColor=083344&logo=jsr&logoSize=auto&label=&labelColor=f7df1e&color=black)][jsr]
11
+ [![Socket](https://badge.socket.dev/npm/package/micro509)][socket]
11
12
 
12
13
  [npm]: https://npm.im/micro509
13
14
  [jsr]: https://jsr.io/@kjanat/micro509
15
+ [socket]: https://socket.dev/npm/package/micro509
14
16
 
15
17
  A zero-dependency TypeScript PKI toolkit for certificates, verification, revocation, and PKCS workflows.
16
18
 
@@ -1,2 +1,2 @@
1
- import{integer as e,readSequenceChildren as t,sequence as n}from"../asn1/der.js";function r(e,n){let r=t(e),i=r[0],a=r[1];if(i===void 0||a===void 0||r.length!==2)throw Error(`Malformed ECDSA DER signature`);if(i.tag!==2||a.tag!==2)throw Error(`ECDSA DER signature must contain two INTEGERs`);return o(s(i.value),s(a.value),n)}function i(t,r){if(t.length!==r*2)throw Error(`Unexpected ECDSA raw signature length`);return n([e(t.slice(0,r)),e(t.slice(r))])}function a(e,t){if(e[0]===48)try{return r(e,t)}catch{}try{return i(e,t)}catch{return}}function o(e,t,n){if(e.length>n||t.length>n)throw Error(`ECDSA signature integer too large`);let r=new Uint8Array(n*2);return r.set(e,n-e.length),r.set(t,r.length-t.length),r}function s(e){let t=0;for(;t<e.length-1&&e[t]===0;)t+=1;return e.slice(t)}export{a as alternateEcdsaSignatureEncoding,o as concatFixedWidth,r as derEcdsaSignatureToRaw,i as rawEcdsaSignatureToDer};
1
+ import{integer as e,readSequenceChildren as t,sequence as n}from"../asn1/der.js";function r(e,n){let r=t(e),i=r[0],a=r[1];if(i===void 0||a===void 0||r.length!==2)throw Error(`Malformed ECDSA DER signature`);if(i.tag!==2||a.tag!==2)throw Error(`ECDSA DER signature must contain two INTEGERs`);return s(c(i.value),c(a.value),n)}function i(t,r){if(t.length!==r*2)throw Error(`Unexpected ECDSA raw signature length`);return n([e(t.slice(0,r)),e(t.slice(r))])}function a(e,t){return e.length===t?i(e,t/2):e}function o(e,t){if(e[0]===48)try{return r(e,t)}catch{}try{return i(e,t)}catch{return}}function s(e,t,n){if(e.length>n||t.length>n)throw Error(`ECDSA signature integer too large`);let r=new Uint8Array(n*2);return r.set(e,n-e.length),r.set(t,r.length-t.length),r}function c(e){let t=0;for(;t<e.length-1&&e[t]===0;)t+=1;return e.slice(t)}export{o as alternateEcdsaSignatureEncoding,s as concatFixedWidth,r as derEcdsaSignatureToRaw,a as ecdsaSignatureToDer,i as rawEcdsaSignatureToDer};
2
2
  //# sourceMappingURL=ecdsa.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ecdsa.js","names":[],"sources":["../../../src/internal/crypto/ecdsa.ts"],"sourcesContent":["/**\n * ECDSA signature encoding conversion between ASN.1 DER (r, s INTEGER) and the\n * fixed-width raw format used by WebCrypto.\n *\n * @module\n */\n\nimport { integer, readSequenceChildren, sequence } from '#micro509/internal/asn1/der.ts';\n\n/** Convert a DER-encoded ECDSA signature (SEQUENCE of two INTEGERs) to fixed-width raw `r || s`. */\nexport function derEcdsaSignatureToRaw(signature: Uint8Array, partLength: number): Uint8Array {\n\tconst parts = readSequenceChildren(signature);\n\tconst r = parts[0];\n\tconst s = parts[1];\n\tif (r === undefined || s === undefined || parts.length !== 2) {\n\t\tthrow new Error('Malformed ECDSA DER signature');\n\t}\n\tif (r.tag !== 0x02 || s.tag !== 0x02) {\n\t\tthrow new Error('ECDSA DER signature must contain two INTEGERs');\n\t}\n\treturn concatFixedWidth(trimLeadingZero(r.value), trimLeadingZero(s.value), partLength);\n}\n\n/** Convert a fixed-width raw `r || s` ECDSA signature to DER-encoded SEQUENCE of two INTEGERs. */\nexport function rawEcdsaSignatureToDer(signature: Uint8Array, partLength: number): Uint8Array {\n\tif (signature.length !== partLength * 2) {\n\t\tthrow new Error('Unexpected ECDSA raw signature length');\n\t}\n\treturn sequence([integer(signature.slice(0, partLength)), integer(signature.slice(partLength))]);\n}\n\n/**\n * Try the opposite ECDSA encoding: DER→raw or raw→DER.\n *\n * Returns `undefined` if conversion fails, letting callers retry verification\n * with the alternate encoding.\n */\nexport function alternateEcdsaSignatureEncoding(\n\tsignature: Uint8Array,\n\tpartLength: number,\n): Uint8Array | undefined {\n\t// Try DER→raw first if it looks like DER (starts with SEQUENCE tag)\n\tif (signature[0] === 0x30) {\n\t\ttry {\n\t\t\treturn derEcdsaSignatureToRaw(signature, partLength);\n\t\t} catch {\n\t\t\t// Fall through to try raw→DER\n\t\t}\n\t}\n\t// Try raw→DER\n\ttry {\n\t\treturn rawEcdsaSignatureToDer(signature, partLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Left-pad and concatenate `r` and `s` into a fixed-width `partLength * 2` byte buffer. */\nexport function concatFixedWidth(\n\tleft: Uint8Array,\n\tright: Uint8Array,\n\tpartLength: number,\n): Uint8Array {\n\tif (left.length > partLength || right.length > partLength) {\n\t\tthrow new Error('ECDSA signature integer too large');\n\t}\n\tconst out = new Uint8Array(partLength * 2);\n\tout.set(left, partLength - left.length);\n\tout.set(right, out.length - right.length);\n\treturn out;\n}\n\n/** Strip leading zero bytes from a DER INTEGER value, keeping at least one byte. */\nfunction trimLeadingZero(bytes: Uint8Array): Uint8Array {\n\tlet index = 0;\n\twhile (index < bytes.length - 1 && bytes[index] === 0) {\n\t\tindex += 1;\n\t}\n\treturn bytes.slice(index);\n}\n"],"mappings":"iFAUA,SAAgB,EAAuB,EAAuB,EAAgC,CAC7F,IAAM,EAAQ,EAAqB,CAAS,EACtC,EAAI,EAAM,GACV,EAAI,EAAM,GAChB,GAAI,IAAM,IAAA,IAAa,IAAM,IAAA,IAAa,EAAM,SAAW,EAC1D,MAAU,MAAM,+BAA+B,EAEhD,GAAI,EAAE,MAAQ,GAAQ,EAAE,MAAQ,EAC/B,MAAU,MAAM,+CAA+C,EAEhE,OAAO,EAAiB,EAAgB,EAAE,KAAK,EAAG,EAAgB,EAAE,KAAK,EAAG,CAAU,CACvF,CAGA,SAAgB,EAAuB,EAAuB,EAAgC,CAC7F,GAAI,EAAU,SAAW,EAAa,EACrC,MAAU,MAAM,uCAAuC,EAExD,OAAO,EAAS,CAAC,EAAQ,EAAU,MAAM,EAAG,CAAU,CAAC,EAAG,EAAQ,EAAU,MAAM,CAAU,CAAC,CAAC,CAAC,CAChG,CAQA,SAAgB,EACf,EACA,EACyB,CAEzB,GAAI,EAAU,KAAO,GACpB,GAAI,CACH,OAAO,EAAuB,EAAW,CAAU,CACpD,MAAQ,CAER,CAGD,GAAI,CACH,OAAO,EAAuB,EAAW,CAAU,CACpD,MAAQ,CACP,MACD,CACD,CAGA,SAAgB,EACf,EACA,EACA,EACa,CACb,GAAI,EAAK,OAAS,GAAc,EAAM,OAAS,EAC9C,MAAU,MAAM,mCAAmC,EAEpD,IAAM,EAAM,IAAI,WAAW,EAAa,CAAC,EAGzC,OAFA,EAAI,IAAI,EAAM,EAAa,EAAK,MAAM,EACtC,EAAI,IAAI,EAAO,EAAI,OAAS,EAAM,MAAM,EACjC,CACR,CAGA,SAAS,EAAgB,EAA+B,CACvD,IAAI,EAAQ,EACZ,KAAO,EAAQ,EAAM,OAAS,GAAK,EAAM,KAAW,GACnD,GAAS,EAEV,OAAO,EAAM,MAAM,CAAK,CACzB"}
1
+ {"version":3,"file":"ecdsa.js","names":[],"sources":["../../../src/internal/crypto/ecdsa.ts"],"sourcesContent":["/**\n * ECDSA signature encoding conversion between ASN.1 DER (r, s INTEGER) and the\n * fixed-width raw format used by WebCrypto.\n *\n * @module\n */\n\nimport { integer, readSequenceChildren, sequence } from '#micro509/internal/asn1/der.ts';\n\n/** Convert a DER-encoded ECDSA signature (SEQUENCE of two INTEGERs) to fixed-width raw `r || s`. */\nexport function derEcdsaSignatureToRaw(signature: Uint8Array, partLength: number): Uint8Array {\n\tconst parts = readSequenceChildren(signature);\n\tconst r = parts[0];\n\tconst s = parts[1];\n\tif (r === undefined || s === undefined || parts.length !== 2) {\n\t\tthrow new Error('Malformed ECDSA DER signature');\n\t}\n\tif (r.tag !== 0x02 || s.tag !== 0x02) {\n\t\tthrow new Error('ECDSA DER signature must contain two INTEGERs');\n\t}\n\treturn concatFixedWidth(trimLeadingZero(r.value), trimLeadingZero(s.value), partLength);\n}\n\n/** Convert a fixed-width raw `r || s` ECDSA signature to DER-encoded SEQUENCE of two INTEGERs. */\nexport function rawEcdsaSignatureToDer(signature: Uint8Array, partLength: number): Uint8Array {\n\tif (signature.length !== partLength * 2) {\n\t\tthrow new Error('Unexpected ECDSA raw signature length');\n\t}\n\treturn sequence([integer(signature.slice(0, partLength)), integer(signature.slice(partLength))]);\n}\n\n/**\n * Normalize a WebCrypto ECDSA signature to DER.\n *\n * Spec-compliant WebCrypto always returns fixed-width raw `r || s`\n * (exactly `rawSignatureBytes` long), which needs conversion. Detection is\n * by length, never by sniffing the first byte: a raw signature whose `r`\n * happens to start with `0x30` (1-in-256 per signature) is\n * indistinguishable from DER by tag, and embedding it unconverted produces\n * a certificate/CRL that OpenSSL rejects with a signature failure.\n */\nexport function ecdsaSignatureToDer(signature: Uint8Array, rawSignatureBytes: number): Uint8Array {\n\tif (signature.length === rawSignatureBytes) {\n\t\treturn rawEcdsaSignatureToDer(signature, rawSignatureBytes / 2);\n\t}\n\treturn signature;\n}\n\n/**\n * Try the opposite ECDSA encoding: DER→raw or raw→DER.\n *\n * Returns `undefined` if conversion fails, letting callers retry verification\n * with the alternate encoding.\n */\nexport function alternateEcdsaSignatureEncoding(\n\tsignature: Uint8Array,\n\tpartLength: number,\n): Uint8Array | undefined {\n\t// Try DER→raw first if it looks like DER (starts with SEQUENCE tag)\n\tif (signature[0] === 0x30) {\n\t\ttry {\n\t\t\treturn derEcdsaSignatureToRaw(signature, partLength);\n\t\t} catch {\n\t\t\t// Fall through to try raw→DER\n\t\t}\n\t}\n\t// Try raw→DER\n\ttry {\n\t\treturn rawEcdsaSignatureToDer(signature, partLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Left-pad and concatenate `r` and `s` into a fixed-width `partLength * 2` byte buffer. */\nexport function concatFixedWidth(\n\tleft: Uint8Array,\n\tright: Uint8Array,\n\tpartLength: number,\n): Uint8Array {\n\tif (left.length > partLength || right.length > partLength) {\n\t\tthrow new Error('ECDSA signature integer too large');\n\t}\n\tconst out = new Uint8Array(partLength * 2);\n\tout.set(left, partLength - left.length);\n\tout.set(right, out.length - right.length);\n\treturn out;\n}\n\n/** Strip leading zero bytes from a DER INTEGER value, keeping at least one byte. */\nfunction trimLeadingZero(bytes: Uint8Array): Uint8Array {\n\tlet index = 0;\n\twhile (index < bytes.length - 1 && bytes[index] === 0) {\n\t\tindex += 1;\n\t}\n\treturn bytes.slice(index);\n}\n"],"mappings":"iFAUA,SAAgB,EAAuB,EAAuB,EAAgC,CAC7F,IAAM,EAAQ,EAAqB,CAAS,EACtC,EAAI,EAAM,GACV,EAAI,EAAM,GAChB,GAAI,IAAM,IAAA,IAAa,IAAM,IAAA,IAAa,EAAM,SAAW,EAC1D,MAAU,MAAM,+BAA+B,EAEhD,GAAI,EAAE,MAAQ,GAAQ,EAAE,MAAQ,EAC/B,MAAU,MAAM,+CAA+C,EAEhE,OAAO,EAAiB,EAAgB,EAAE,KAAK,EAAG,EAAgB,EAAE,KAAK,EAAG,CAAU,CACvF,CAGA,SAAgB,EAAuB,EAAuB,EAAgC,CAC7F,GAAI,EAAU,SAAW,EAAa,EACrC,MAAU,MAAM,uCAAuC,EAExD,OAAO,EAAS,CAAC,EAAQ,EAAU,MAAM,EAAG,CAAU,CAAC,EAAG,EAAQ,EAAU,MAAM,CAAU,CAAC,CAAC,CAAC,CAChG,CAYA,SAAgB,EAAoB,EAAuB,EAAuC,CAIjG,OAHI,EAAU,SAAW,EACjB,EAAuB,EAAW,EAAoB,CAAC,EAExD,CACR,CAQA,SAAgB,EACf,EACA,EACyB,CAEzB,GAAI,EAAU,KAAO,GACpB,GAAI,CACH,OAAO,EAAuB,EAAW,CAAU,CACpD,MAAQ,CAER,CAGD,GAAI,CACH,OAAO,EAAuB,EAAW,CAAU,CACpD,MAAQ,CACP,MACD,CACD,CAGA,SAAgB,EACf,EACA,EACA,EACa,CACb,GAAI,EAAK,OAAS,GAAc,EAAM,OAAS,EAC9C,MAAU,MAAM,mCAAmC,EAEpD,IAAM,EAAM,IAAI,WAAW,EAAa,CAAC,EAGzC,OAFA,EAAI,IAAI,EAAM,EAAa,EAAK,MAAM,EACtC,EAAI,IAAI,EAAO,EAAI,OAAS,EAAM,MAAM,EACjC,CACR,CAGA,SAAS,EAAgB,EAA+B,CACvD,IAAI,EAAQ,EACZ,KAAO,EAAQ,EAAM,OAAS,GAAK,EAAM,KAAW,GACnD,GAAS,EAEV,OAAO,EAAM,MAAM,CAAK,CACzB"}
@@ -1,2 +1,2 @@
1
- import{nullValue as e,objectIdentifier as t,sequence as n}from"../asn1/der.js";import{OIDS as r}from"../asn1/oids.js";import{getCrypto as i}from"./webcrypto.js";import{encodeRsaPssParameters as a,rsaPssParametersForHash as o}from"./rsa-pss.js";import{rawEcdsaSignatureToDer as s}from"./ecdsa.js";function c(t,n={}){let i=t.algorithm;if(n.kind===`rsa-pss`)return l(t,n.saltLength);if(i.name===`RSASSA-PKCS1-v1_5`){if(!f(i))throw Error(`RSA key is missing hash metadata`);switch(i.hash.name){case`SHA-256`:return{algorithmOid:r.sha256WithRSAEncryption,parameters:e(),signParams:{name:`RSASSA-PKCS1-v1_5`}};case`SHA-384`:return{algorithmOid:r.sha384WithRSAEncryption,parameters:e(),signParams:{name:`RSASSA-PKCS1-v1_5`}};case`SHA-512`:return{algorithmOid:r.sha512WithRSAEncryption,parameters:e(),signParams:{name:`RSASSA-PKCS1-v1_5`}};default:throw Error(`Unsupported RSA hash: ${i.hash.name}`)}}if(i.name===`RSA-PSS`)throw Error(`RSA-PSS signing requires an explicit signature profile`);if(i.name===`ECDSA`){if(!p(i))throw Error(`ECDSA key is missing namedCurve metadata`);switch(i.namedCurve){case`P-256`:return{algorithmOid:r.ecdsaWithSHA256,signParams:{name:`ECDSA`,hash:`SHA-256`},ecdsaRawSignatureBytes:64};case`P-384`:return{algorithmOid:r.ecdsaWithSHA384,signParams:{name:`ECDSA`,hash:`SHA-384`},ecdsaRawSignatureBytes:96};case`P-521`:return{algorithmOid:r.ecdsaWithSHA512,signParams:{name:`ECDSA`,hash:`SHA-512`},ecdsaRawSignatureBytes:132};default:throw Error(`Unsupported curve: ${i.namedCurve}`)}}if(i.name===`Ed25519`)return{algorithmOid:r.ed25519,signParams:{name:`Ed25519`}};throw Error(`Unsupported signing key algorithm: ${i.name}`)}function l(e,t){let n=e.algorithm;if(n.name!==`RSA-PSS`)throw Error(`RSA-PSS signature profile requires an RSA-PSS private key`);if(!f(n))throw Error(`RSA-PSS key is missing hash metadata`);let i=m(n.hash.name),s=o(i);if(t!==void 0&&t!==s.saltLength)throw Error(`Unsupported RSA-PSS saltLength ${t} for ${i}; expected ${s.saltLength}`);return{algorithmOid:r.rsassaPss,parameters:a(s),signParams:{name:`RSA-PSS`,saltLength:s.saltLength}}}function u(e){let r=[t(e.algorithmOid)];return e.parameters!==void 0&&r.push(e.parameters),n(r)}async function d(e,t,n){let r=new Uint8Array(n),a=new Uint8Array(await i().subtle.sign(t.signParams,e,r));return t.ecdsaRawSignatureBytes!==void 0&&a[0]!==48?s(a,t.ecdsaRawSignatureBytes/2):a}function f(e){return`hash`in e}function p(e){return`namedCurve`in e}function m(e){switch(e){case`SHA-256`:return`SHA-256`;case`SHA-384`:return`SHA-384`;case`SHA-512`:return`SHA-512`;default:throw Error(`Unsupported RSA hash: ${e}`)}}export{u as encodeAlgorithmIdentifier,c as getSignatureAlgorithm,d as signBytes};
1
+ import{nullValue as e,objectIdentifier as t,sequence as n}from"../asn1/der.js";import{OIDS as r}from"../asn1/oids.js";import{getCrypto as i}from"./webcrypto.js";import{encodeRsaPssParameters as a,rsaPssParametersForHash as o}from"./rsa-pss.js";import{ecdsaSignatureToDer as s}from"./ecdsa.js";function c(t,n={}){let i=t.algorithm;if(n.kind===`rsa-pss`)return l(t,n.saltLength);if(i.name===`RSASSA-PKCS1-v1_5`){if(!f(i))throw Error(`RSA key is missing hash metadata`);switch(i.hash.name){case`SHA-256`:return{algorithmOid:r.sha256WithRSAEncryption,parameters:e(),signParams:{name:`RSASSA-PKCS1-v1_5`}};case`SHA-384`:return{algorithmOid:r.sha384WithRSAEncryption,parameters:e(),signParams:{name:`RSASSA-PKCS1-v1_5`}};case`SHA-512`:return{algorithmOid:r.sha512WithRSAEncryption,parameters:e(),signParams:{name:`RSASSA-PKCS1-v1_5`}};default:throw Error(`Unsupported RSA hash: ${i.hash.name}`)}}if(i.name===`RSA-PSS`)throw Error(`RSA-PSS signing requires an explicit signature profile`);if(i.name===`ECDSA`){if(!p(i))throw Error(`ECDSA key is missing namedCurve metadata`);switch(i.namedCurve){case`P-256`:return{algorithmOid:r.ecdsaWithSHA256,signParams:{name:`ECDSA`,hash:`SHA-256`},ecdsaRawSignatureBytes:64};case`P-384`:return{algorithmOid:r.ecdsaWithSHA384,signParams:{name:`ECDSA`,hash:`SHA-384`},ecdsaRawSignatureBytes:96};case`P-521`:return{algorithmOid:r.ecdsaWithSHA512,signParams:{name:`ECDSA`,hash:`SHA-512`},ecdsaRawSignatureBytes:132};default:throw Error(`Unsupported curve: ${i.namedCurve}`)}}if(i.name===`Ed25519`)return{algorithmOid:r.ed25519,signParams:{name:`Ed25519`}};throw Error(`Unsupported signing key algorithm: ${i.name}`)}function l(e,t){let n=e.algorithm;if(n.name!==`RSA-PSS`)throw Error(`RSA-PSS signature profile requires an RSA-PSS private key`);if(!f(n))throw Error(`RSA-PSS key is missing hash metadata`);let i=m(n.hash.name),s=o(i);if(t!==void 0&&t!==s.saltLength)throw Error(`Unsupported RSA-PSS saltLength ${t} for ${i}; expected ${s.saltLength}`);return{algorithmOid:r.rsassaPss,parameters:a(s),signParams:{name:`RSA-PSS`,saltLength:s.saltLength}}}function u(e){let r=[t(e.algorithmOid)];return e.parameters!==void 0&&r.push(e.parameters),n(r)}async function d(e,t,n){let r=new Uint8Array(n),a=new Uint8Array(await i().subtle.sign(t.signParams,e,r));return t.ecdsaRawSignatureBytes===void 0?a:s(a,t.ecdsaRawSignatureBytes)}function f(e){return`hash`in e}function p(e){return`namedCurve`in e}function m(e){switch(e){case`SHA-256`:return`SHA-256`;case`SHA-384`:return`SHA-384`;case`SHA-512`:return`SHA-512`;default:throw Error(`Unsupported RSA hash: ${e}`)}}export{u as encodeAlgorithmIdentifier,c as getSignatureAlgorithm,d as signBytes};
2
2
  //# sourceMappingURL=signing.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"signing.js","names":[],"sources":["../../../src/internal/crypto/signing.ts"],"sourcesContent":["/**\n * Signing helpers that map WebCrypto keys and signature profiles to on-wire\n * `AlgorithmIdentifier` values. Used by certificate and CSR builders.\n *\n * @module\n */\n\nimport { nullValue, objectIdentifier, sequence } from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { rawEcdsaSignatureToDer } from './ecdsa.ts';\nimport { encodeRsaPssParameters, type RsaPssHash, rsaPssParametersForHash } from './rsa-pss.ts';\nimport { getCrypto } from './webcrypto.ts';\n\n/**\n * Controls how the signature algorithm is chosen.\n *\n * `'auto'` (default) infers the algorithm from the key. `'rsa-pss'` forces RSA-PSS\n * padding and requires an RSA-PSS private key.\n */\nexport type SignatureProfileInput =\n\t| {\n\t\t\t/** Infer the signature algorithm from the private key. */\n\t\t\treadonly kind?: 'auto';\n\t }\n\t| {\n\t\t\t/** Force RSA-PSS padding. */\n\t\t\treadonly kind: 'rsa-pss';\n\t\t\t/** Salt length in bytes. Must match the key's hash digest size. */\n\t\t\treadonly saltLength?: 32 | 48 | 64;\n\t };\n\n/** Resolved signature algorithm: the OID/parameters for DER encoding and the WebCrypto sign params. */\nexport interface SignatureAlgorithmIdentifier {\n\t/** ASN.1 OID of the signature algorithm (e.g. sha256WithRSAEncryption). */\n\treadonly algorithmOid: string;\n\t/** DER-encoded algorithm parameters, if the algorithm requires them (e.g. RSA-PSS). */\n\treadonly parameters?: Uint8Array;\n\t/** WebCrypto `sign()` algorithm parameter. */\n\treadonly signParams: Algorithm | EcdsaParams | RsaPssParams;\n\t/** When set, the raw ECDSA signature is this many bytes and must be DER-converted. */\n\treadonly ecdsaRawSignatureBytes?: number;\n}\n\n/** Resolve a private key and optional profile into a {@linkcode SignatureAlgorithmIdentifier}. */\nexport function getSignatureAlgorithm(\n\tprivateKey: CryptoKey,\n\tprofile: SignatureProfileInput = {},\n): SignatureAlgorithmIdentifier {\n\tconst algorithm = privateKey.algorithm;\n\tif (profile.kind === 'rsa-pss') {\n\t\treturn getRsaPssSignatureAlgorithm(privateKey, profile.saltLength);\n\t}\n\tif (algorithm.name === 'RSASSA-PKCS1-v1_5') {\n\t\tif (!hasHash(algorithm)) {\n\t\t\tthrow new Error('RSA key is missing hash metadata');\n\t\t}\n\t\tswitch (algorithm.hash.name) {\n\t\t\tcase 'SHA-256':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.sha256WithRSAEncryption,\n\t\t\t\t\tparameters: nullValue(),\n\t\t\t\t\tsignParams: { name: 'RSASSA-PKCS1-v1_5' },\n\t\t\t\t};\n\t\t\tcase 'SHA-384':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.sha384WithRSAEncryption,\n\t\t\t\t\tparameters: nullValue(),\n\t\t\t\t\tsignParams: { name: 'RSASSA-PKCS1-v1_5' },\n\t\t\t\t};\n\t\t\tcase 'SHA-512':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.sha512WithRSAEncryption,\n\t\t\t\t\tparameters: nullValue(),\n\t\t\t\t\tsignParams: { name: 'RSASSA-PKCS1-v1_5' },\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unsupported RSA hash: ${algorithm.hash.name}`);\n\t\t}\n\t}\n\n\tif (algorithm.name === 'RSA-PSS') {\n\t\tthrow new Error('RSA-PSS signing requires an explicit signature profile');\n\t}\n\n\tif (algorithm.name === 'ECDSA') {\n\t\tif (!hasNamedCurve(algorithm)) {\n\t\t\tthrow new Error('ECDSA key is missing namedCurve metadata');\n\t\t}\n\t\tswitch (algorithm.namedCurve) {\n\t\t\tcase 'P-256':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.ecdsaWithSHA256,\n\t\t\t\t\tsignParams: { name: 'ECDSA', hash: 'SHA-256' },\n\t\t\t\t\tecdsaRawSignatureBytes: 64,\n\t\t\t\t};\n\t\t\tcase 'P-384':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.ecdsaWithSHA384,\n\t\t\t\t\tsignParams: { name: 'ECDSA', hash: 'SHA-384' },\n\t\t\t\t\tecdsaRawSignatureBytes: 96,\n\t\t\t\t};\n\t\t\tcase 'P-521':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.ecdsaWithSHA512,\n\t\t\t\t\tsignParams: { name: 'ECDSA', hash: 'SHA-512' },\n\t\t\t\t\tecdsaRawSignatureBytes: 132,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unsupported curve: ${algorithm.namedCurve}`);\n\t\t}\n\t}\n\n\tif (algorithm.name === 'Ed25519') {\n\t\treturn {\n\t\t\talgorithmOid: OIDS.ed25519,\n\t\t\tsignParams: { name: 'Ed25519' },\n\t\t};\n\t}\n\n\tthrow new Error(`Unsupported signing key algorithm: ${algorithm.name}`);\n}\n\n/** Build an RSA-PSS {@linkcode SignatureAlgorithmIdentifier} from an RSA-PSS private key. */\nfunction getRsaPssSignatureAlgorithm(\n\tprivateKey: CryptoKey,\n\tsaltLength: number | undefined,\n): SignatureAlgorithmIdentifier {\n\tconst algorithm = privateKey.algorithm;\n\tif (algorithm.name !== 'RSA-PSS') {\n\t\tthrow new Error('RSA-PSS signature profile requires an RSA-PSS private key');\n\t}\n\tif (!hasHash(algorithm)) {\n\t\tthrow new Error('RSA-PSS key is missing hash metadata');\n\t}\n\tconst hash = rsaPssHashFromWebCryptoName(algorithm.hash.name);\n\tconst parameters = rsaPssParametersForHash(hash);\n\tif (saltLength !== undefined && saltLength !== parameters.saltLength) {\n\t\tthrow new Error(\n\t\t\t`Unsupported RSA-PSS saltLength ${saltLength} for ${hash}; expected ${parameters.saltLength}`,\n\t\t);\n\t}\n\treturn {\n\t\talgorithmOid: OIDS.rsassaPss,\n\t\tparameters: encodeRsaPssParameters(parameters),\n\t\tsignParams: {\n\t\t\tname: 'RSA-PSS',\n\t\t\tsaltLength: parameters.saltLength,\n\t\t},\n\t};\n}\n\n/** DER-encode a {@linkcode SignatureAlgorithmIdentifier} as an ASN.1 `AlgorithmIdentifier` SEQUENCE. */\nexport function encodeAlgorithmIdentifier(input: SignatureAlgorithmIdentifier): Uint8Array {\n\tconst parts = [objectIdentifier(input.algorithmOid)];\n\tif (input.parameters !== undefined) {\n\t\tparts.push(input.parameters);\n\t}\n\treturn sequence(parts);\n}\n\n/** Sign `data` and return a DER-encoded signature. ECDSA raw signatures are auto-converted to DER. */\nexport async function signBytes(\n\tprivateKey: CryptoKey,\n\talgorithm: SignatureAlgorithmIdentifier,\n\tdata: Uint8Array,\n): Promise<Uint8Array> {\n\tconst view = new Uint8Array(data);\n\tconst signature = new Uint8Array(\n\t\tawait getCrypto().subtle.sign(algorithm.signParams, privateKey, view),\n\t);\n\t// For ECDSA keys, WebCrypto may return either raw (r || s) or DER format.\n\t// If the signature doesn't start with SEQUENCE tag and we expect ECDSA, convert to DER.\n\tif (algorithm.ecdsaRawSignatureBytes !== undefined && signature[0] !== 0x30) {\n\t\treturn rawEcdsaSignatureToDer(signature, algorithm.ecdsaRawSignatureBytes / 2);\n\t}\n\treturn signature;\n}\n\n/** Type guard: does this key algorithm carry a `hash` property (RSA keys). */\nfunction hasHash(algorithm: KeyAlgorithm): algorithm is RsaHashedKeyAlgorithm {\n\treturn 'hash' in algorithm;\n}\n\n/** Type guard: does this key algorithm carry a `namedCurve` property (EC keys). */\nfunction hasNamedCurve(algorithm: KeyAlgorithm): algorithm is EcKeyAlgorithm {\n\treturn 'namedCurve' in algorithm;\n}\n\n/** Narrow a WebCrypto hash name string to the supported {@linkcode RsaPssHash} union. */\nfunction rsaPssHashFromWebCryptoName(hash: string): RsaPssHash {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn 'SHA-256';\n\t\tcase 'SHA-384':\n\t\t\treturn 'SHA-384';\n\t\tcase 'SHA-512':\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported RSA hash: ${hash}`);\n\t}\n}\n"],"mappings":"wSA4CA,SAAgB,EACf,EACA,EAAiC,CAAC,EACH,CAC/B,IAAM,EAAY,EAAW,UAC7B,GAAI,EAAQ,OAAS,UACpB,OAAO,EAA4B,EAAY,EAAQ,UAAU,EAElE,GAAI,EAAU,OAAS,oBAAqB,CAC3C,GAAI,CAAC,EAAQ,CAAS,EACrB,MAAU,MAAM,kCAAkC,EAEnD,OAAQ,EAAU,KAAK,KAAvB,CACC,IAAK,UACJ,MAAO,CACN,aAAc,EAAK,wBACnB,WAAY,EAAU,EACtB,WAAY,CAAE,KAAM,mBAAoB,CACzC,EACD,IAAK,UACJ,MAAO,CACN,aAAc,EAAK,wBACnB,WAAY,EAAU,EACtB,WAAY,CAAE,KAAM,mBAAoB,CACzC,EACD,IAAK,UACJ,MAAO,CACN,aAAc,EAAK,wBACnB,WAAY,EAAU,EACtB,WAAY,CAAE,KAAM,mBAAoB,CACzC,EACD,QACC,MAAU,MAAM,yBAAyB,EAAU,KAAK,MAAM,CAChE,CACD,CAEA,GAAI,EAAU,OAAS,UACtB,MAAU,MAAM,wDAAwD,EAGzE,GAAI,EAAU,OAAS,QAAS,CAC/B,G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B,IAAM,EAAO,IAAI,WAAW,CAAI,EAC1B,EAAY,IAAI,WACrB,MAAM,EAAU,CAAC,CAAC,OAAO,KAAK,EAAU,WAAY,EAAY,CAAI,CACrE,EAMA,OAHI,EAAU,yBAA2B,IAAA,IAAa,EAAU,KAAO,GAC/D,EAAuB,EAAW,EAAU,uBAAyB,CAAC,EAEvE,CACR,CAGA,SAAS,EAAQ,EAA6D,CAC7E,MAAO,SAAU,CAClB,CAGA,SAAS,EAAc,EAAsD,CAC5E,MAAO,eAAgB,CACxB,CAGA,SAAS,EAA4B,EAA0B,CAC9D,OAAQ,EAAR,CACC,IAAK,UACJ,MAAO,UACR,IAAK,UACJ,MAAO,UACR,IAAK,UACJ,MAAO,UACR,QACC,MAAU,MAAM,yBAAyB,GAAM,CACjD,CACD"}
1
+ {"version":3,"file":"signing.js","names":[],"sources":["../../../src/internal/crypto/signing.ts"],"sourcesContent":["/**\n * Signing helpers that map WebCrypto keys and signature profiles to on-wire\n * `AlgorithmIdentifier` values. Used by certificate and CSR builders.\n *\n * @module\n */\n\nimport { nullValue, objectIdentifier, sequence } from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { ecdsaSignatureToDer } from './ecdsa.ts';\nimport { encodeRsaPssParameters, type RsaPssHash, rsaPssParametersForHash } from './rsa-pss.ts';\nimport { getCrypto } from './webcrypto.ts';\n\n/**\n * Controls how the signature algorithm is chosen.\n *\n * `'auto'` (default) infers the algorithm from the key. `'rsa-pss'` forces RSA-PSS\n * padding and requires an RSA-PSS private key.\n */\nexport type SignatureProfileInput =\n\t| {\n\t\t\t/** Infer the signature algorithm from the private key. */\n\t\t\treadonly kind?: 'auto';\n\t }\n\t| {\n\t\t\t/** Force RSA-PSS padding. */\n\t\t\treadonly kind: 'rsa-pss';\n\t\t\t/** Salt length in bytes. Must match the key's hash digest size. */\n\t\t\treadonly saltLength?: 32 | 48 | 64;\n\t };\n\n/** Resolved signature algorithm: the OID/parameters for DER encoding and the WebCrypto sign params. */\nexport interface SignatureAlgorithmIdentifier {\n\t/** ASN.1 OID of the signature algorithm (e.g. sha256WithRSAEncryption). */\n\treadonly algorithmOid: string;\n\t/** DER-encoded algorithm parameters, if the algorithm requires them (e.g. RSA-PSS). */\n\treadonly parameters?: Uint8Array;\n\t/** WebCrypto `sign()` algorithm parameter. */\n\treadonly signParams: Algorithm | EcdsaParams | RsaPssParams;\n\t/** When set, the raw ECDSA signature is this many bytes and must be DER-converted. */\n\treadonly ecdsaRawSignatureBytes?: number;\n}\n\n/** Resolve a private key and optional profile into a {@linkcode SignatureAlgorithmIdentifier}. */\nexport function getSignatureAlgorithm(\n\tprivateKey: CryptoKey,\n\tprofile: SignatureProfileInput = {},\n): SignatureAlgorithmIdentifier {\n\tconst algorithm = privateKey.algorithm;\n\tif (profile.kind === 'rsa-pss') {\n\t\treturn getRsaPssSignatureAlgorithm(privateKey, profile.saltLength);\n\t}\n\tif (algorithm.name === 'RSASSA-PKCS1-v1_5') {\n\t\tif (!hasHash(algorithm)) {\n\t\t\tthrow new Error('RSA key is missing hash metadata');\n\t\t}\n\t\tswitch (algorithm.hash.name) {\n\t\t\tcase 'SHA-256':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.sha256WithRSAEncryption,\n\t\t\t\t\tparameters: nullValue(),\n\t\t\t\t\tsignParams: { name: 'RSASSA-PKCS1-v1_5' },\n\t\t\t\t};\n\t\t\tcase 'SHA-384':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.sha384WithRSAEncryption,\n\t\t\t\t\tparameters: nullValue(),\n\t\t\t\t\tsignParams: { name: 'RSASSA-PKCS1-v1_5' },\n\t\t\t\t};\n\t\t\tcase 'SHA-512':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.sha512WithRSAEncryption,\n\t\t\t\t\tparameters: nullValue(),\n\t\t\t\t\tsignParams: { name: 'RSASSA-PKCS1-v1_5' },\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unsupported RSA hash: ${algorithm.hash.name}`);\n\t\t}\n\t}\n\n\tif (algorithm.name === 'RSA-PSS') {\n\t\tthrow new Error('RSA-PSS signing requires an explicit signature profile');\n\t}\n\n\tif (algorithm.name === 'ECDSA') {\n\t\tif (!hasNamedCurve(algorithm)) {\n\t\t\tthrow new Error('ECDSA key is missing namedCurve metadata');\n\t\t}\n\t\tswitch (algorithm.namedCurve) {\n\t\t\tcase 'P-256':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.ecdsaWithSHA256,\n\t\t\t\t\tsignParams: { name: 'ECDSA', hash: 'SHA-256' },\n\t\t\t\t\tecdsaRawSignatureBytes: 64,\n\t\t\t\t};\n\t\t\tcase 'P-384':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.ecdsaWithSHA384,\n\t\t\t\t\tsignParams: { name: 'ECDSA', hash: 'SHA-384' },\n\t\t\t\t\tecdsaRawSignatureBytes: 96,\n\t\t\t\t};\n\t\t\tcase 'P-521':\n\t\t\t\treturn {\n\t\t\t\t\talgorithmOid: OIDS.ecdsaWithSHA512,\n\t\t\t\t\tsignParams: { name: 'ECDSA', hash: 'SHA-512' },\n\t\t\t\t\tecdsaRawSignatureBytes: 132,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unsupported curve: ${algorithm.namedCurve}`);\n\t\t}\n\t}\n\n\tif (algorithm.name === 'Ed25519') {\n\t\treturn {\n\t\t\talgorithmOid: OIDS.ed25519,\n\t\t\tsignParams: { name: 'Ed25519' },\n\t\t};\n\t}\n\n\tthrow new Error(`Unsupported signing key algorithm: ${algorithm.name}`);\n}\n\n/** Build an RSA-PSS {@linkcode SignatureAlgorithmIdentifier} from an RSA-PSS private key. */\nfunction getRsaPssSignatureAlgorithm(\n\tprivateKey: CryptoKey,\n\tsaltLength: number | undefined,\n): SignatureAlgorithmIdentifier {\n\tconst algorithm = privateKey.algorithm;\n\tif (algorithm.name !== 'RSA-PSS') {\n\t\tthrow new Error('RSA-PSS signature profile requires an RSA-PSS private key');\n\t}\n\tif (!hasHash(algorithm)) {\n\t\tthrow new Error('RSA-PSS key is missing hash metadata');\n\t}\n\tconst hash = rsaPssHashFromWebCryptoName(algorithm.hash.name);\n\tconst parameters = rsaPssParametersForHash(hash);\n\tif (saltLength !== undefined && saltLength !== parameters.saltLength) {\n\t\tthrow new Error(\n\t\t\t`Unsupported RSA-PSS saltLength ${saltLength} for ${hash}; expected ${parameters.saltLength}`,\n\t\t);\n\t}\n\treturn {\n\t\talgorithmOid: OIDS.rsassaPss,\n\t\tparameters: encodeRsaPssParameters(parameters),\n\t\tsignParams: {\n\t\t\tname: 'RSA-PSS',\n\t\t\tsaltLength: parameters.saltLength,\n\t\t},\n\t};\n}\n\n/** DER-encode a {@linkcode SignatureAlgorithmIdentifier} as an ASN.1 `AlgorithmIdentifier` SEQUENCE. */\nexport function encodeAlgorithmIdentifier(input: SignatureAlgorithmIdentifier): Uint8Array {\n\tconst parts = [objectIdentifier(input.algorithmOid)];\n\tif (input.parameters !== undefined) {\n\t\tparts.push(input.parameters);\n\t}\n\treturn sequence(parts);\n}\n\n/** Sign `data` and return a DER-encoded signature. ECDSA raw signatures are auto-converted to DER. */\nexport async function signBytes(\n\tprivateKey: CryptoKey,\n\talgorithm: SignatureAlgorithmIdentifier,\n\tdata: Uint8Array,\n): Promise<Uint8Array> {\n\tconst view = new Uint8Array(data);\n\tconst signature = new Uint8Array(\n\t\tawait getCrypto().subtle.sign(algorithm.signParams, privateKey, view),\n\t);\n\tif (algorithm.ecdsaRawSignatureBytes !== undefined) {\n\t\treturn ecdsaSignatureToDer(signature, algorithm.ecdsaRawSignatureBytes);\n\t}\n\treturn signature;\n}\n\n/** Type guard: does this key algorithm carry a `hash` property (RSA keys). */\nfunction hasHash(algorithm: KeyAlgorithm): algorithm is RsaHashedKeyAlgorithm {\n\treturn 'hash' in algorithm;\n}\n\n/** Type guard: does this key algorithm carry a `namedCurve` property (EC keys). */\nfunction hasNamedCurve(algorithm: KeyAlgorithm): algorithm is EcKeyAlgorithm {\n\treturn 'namedCurve' in algorithm;\n}\n\n/** Narrow a WebCrypto hash name string to the supported {@linkcode RsaPssHash} union. */\nfunction rsaPssHashFromWebCryptoName(hash: string): RsaPssHash {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn 'SHA-256';\n\t\tcase 'SHA-384':\n\t\t\treturn 'SHA-384';\n\t\tcase 'SHA-512':\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported RSA hash: ${hash}`);\n\t}\n}\n"],"mappings":"qSA4CA,SAAgB,EACf,EACA,EAAiC,CAAC,EACH,CAC/B,IAAM,EAAY,EAAW,UAC7B,GAAI,EAAQ,OAAS,UACpB,OAAO,EAA4B,EAAY,EAAQ,UAAU,EAElE,GAAI,EAAU,OAAS,oBAAqB,CAC3C,GAAI,CAAC,EAAQ,CAAS,EACrB,MAAU,MAAM,kCAAkC,EAEnD,OAAQ,EAAU,KAAK,KAAvB,CACC,IAAK,UACJ,MAAO,CACN,aAAc,EAAK,wBACnB,WAAY,EAAU,EACtB,WAAY,CAAE,KAAM,mBAAoB,CACzC,EACD,IAAK,UACJ,MAAO,CACN,aAAc,EAAK,wBACnB,WAAY,EAAU,EACtB,WAAY,CAAE,KAAM,mBAAoB,CACzC,EACD,IAAK,UACJ,MAAO,CACN,aAAc,EAAK,wBACnB,WAAY,EAAU,EACtB,WAAY,CAAE,KAAM,mBAAoB,CACzC,EACD,QACC,MAAU,MAAM,yBAAyB,EAAU,KAAK,MAAM,CAChE,CACD,CAEA,GAAI,EAAU,OAAS,UACtB,MAAU,MAAM,wDAAwD,EAGzE,GAAI,EAAU,OAAS,QAAS,CAC/B,GAAI,CAAC,EAAc,CAAS,EAC3B,MAAU,MAAM,0CAA0C,EAE3D,OAAQ,EAAU,WAAlB,CACC,IAAK,QACJ,MAAO,CACN,aAAc,EAAK,gBACnB,WA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A,OAHI,EAAU,yBAA2B,IAAA,GAGlC,EAFC,EAAoB,EAAW,EAAU,sBAAsB,CAGxE,CAGA,SAAS,EAAQ,EAA6D,CAC7E,MAAO,SAAU,CAClB,CAGA,SAAS,EAAc,EAAsD,CAC5E,MAAO,eAAgB,CACxB,CAGA,SAAS,EAA4B,EAA0B,CAC9D,OAAQ,EAAR,CACC,IAAK,UACJ,MAAO,UACR,IAAK,UACJ,MAAO,UACR,IAAK,UACJ,MAAO,UACR,QACC,MAAU,MAAM,yBAAyB,GAAM,CACjD,CACD"}
package/dist/keys/keys.js CHANGED
@@ -1,5 +1,5 @@
1
- import{nullValue as e,objectIdentifier as t,octetString as n,readSequenceChildren as r,sequence as i}from"../internal/asn1/der.js";import{decodeObjectIdentifier as a,extractBitStringValue as o,hexToBytes as s,toArrayBuffer as c,toHex as l}from"../internal/asn1/asn1.js";import{OIDS as u}from"../internal/asn1/oids.js";import{md5 as ee}from"../internal/crypto/hash.js";import{getCrypto as d}from"../internal/crypto/webcrypto.js";import{decryptPbes2 as te,encryptPbes2 as ne,isWrongPasswordError as re,wrongPasswordError as ie}from"../internal/crypto/pbes2.js";import{base64Decode as f,base64Encode as p}from"../internal/shared/base64.js";import{failureResult as m,rethrowIfInvariant as h,successResult as g}from"../result/result.js";import{pemDecodeOrThrow as _,pemEncode as v}from"../pem/pem.js";async function ae(e={kind:`ecdsa`,curve:`P-256`}){let t=await d().subtle.generateKey(Oe(e),!0,[`sign`,`verify`]);if(!(`publicKey`in t)||!(`privateKey`in t))throw Error(`Expected an asymmetric key pair`);return y(t.publicKey,t.privateKey)}function y(e,t){return{publicKey:e,privateKey:t,async exportSpkiDer(){return new Uint8Array(await d().subtle.exportKey(`spki`,e))},async exportSpkiPem(){return v(`PUBLIC KEY`,await this.exportSpkiDer())},async exportPkcs8Der(){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,t))},async exportPkcs8Pem(){return v(`PRIVATE KEY`,await this.exportPkcs8Der())},async exportPublicJwk(){return d().subtle.exportKey(`jwk`,e)},async exportPrivateJwk(){return d().subtle.exportKey(`jwk`,t)}}}async function b(e){return new Uint8Array(await d().subtle.exportKey(`spki`,e))}async function x(e){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,e))}async function oe(e){return d().subtle.exportKey(`jwk`,e)}async function se(e){return d().subtle.exportKey(`jwk`,e)}async function ce(e){return v(`PRIVATE KEY`,await x(e))}async function S(e,t){let r=await ne(await x(e),t);return i([r.algorithmIdentifierDer,n(r.encryptedData)])}async function le(e,t){return v(`ENCRYPTED PRIVATE KEY`,await S(e,t))}async function C(e){let t=J(await x(e));if(t.algorithmOid!==u.rsaEncryption)throw Error(`PKCS#1 export requires an RSA private key`);return t.privateKeyDer}async function ue(e){return v(`RSA PRIVATE KEY`,await C(e))}async function de(e,t){return Z(`RSA PRIVATE KEY`,await C(e),t)}async function w(e){let t=J(await x(e));if(t.algorithmOid!==u.ecPublicKey)throw Error(`SEC1 export requires an EC private key`);return t.privateKeyDer}async function fe(e){return v(`EC PRIVATE KEY`,await w(e))}async function T(e,t){return Z(`EC PRIVATE KEY`,await w(e),t)}async function pe(e){return v(`PUBLIC KEY`,await b(e))}async function me(e){if(e.type===`public`)return p(await b(e));if(e.type===`private`)return p(await x(e));throw Error(`Cannot export secret/symmetric CryptoKey`)}async function E(e,t){Le(Ie(e),t);try{return await d().subtle.importKey(`spki`,new Uint8Array(e),q(t),!0,[`verify`])}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}async function D(e){try{return g(await e())}catch(e){return h(e),m(`malformed`,e instanceof Error?e.message:`Malformed key`)}}async function O(e){try{return g(await e())}catch(e){return h(e),re(e)?m(`invalid_password`,e.message):m(`malformed`,e instanceof Error?e.message:`Malformed encrypted key`)}}function he(e,t){return D(()=>E(e,t))}async function k(e,t){return E(_(`PUBLIC KEY`,e),t)}function ge(e,t){return D(()=>k(e,t))}async function A(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 SubjectPublicKeyInfo`)}return E(n,t)}function _e(e,t){return D(()=>A(e,t))}async function j(e,t){let n;try{n=J(e)}catch{throw Error(`Malformed PKCS#8 private key`)}Re(n,t);try{return await d().subtle.importKey(`pkcs8`,new Uint8Array(e),q(t),!0,[`sign`])}catch{throw Error(`Malformed PKCS#8 private key`)}}function ve(e,t){return D(()=>j(e,t))}async function M(e,t){return j(_(`PRIVATE KEY`,e),t)}function N(e,t){return D(()=>M(e,t))}async function P(e,t,n){let i;try{i=r(e)}catch{throw Error(`Malformed EncryptedPrivateKeyInfo`)}let a=i[0],o=i[1];if(i.length!==2||a===void 0||o===void 0||o.tag!==4)throw Error(`Malformed EncryptedPrivateKeyInfo`);return j(await te(e.slice(a.start-a.headerLength,a.end),o.value,t),n)}function F(e,t,n){return O(()=>P(e,t,n))}async function I(e,t,n){return P(_(`ENCRYPTED PRIVATE KEY`,e),t,n)}function ye(e,t,n){return O(()=>I(e,t,n))}async function L(e,t={kind:`rsa`}){return j(ke(e),t)}function be(e,t={kind:`rsa`}){return D(()=>L(e,t))}async function R(e,t={kind:`rsa`}){return L(_(`RSA PRIVATE KEY`,e),t)}function z(e,t={kind:`rsa`}){return D(()=>R(e,t))}async function B(e,t,n={kind:`rsa`}){return L(await Q(`RSA PRIVATE KEY`,e,t),n)}function xe(e,t,n={kind:`rsa`}){return O(()=>B(e,t,n))}async function V(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 PKCS#8 private key`)}return j(n,t)}function Se(e,t){return D(()=>V(e,t))}async function H(e,t){return j(Ae(e,t.curve),t)}function Ce(e,t){return D(()=>H(e,t))}async function U(e,t){return H(_(`EC PRIVATE KEY`,e),t)}function we(e,t){return D(()=>U(e,t))}async function W(e,t,n){return H(await Q(`EC PRIVATE KEY`,e,t),n)}function Te(e,t,n){return O(()=>W(e,t,n))}async function G(e,t){ze(e,t);try{return await d().subtle.importKey(`jwk`,e,q(t),!0,[`verify`])}catch{throw Error(`Malformed public JWK`)}}function Ee(e,t){return D(()=>G(e,t))}async function K(e,t){return d().subtle.importKey(`jwk`,e,q(t),!0,[`sign`])}function De(e,t){return D(()=>K(e,t))}function Oe(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),modulusLength:e.modulusLength??2048,publicExponent:Uint8Array.of(1,0,1),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve??`P-256`};case`ed25519`:return{name:`Ed25519`}}}function q(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve};case`ed25519`:return{name:`Ed25519`}}}function J(e){let t=r(e),n=t[1],i=t[2];if(t.length<3||t.length>4||n===void 0||n.tag!==48||i===void 0||i.tag!==4)throw Error(`Malformed PKCS#8 private key`);let o=r(e.slice(n.start-n.headerLength,n.end)),s=o[0];if(s===void 0||s.tag!==6||o.length<1||o.length>2)throw Error(`Malformed PKCS#8 private key`);let c=o[1];return{algorithmOid:a(s.value),...c===void 0?{}:{parametersTag:c.tag},...c?.tag===6?{parametersOid:a(c.value)}:{},privateKeyDer:i.value}}function ke(r){return i([Uint8Array.of(2,1,0),i([t(u.rsaEncryption),e()]),n(new Uint8Array(r))])}function Ae(e,r){return i([Uint8Array.of(2,1,0),i([t(u.ecPublicKey),t(Y(r))]),n(new Uint8Array(e))])}function Y(e){switch(e){case`P-256`:return u.prime256v1;case`P-384`:return u.secp384r1;case`P-521`:return u.secp521r1}}function X(e){return e===`pss`?`RSA-PSS`:`RSASSA-PKCS1-v1_5`}async function Z(e,t,n){let r=n.iv??d().getRandomValues(new Uint8Array(16));if(r.length!==16)throw Error(`Traditional PEM encryption requires a 16-byte IV`);let i=n.cipher??`AES-256-CBC`,a=await $(n.password,r.slice(0,8),i,[`encrypt`]),o=p(new Uint8Array(await d().subtle.encrypt({name:`AES-CBC`,iv:c(r)},a,c(t)))).match(/.{1,64}/g)?.join(`
1
+ import{nullValue as e,objectIdentifier as t,octetString as n,readSequenceChildren as r,sequence as i}from"../internal/asn1/der.js";import{decodeObjectIdentifier as a,extractBitStringValue as o,hexToBytes as s,toArrayBuffer as c,toHex as l}from"../internal/asn1/asn1.js";import{OIDS as u}from"../internal/asn1/oids.js";import{md5 as ee}from"../internal/crypto/hash.js";import{getCrypto as d}from"../internal/crypto/webcrypto.js";import{decryptPbes2 as te,encryptPbes2 as ne,isWrongPasswordError as re,wrongPasswordError as f}from"../internal/crypto/pbes2.js";import{base64Decode as p,base64Encode as m}from"../internal/shared/base64.js";import{failureResult as h,rethrowIfInvariant as g,successResult as _}from"../result/result.js";import{pemDecodeOrThrow as v,pemEncode as y}from"../pem/pem.js";async function ie(e={kind:`ecdsa`,curve:`P-256`}){let t=await d().subtle.generateKey(Oe(e),!0,[`sign`,`verify`]);if(!(`publicKey`in t)||!(`privateKey`in t))throw Error(`Expected an asymmetric key pair`);return b(t.publicKey,t.privateKey)}function b(e,t){return{publicKey:e,privateKey:t,async exportSpkiDer(){return new Uint8Array(await d().subtle.exportKey(`spki`,e))},async exportSpkiPem(){return y(`PUBLIC KEY`,await this.exportSpkiDer())},async exportPkcs8Der(){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,t))},async exportPkcs8Pem(){return y(`PRIVATE KEY`,await this.exportPkcs8Der())},async exportPublicJwk(){return d().subtle.exportKey(`jwk`,e)},async exportPrivateJwk(){return d().subtle.exportKey(`jwk`,t)}}}async function x(e){return new Uint8Array(await d().subtle.exportKey(`spki`,e))}async function S(e){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,e))}async function ae(e){return d().subtle.exportKey(`jwk`,e)}async function oe(e){return d().subtle.exportKey(`jwk`,e)}async function se(e){return y(`PRIVATE KEY`,await S(e))}async function C(e,t){let r=await ne(await S(e),t);return i([r.algorithmIdentifierDer,n(r.encryptedData)])}async function ce(e,t){return y(`ENCRYPTED PRIVATE KEY`,await C(e,t))}async function w(e){let t=J(await S(e));if(t.algorithmOid!==u.rsaEncryption)throw Error(`PKCS#1 export requires an RSA private key`);return t.privateKeyDer}async function le(e){return y(`RSA PRIVATE KEY`,await w(e))}async function ue(e,t){return Z(`RSA PRIVATE KEY`,await w(e),t)}async function T(e){let t=J(await S(e));if(t.algorithmOid!==u.ecPublicKey)throw Error(`SEC1 export requires an EC private key`);return t.privateKeyDer}async function de(e){return y(`EC PRIVATE KEY`,await T(e))}async function fe(e,t){return Z(`EC PRIVATE KEY`,await T(e),t)}async function pe(e){return y(`PUBLIC KEY`,await x(e))}async function me(e){if(e.type===`public`)return m(await x(e));if(e.type===`private`)return m(await S(e));throw Error(`Cannot export secret/symmetric CryptoKey`)}async function E(e,t){Le(Ie(e),t);try{return await d().subtle.importKey(`spki`,new Uint8Array(e),q(t),!0,[`verify`])}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}async function D(e){try{return _(await e())}catch(e){return g(e),h(`malformed`,e instanceof Error?e.message:`Malformed key`)}}async function O(e){try{return _(await e())}catch(e){return g(e),re(e)?h(`invalid_password`,e.message):h(`malformed`,e instanceof Error?e.message:`Malformed encrypted key`)}}function he(e,t){return D(()=>E(e,t))}async function k(e,t){return E(v(`PUBLIC KEY`,e),t)}function ge(e,t){return D(()=>k(e,t))}async function A(e,t){let n;try{n=p(e)}catch{throw Error(`Invalid base64 SubjectPublicKeyInfo`)}return E(n,t)}function _e(e,t){return D(()=>A(e,t))}async function j(e,t){let n;try{n=J(e)}catch{throw Error(`Malformed PKCS#8 private key`)}Re(n,t);try{return await d().subtle.importKey(`pkcs8`,new Uint8Array(e),q(t),!0,[`sign`])}catch{throw Error(`Malformed PKCS#8 private key`)}}function ve(e,t){return D(()=>j(e,t))}async function M(e,t){return j(v(`PRIVATE KEY`,e),t)}function N(e,t){return D(()=>M(e,t))}async function P(e,t,n){let i;try{i=r(e)}catch{throw Error(`Malformed EncryptedPrivateKeyInfo`)}let a=i[0],o=i[1];if(i.length!==2||a===void 0||o===void 0||o.tag!==4)throw Error(`Malformed EncryptedPrivateKeyInfo`);let s=await te(e.slice(a.start-a.headerLength,a.end),o.value,t);try{J(s)}catch{throw f(`Invalid password or encrypted content`)}return j(s,n)}function F(e,t,n){return O(()=>P(e,t,n))}async function I(e,t,n){return P(v(`ENCRYPTED PRIVATE KEY`,e),t,n)}function ye(e,t,n){return O(()=>I(e,t,n))}async function L(e,t={kind:`rsa`}){return j(ke(e),t)}function be(e,t={kind:`rsa`}){return D(()=>L(e,t))}async function R(e,t={kind:`rsa`}){return L(v(`RSA PRIVATE KEY`,e),t)}function z(e,t={kind:`rsa`}){return D(()=>R(e,t))}async function B(e,t,n={kind:`rsa`}){return L(await Q(`RSA PRIVATE KEY`,e,t),n)}function xe(e,t,n={kind:`rsa`}){return O(()=>B(e,t,n))}async function V(e,t){let n;try{n=p(e)}catch{throw Error(`Invalid base64 PKCS#8 private key`)}return j(n,t)}function Se(e,t){return D(()=>V(e,t))}async function H(e,t){return j(Ae(e,t.curve),t)}function Ce(e,t){return D(()=>H(e,t))}async function U(e,t){return H(v(`EC PRIVATE KEY`,e),t)}function we(e,t){return D(()=>U(e,t))}async function W(e,t,n){return H(await Q(`EC PRIVATE KEY`,e,t),n)}function Te(e,t,n){return O(()=>W(e,t,n))}async function G(e,t){ze(e,t);try{return await d().subtle.importKey(`jwk`,e,q(t),!0,[`verify`])}catch{throw Error(`Malformed public JWK`)}}function Ee(e,t){return D(()=>G(e,t))}async function K(e,t){return d().subtle.importKey(`jwk`,e,q(t),!0,[`sign`])}function De(e,t){return D(()=>K(e,t))}function Oe(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),modulusLength:e.modulusLength??2048,publicExponent:Uint8Array.of(1,0,1),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve??`P-256`};case`ed25519`:return{name:`Ed25519`}}}function q(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve};case`ed25519`:return{name:`Ed25519`}}}function J(e){let t=r(e),n=t[1],i=t[2];if(t.length<3||t.length>4||n===void 0||n.tag!==48||i===void 0||i.tag!==4)throw Error(`Malformed PKCS#8 private key`);let o=r(e.slice(n.start-n.headerLength,n.end)),s=o[0];if(s===void 0||s.tag!==6||o.length<1||o.length>2)throw Error(`Malformed PKCS#8 private key`);let c=o[1];return{algorithmOid:a(s.value),...c===void 0?{}:{parametersTag:c.tag},...c?.tag===6?{parametersOid:a(c.value)}:{},privateKeyDer:i.value}}function ke(r){return i([Uint8Array.of(2,1,0),i([t(u.rsaEncryption),e()]),n(new Uint8Array(r))])}function Ae(e,r){return i([Uint8Array.of(2,1,0),i([t(u.ecPublicKey),t(Y(r))]),n(new Uint8Array(e))])}function Y(e){switch(e){case`P-256`:return u.prime256v1;case`P-384`:return u.secp384r1;case`P-521`:return u.secp521r1}}function X(e){return e===`pss`?`RSA-PSS`:`RSASSA-PKCS1-v1_5`}async function Z(e,t,n){let r=n.iv??d().getRandomValues(new Uint8Array(16));if(r.length!==16)throw Error(`Traditional PEM encryption requires a 16-byte IV`);let i=n.cipher??`AES-256-CBC`,a=await $(n.password,r.slice(0,8),i,[`encrypt`]),o=m(new Uint8Array(await d().subtle.encrypt({name:`AES-CBC`,iv:c(r)},a,c(t)))).match(/.{1,64}/g)?.join(`
2
2
  `)??``;return[`-----BEGIN ${e}-----`,`Proc-Type: 4,ENCRYPTED`,`DEK-Info: ${i},${l(r).toUpperCase()}`,``,o,`-----END ${e}-----`].join(`
3
- `)}async function Q(e,t,n){let r=Fe(t);if(r.label!==e)throw Error(`Expected ${e} PEM block`);let i=r.headers.get(`DEK-Info`);if(r.headers.get(`Proc-Type`)!==`4,ENCRYPTED`||i===void 0)throw Error(`Traditional PEM encryption headers missing`);let[a,o]=i.split(`,`);if(!je(a)||o===void 0)throw Error(`Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported`);if(!Me(o))throw Error(`Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters`);let l=s(o),u=await $(n,l.slice(0,8),a,[`decrypt`]);try{return new Uint8Array(await d().subtle.decrypt({name:`AES-CBC`,iv:c(l)},u,c(f(r.base64Body))))}catch{throw ie(`Invalid password or encrypted PEM content`)}}async function $(e,t,n,r){let i=Ne(n),a=Pe(e,t,i/8);return d().subtle.importKey(`raw`,c(a),{name:`AES-CBC`,length:i},!1,r)}function je(e){return e===`AES-128-CBC`||e===`AES-192-CBC`||e===`AES-256-CBC`}function Me(e){return e.length===32&&/^[0-9A-Fa-f]+$/.test(e)}function Ne(e){switch(e){case`AES-128-CBC`:return 128;case`AES-192-CBC`:return 192;case`AES-256-CBC`:return 256}}function Pe(e,t,n){let r=new TextEncoder().encode(e),i=[],a=new Uint8Array,o=0;for(;o<n;){let e=new Uint8Array(a.length+r.length+t.length);e.set(a,0),e.set(r,a.length),e.set(t,a.length+r.length),a=ee(e),i.push(a),o+=a.length}let s=new Uint8Array(n),c=0;for(let e of i){let t=e.slice(0,Math.min(e.length,n-c));if(s.set(t,c),c+=t.length,c>=n)break}return s}function Fe(e){let t=e.replace(/\r/g,``).trim().split(`
4
- `),n=t[0],r=t[t.length-1];if(n===void 0||r===void 0||!n.startsWith(`-----BEGIN `)||!r.startsWith(`-----END `))throw Error(`Invalid PEM block`);let i=n.slice(11,-5);if(r!==`-----END ${i}-----`)throw Error(`PEM boundaries do not match`);let a=new Map,o=1;for(;o<t.length-1;){let e=t[o];if(e===void 0)break;if(e.length===0){o+=1;break}let n=e.indexOf(`: `);if(n===-1)break;let r=e.slice(0,n);if(a.has(r))throw Error(`Duplicate PEM header: ${r}`);a.set(r,e.slice(n+2)),o+=1}return{label:i,headers:a,base64Body:t.slice(o,t.length-1).join(``)}}function Ie(e){try{let t=r(e);if(t.length!==2)throw Error(`Malformed SubjectPublicKeyInfo`);let n=t[0],i=t[1];if(n===void 0||n.tag!==48||i===void 0||i.tag!==3)throw Error(`Malformed SubjectPublicKeyInfo`);o(i);let s=r(e.slice(n.start-n.headerLength,n.end)),c=s[0];if(c===void 0||c.tag!==6||s.length<1||s.length>2)throw Error(`Malformed SubjectPublicKeyInfo`);let l=s[1];return{algorithmOid:a(c.value),...l===void 0?{}:{parametersTag:l.tag},...l?.tag===6?{parametersOid:a(l.value)}:{}}}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}function Le(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return}}function Re(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return}}function ze(e,t){if(e.k!==void 0||e.d!==void 0||e.p!==void 0||e.q!==void 0||e.dp!==void 0||e.dq!==void 0||e.qi!==void 0||e.oth!==void 0)throw Error(`Public JWK must not contain private key material`);switch(t.kind){case`rsa`:if(e.kty!==`RSA`||typeof e.n!=`string`||typeof e.e!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.kty!==`EC`||e.crv!==t.curve||typeof e.x!=`string`||typeof e.y!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.kty!==`OKP`||e.crv!==`Ed25519`||typeof e.x!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return}}export{me as exportBinaryBase64,de as exportEncryptedPkcs1Pem,S as exportEncryptedPkcs8Der,le as exportEncryptedPkcs8Pem,T as exportEncryptedSec1Pem,C as exportPkcs1Der,ue as exportPkcs1Pem,x as exportPkcs8Der,ce as exportPkcs8Pem,se as exportPrivateJwk,oe as exportPublicJwk,w as exportSec1Der,fe as exportSec1Pem,b as exportSpkiDer,pe as exportSpkiPem,ae as generateKeyPair,xe as importEncryptedPkcs1Pem,B as importEncryptedPkcs1PemOrThrow,F as importEncryptedPkcs8Der,P as importEncryptedPkcs8DerOrThrow,ye as importEncryptedPkcs8Pem,I as importEncryptedPkcs8PemOrThrow,Te as importEncryptedSec1Pem,W as importEncryptedSec1PemOrThrow,be as importPkcs1Der,L as importPkcs1DerOrThrow,z as importPkcs1Pem,R as importPkcs1PemOrThrow,Se as importPkcs8Base64,V as importPkcs8Base64OrThrow,ve as importPkcs8Der,j as importPkcs8DerOrThrow,N as importPkcs8Pem,M as importPkcs8PemOrThrow,De as importPrivateJwk,K as importPrivateJwkOrThrow,Ee as importPublicJwk,G as importPublicJwkOrThrow,Ce as importSec1Der,H as importSec1DerOrThrow,we as importSec1Pem,U as importSec1PemOrThrow,_e as importSpkiBase64,A as importSpkiBase64OrThrow,he as importSpkiDer,E as importSpkiDerOrThrow,ge as importSpkiPem,k as importSpkiPemOrThrow};
3
+ `)}async function Q(e,t,n){let r=Fe(t);if(r.label!==e)throw Error(`Expected ${e} PEM block`);let i=r.headers.get(`DEK-Info`);if(r.headers.get(`Proc-Type`)!==`4,ENCRYPTED`||i===void 0)throw Error(`Traditional PEM encryption headers missing`);let[a,o]=i.split(`,`);if(!je(a)||o===void 0)throw Error(`Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported`);if(!Me(o))throw Error(`Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters`);let l=s(o),u=await $(n,l.slice(0,8),a,[`decrypt`]);try{return new Uint8Array(await d().subtle.decrypt({name:`AES-CBC`,iv:c(l)},u,c(p(r.base64Body))))}catch{throw f(`Invalid password or encrypted PEM content`)}}async function $(e,t,n,r){let i=Ne(n),a=Pe(e,t,i/8);return d().subtle.importKey(`raw`,c(a),{name:`AES-CBC`,length:i},!1,r)}function je(e){return e===`AES-128-CBC`||e===`AES-192-CBC`||e===`AES-256-CBC`}function Me(e){return e.length===32&&/^[0-9A-Fa-f]+$/.test(e)}function Ne(e){switch(e){case`AES-128-CBC`:return 128;case`AES-192-CBC`:return 192;case`AES-256-CBC`:return 256}}function Pe(e,t,n){let r=new TextEncoder().encode(e),i=[],a=new Uint8Array,o=0;for(;o<n;){let e=new Uint8Array(a.length+r.length+t.length);e.set(a,0),e.set(r,a.length),e.set(t,a.length+r.length),a=ee(e),i.push(a),o+=a.length}let s=new Uint8Array(n),c=0;for(let e of i){let t=e.slice(0,Math.min(e.length,n-c));if(s.set(t,c),c+=t.length,c>=n)break}return s}function Fe(e){let t=e.replace(/\r/g,``).trim().split(`
4
+ `),n=t[0],r=t[t.length-1];if(n===void 0||r===void 0||!n.startsWith(`-----BEGIN `)||!r.startsWith(`-----END `))throw Error(`Invalid PEM block`);let i=n.slice(11,-5);if(r!==`-----END ${i}-----`)throw Error(`PEM boundaries do not match`);let a=new Map,o=1;for(;o<t.length-1;){let e=t[o];if(e===void 0)break;if(e.length===0){o+=1;break}let n=e.indexOf(`: `);if(n===-1)break;let r=e.slice(0,n);if(a.has(r))throw Error(`Duplicate PEM header: ${r}`);a.set(r,e.slice(n+2)),o+=1}return{label:i,headers:a,base64Body:t.slice(o,t.length-1).join(``)}}function Ie(e){try{let t=r(e);if(t.length!==2)throw Error(`Malformed SubjectPublicKeyInfo`);let n=t[0],i=t[1];if(n===void 0||n.tag!==48||i===void 0||i.tag!==3)throw Error(`Malformed SubjectPublicKeyInfo`);o(i);let s=r(e.slice(n.start-n.headerLength,n.end)),c=s[0];if(c===void 0||c.tag!==6||s.length<1||s.length>2)throw Error(`Malformed SubjectPublicKeyInfo`);let l=s[1];return{algorithmOid:a(c.value),...l===void 0?{}:{parametersTag:l.tag},...l?.tag===6?{parametersOid:a(l.value)}:{}}}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}function Le(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return}}function Re(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return}}function ze(e,t){if(e.k!==void 0||e.d!==void 0||e.p!==void 0||e.q!==void 0||e.dp!==void 0||e.dq!==void 0||e.qi!==void 0||e.oth!==void 0)throw Error(`Public JWK must not contain private key material`);switch(t.kind){case`rsa`:if(e.kty!==`RSA`||typeof e.n!=`string`||typeof e.e!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.kty!==`EC`||e.crv!==t.curve||typeof e.x!=`string`||typeof e.y!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.kty!==`OKP`||e.crv!==`Ed25519`||typeof e.x!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return}}export{me as exportBinaryBase64,ue as exportEncryptedPkcs1Pem,C as exportEncryptedPkcs8Der,ce as exportEncryptedPkcs8Pem,fe as exportEncryptedSec1Pem,w as exportPkcs1Der,le as exportPkcs1Pem,S as exportPkcs8Der,se as exportPkcs8Pem,oe as exportPrivateJwk,ae as exportPublicJwk,T as exportSec1Der,de as exportSec1Pem,x as exportSpkiDer,pe as exportSpkiPem,ie as generateKeyPair,xe as importEncryptedPkcs1Pem,B as importEncryptedPkcs1PemOrThrow,F as importEncryptedPkcs8Der,P as importEncryptedPkcs8DerOrThrow,ye as importEncryptedPkcs8Pem,I as importEncryptedPkcs8PemOrThrow,Te as importEncryptedSec1Pem,W as importEncryptedSec1PemOrThrow,be as importPkcs1Der,L as importPkcs1DerOrThrow,z as importPkcs1Pem,R as importPkcs1PemOrThrow,Se as importPkcs8Base64,V as importPkcs8Base64OrThrow,ve as importPkcs8Der,j as importPkcs8DerOrThrow,N as importPkcs8Pem,M as importPkcs8PemOrThrow,De as importPrivateJwk,K as importPrivateJwkOrThrow,Ee as importPublicJwk,G as importPublicJwkOrThrow,Ce as importSec1Der,H as importSec1DerOrThrow,we as importSec1Pem,U as importSec1PemOrThrow,_e as importSpkiBase64,A as importSpkiBase64OrThrow,he as importSpkiDer,E as importSpkiDerOrThrow,ge as importSpkiPem,k as importSpkiPemOrThrow};
5
5
  //# sourceMappingURL=keys.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"keys.js","names":[],"sources":["../../src/keys/keys.ts"],"sourcesContent":["/**\n * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.\n *\n * Supports RSA (PKCS#1v1.5 and PSS), ECDSA (P-256, P-384, P-521), and Ed25519 keys.\n * All functions use the WebCrypto API and return extractable keys.\n *\n * @example\n * ```ts\n * import { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const privatePem = await exportPkcs8Pem(keys.privateKey);\n *\n * // Import\n * const publicKey = await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @module\n */\n\nimport {\n\tdecodeObjectIdentifier,\n\textractBitStringValue,\n\thexToBytes,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { md5 } from '#micro509/internal/crypto/hash.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\n\n/** Hash algorithm paired with an RSA key. */\nexport type RsaHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** RSA signature padding scheme. */\nexport type RsaScheme = 'pkcs1-v1_5' | 'pss';\n\n/** NIST elliptic curve for ECDSA keys. */\nexport type EcNamedCurve = 'P-256' | 'P-384' | 'P-521';\n\n/** RSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface RsaKeyAlgorithmInput {\n\t/** Discriminant selecting RSA key generation. */\n\treadonly kind: 'rsa';\n\t/** RSA modulus size in bits. Defaults to `2048`. */\n\treadonly modulusLength?: 2048 | 3072 | 4096;\n\t/** Hash algorithm for the key. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface EcKeyAlgorithmInput {\n\t/** Discriminant selecting ECDSA key generation. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve. Defaults to `'P-256'`. */\n\treadonly curve?: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode KeyAlgorithmInput}. */\nexport interface Ed25519KeyAlgorithmInput {\n\t/** Discriminant selecting Ed25519 key generation. */\n\treadonly kind: 'ed25519';\n}\n\n/** Input for {@linkcode generateKeyPair}. Selects algorithm family and parameters. */\nexport type KeyAlgorithmInput =\n\t| RsaKeyAlgorithmInput\n\t| EcKeyAlgorithmInput\n\t| Ed25519KeyAlgorithmInput;\n\n/** Key pair with convenience export helpers. Returned by {@linkcode generateKeyPair}. */\nexport interface KeyPairMaterial {\n\t/** The WebCrypto public key (extractable, `verify` usage). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage). */\n\treadonly privateKey: CryptoKey;\n\t/** Export the public key as DER-encoded SubjectPublicKeyInfo. */\n\texportSpkiDer(): Promise<Uint8Array>;\n\t/** Export the public key as PEM-encoded SubjectPublicKeyInfo. */\n\texportSpkiPem(): Promise<string>;\n\t/** Export the private key as DER-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Der(): Promise<Uint8Array>;\n\t/** Export the private key as PEM-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Pem(): Promise<string>;\n\t/** Export the public key as a JSON Web Key. */\n\texportPublicJwk(): Promise<JsonWebKey>;\n\t/** Export the private key as a JSON Web Key. */\n\texportPrivateJwk(): Promise<JsonWebKey>;\n}\n\n/** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportRsaKeyInput {\n\t/** Discriminant selecting RSA import. */\n\treadonly kind: 'rsa';\n\t/** Hash algorithm. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEcKeyInput {\n\t/** Discriminant selecting ECDSA import. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve the key belongs to. Required for EC import. */\n\treadonly curve: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEd25519KeyInput {\n\t/** Discriminant selecting Ed25519 import. */\n\treadonly kind: 'ed25519';\n}\n\n/** Algorithm descriptor for public key import functions. */\nexport type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\n/** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */\nexport type PrivateKeyImportInput = PublicKeyImportInput;\n\n/** PBES2 encryption options for the encrypted PKCS#8 export/import functions. */\nexport type EncryptedPkcs8Options = Pbes2EncryptionOptions;\n\n/** Options for OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM encryption (PKCS#1/SEC1). */\nexport interface LegacyPemEncryptionOptions {\n\t/** Passphrase used to derive the encryption key. */\n\treadonly password: string;\n\t/** 16-byte initialization vector. Random when omitted. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Defaults to `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n}\n\n/** Machine-readable failure reason for the `import*` key functions. */\nexport type ImportKeyErrorCode = 'malformed';\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `import*` key functions.\n *\n * On failure, `code` is always `'malformed'`: structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures all surface\n * the same way (see the throwing `*OrThrow` variants for raw error messages).\n */\nexport type ImportKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>;\n\n/**\n * Machine-readable failure reason for the `importEncrypted*` key functions.\n *\n * Distinguishes a wrong decryption password (`'invalid_password'`) from\n * structurally invalid input or algorithm mismatches (`'malformed'`).\n */\nexport type ImportEncryptedKeyErrorCode = 'malformed' | 'invalid_password';\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `importEncrypted*` key functions.\n *\n * On failure, `code` is `'invalid_password'` when decryption failed (wrong\n * password or corrupted ciphertext) and `'malformed'` for everything else.\n */\nexport type ImportEncryptedKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportEncryptedKeyErrorCode, Record<never, never>, ImportEncryptedKeyFailure>;\n\n/**\n * Generate an asymmetric key pair for signing and verification.\n *\n * @example\n * ```ts\n * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });\n * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });\n * const edKeys = await generateKeyPair({ kind: 'ed25519' });\n *\n * // Default: ECDSA P-256\n * const keys = await generateKeyPair();\n * const pem = await keys.exportPkcs8Pem();\n * ```\n */\nexport async function generateKeyPair(\n\talgorithm: KeyAlgorithmInput = { kind: 'ecdsa', curve: 'P-256' },\n): Promise<KeyPairMaterial> {\n\tconst subtle = getCrypto().subtle;\n\tconst generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, [\n\t\t'sign',\n\t\t'verify',\n\t]);\n\n\tif (!('publicKey' in generated) || !('privateKey' in generated)) {\n\t\tthrow new Error('Expected an asymmetric key pair');\n\t}\n\n\treturn wrapKeyPair(generated.publicKey, generated.privateKey);\n}\n\nfunction wrapKeyPair(publicKey: CryptoKey, privateKey: CryptoKey): KeyPairMaterial {\n\treturn {\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tasync exportSpkiDer() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n\t\t},\n\t\tasync exportSpkiPem() {\n\t\t\treturn pemEncode('PUBLIC KEY', await this.exportSpkiDer());\n\t\t},\n\t\tasync exportPkcs8Der() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n\t\t},\n\t\tasync exportPkcs8Pem() {\n\t\t\treturn pemEncode('PRIVATE KEY', await this.exportPkcs8Der());\n\t\t},\n\t\tasync exportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\tasync exportPrivateJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n\t\t},\n\t};\n}\n\n/**\n * Export a public key as DER-encoded SubjectPublicKeyInfo.\n *\n * @see {@linkcode importSpkiDer} for the inverse operation\n * @see {@linkcode exportSpkiPem} for PEM output\n */\nexport async function exportSpkiDer(publicKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n}\n\n/**\n * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see {@linkcode importPkcs8Der} for the inverse operation\n * @see {@linkcode exportPkcs8Pem} for PEM output\n * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export\n */\nexport async function exportPkcs8Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n}\n\n/**\n * Export a public key as a JSON Web Key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const jwk = await exportPublicJwk(keys.publicKey);\n * ```\n */\nexport async function exportPublicJwk(publicKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n}\n\n/**\n * Export a private key as a JSON Web Key.\n *\n * @see {@linkcode importPrivateJwk} for the inverse operation\n * @see {@linkcode exportPublicJwk} for public key export\n */\nexport async function exportPrivateJwk(privateKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n}\n\n/**\n * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportPkcs8Pem(keys.privateKey);\n * // -----BEGIN PRIVATE KEY-----\n * // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...\n * // -----END PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importPkcs8Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export\n */\nexport async function exportPkcs8Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PRIVATE KEY', await exportPkcs8Der(privateKey));\n}\n\n/**\n * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.\n *\n * @param privateKey - The private key to export\n * @param options - Encryption options including password and optional algorithm settings\n *\n * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output\n */\nexport async function exportEncryptedPkcs8Der(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst encryption = await encryptPbes2(pkcs8, options);\n\treturn sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);\n}\n\n/**\n * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });\n * // -----BEGIN ENCRYPTED PRIVATE KEY-----\n * // MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...\n * // -----END ENCRYPTED PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs8Pem(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<string> {\n\treturn pemEncode('ENCRYPTED PRIVATE KEY', await exportEncryptedPkcs8Der(privateKey, options));\n}\n\n/**\n * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Der} for the inverse operation\n * @see {@linkcode exportPkcs1Pem} for PEM output\n */\nexport async function exportPkcs1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.rsaEncryption) {\n\t\tthrow new Error('PKCS#1 export requires an RSA private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export\n */\nexport async function exportPkcs1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('RSA PRIVATE KEY', await exportPkcs1Der(privateKey));\n}\n\n/**\n * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('RSA PRIVATE KEY', await exportPkcs1Der(privateKey), options);\n}\n\n/**\n * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Der} for the inverse operation\n * @see {@linkcode exportSec1Pem} for PEM output\n */\nexport async function exportSec1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.ecPublicKey) {\n\t\tthrow new Error('SEC1 export requires an EC private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedSec1Pem} for password-protected export\n */\nexport async function exportSec1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('EC PRIVATE KEY', await exportSec1Der(privateKey));\n}\n\n/**\n * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importEncryptedSec1Pem} for the inverse operation\n */\nexport async function exportEncryptedSec1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('EC PRIVATE KEY', await exportSec1Der(privateKey), options);\n}\n\n/**\n * Export a public key as PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportSpkiPem(keys.publicKey);\n * ```\n */\nexport async function exportSpkiPem(publicKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PUBLIC KEY', await exportSpkiDer(publicKey));\n}\n\n/**\n * Export a key as raw base64 (no PEM headers).\n *\n * Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys.\n * Useful for compact storage or transmission where PEM overhead is undesirable.\n *\n * @throws {Error} If the key is a symmetric/secret key\n *\n * @see {@linkcode importSpkiBase64} for public key import\n * @see {@linkcode importPkcs8Base64} for private key import\n */\nexport async function exportBinaryBase64(key: CryptoKey): Promise<string> {\n\tif (key.type === 'public') {\n\t\treturn base64Encode(await exportSpkiDer(key));\n\t}\n\tif (key.type === 'private') {\n\t\treturn base64Encode(await exportPkcs8Der(key));\n\t}\n\tthrow new Error('Cannot export secret/symmetric CryptoKey');\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\n *\n * @see {@linkcode exportSpkiDer} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input\n */\nexport async function importSpkiDerOrThrow(\n\tder: Uint8Array,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst parsedSpki = parseSpkiDer(der);\n\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['verify'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` result; invariants rethrow. */\nasync function importResult(run: () => Promise<CryptoKey>): Promise<ImportKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed key');\n\t}\n}\n\n/** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */\nasync function encryptedImportResult(\n\trun: () => Promise<CryptoKey>,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn failureResult('invalid_password', error.message);\n\t\t}\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed encrypted key',\n\t\t);\n\t}\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiDerOrThrow` for the throwing variant\n */\nexport function importSpkiDer(\n\tder: Uint8Array,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiDerOrThrow(der, algorithm));\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const pem = `-----BEGIN PUBLIC KEY-----\n * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n * -----END PUBLIC KEY-----`;\n * const key = await importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport async function importSpkiPemOrThrow(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importSpkiDerOrThrow(pemDecodeOrThrow('PUBLIC KEY', pem), algorithm);\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiPemOrThrow` for the throwing variant\n */\nexport function importSpkiPem(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiPemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input with headers\n */\nexport async function importSpkiBase64OrThrow(\n\tbase64: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 SubjectPublicKeyInfo');\n\t}\n\treturn importSpkiDerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see `importSpkiBase64OrThrow` for the throwing variant\n */\nexport function importSpkiBase64(\n\tbase64: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiBase64OrThrow(base64, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\n *\n * @see {@linkcode exportPkcs8Der} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input\n * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8\n */\nexport async function importPkcs8DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet parsedPrivateKey: ReturnType<typeof parsePkcs8PrivateKey>;\n\ttry {\n\t\tparsedPrivateKey = parsePkcs8PrivateKey(der);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['sign'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8DerOrThrow` for the throwing variant\n */\nexport function importPkcs8Der(\n\tder: Uint8Array,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8DerOrThrow(der, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPkcs8PemOrThrow(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(pemDecodeOrThrow('PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8PemOrThrow` for the throwing variant\n */\nexport function importPkcs8Pem(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Decrypts the PBES2 envelope using the provided password, then imports the key.\n *\n * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Expected algorithm (must match decrypted key)\n *\n * @throws {Error} If DER is malformed, password is wrong, or algorithm doesn't match\n *\n * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation\n */\nexport async function importEncryptedPkcs8DerOrThrow(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst algorithmIdentifier = children[0];\n\tconst encryptedData = children[1];\n\tif (\n\t\tchildren.length !== 2 ||\n\t\talgorithmIdentifier === undefined ||\n\t\tencryptedData === undefined ||\n\t\tencryptedData.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst decrypted = await decryptPbes2(\n\t\tder.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData.value,\n\t\tpassword,\n\t);\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Der(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importEncryptedPkcs8DerOrThrow(\n\t\tpemDecodeOrThrow('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportPkcs1Der} for the inverse operation\n * @see {@linkcode importPkcs1Pem} for PEM input\n */\nexport async function importPkcs1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1DerOrThrow` for the throwing variant\n */\nexport function importPkcs1Der(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * Expects the `-----BEGIN RSA PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM\n */\nexport async function importPkcs1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs1DerOrThrow(pemDecodeOrThrow('RSA PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1PemOrThrow` for the throwing variant\n */\nexport function importPkcs1Pem(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedPkcs1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('RSA PRIVATE KEY', pem, password);\n\treturn importPkcs1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input with headers\n */\nexport async function importPkcs8Base64OrThrow(\n\tbase64: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 PKCS#8 private key');\n\t}\n\treturn importPkcs8DerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see `importPkcs8Base64OrThrow` for the throwing variant\n */\nexport function importPkcs8Base64(\n\tbase64: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8Base64OrThrow(base64, algorithm));\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportSec1Der} for the inverse operation\n * @see {@linkcode importSec1Pem} for PEM input\n */\nexport async function importSec1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1DerOrThrow` for the throwing variant\n */\nexport function importSec1Der(\n\tder: Uint8Array,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport async function importSec1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importSec1DerOrThrow(pemDecodeOrThrow('EC PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1PemOrThrow` for the throwing variant\n */\nexport function importSec1Pem(\n\tpem: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedSec1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('EC PRIVATE KEY', pem, password);\n\treturn importSec1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * @see `importEncryptedSec1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedSec1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed or algorithm doesn't match\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, [\n\t\t\t'verify',\n\t\t]);\n\t} catch {\n\t\tthrow new Error('Malformed public JWK');\n\t}\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @see `importPublicJwkOrThrow` for the throwing variant\n */\nexport function importPublicJwk(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPublicJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, ['sign']);\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @see `importPrivateJwkOrThrow` for the throwing variant\n */\nexport function importPrivateJwk(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPrivateJwkOrThrow(jwk, algorithm));\n}\n\n/** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */\nfunction toGenerateKeyAlgorithm(\n\talgorithm: KeyAlgorithmInput,\n): EcKeyGenParams | RsaHashedKeyGenParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\tmodulusLength: algorithm.modulusLength ?? 2048,\n\t\t\t\tpublicExponent: Uint8Array.of(0x01, 0x00, 0x01),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve ?? 'P-256',\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t}\n}\n\n/** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */\nfunction toImportAlgorithm(\n\talgorithm: PublicKeyImportInput,\n): EcKeyImportParams | RsaHashedImportParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve,\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t}\n}\n\n/** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */\nfunction parsePkcs8PrivateKey(der: Uint8Array): {\n\t/** OID identifying the algorithm family (e.g. rsaEncryption, ecPublicKey). */\n\treadonly algorithmOid: string;\n\t/** Optional algorithm parameter OID (e.g. named curve for EC keys). */\n\treadonly parametersOid?: string;\n\t/** Optional algorithm parameter tag. */\n\treadonly parametersTag?: number;\n\t/** Raw DER of the inner private key (PKCS#1 for RSA, SEC 1 for EC). */\n\treadonly privateKeyDer: Uint8Array;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tchildren.length > 4 ||\n\t\talgorithm === undefined ||\n\t\talgorithm.tag !== 0x30 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst algorithmChildren = readSequenceChildren(\n\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\talgorithmOid.tag !== 0x06 ||\n\t\talgorithmChildren.length < 1 ||\n\t\talgorithmChildren.length > 2\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst parameters = algorithmChildren[1];\n\treturn {\n\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t...(parameters?.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t: {}),\n\t\tprivateKeyDer: privateKey.value,\n\t};\n}\n\n/** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapPkcs1InPkcs8(der: Uint8Array): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapSec1InPkcs8(der: Uint8Array, curve: ImportEcKeyInput['curve']): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcKeyInput['curve']): string {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn OIDS.prime256v1;\n\t\tcase 'P-384':\n\t\t\treturn OIDS.secp384r1;\n\t\tcase 'P-521':\n\t\t\treturn OIDS.secp521r1;\n\t}\n}\n\n/** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */\nfunction rsaSchemeToWebCryptoAlgorithmName(\n\tscheme: RsaScheme | undefined,\n): 'RSASSA-PKCS1-v1_5' | 'RSA-PSS' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\n}\n\n/** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */\nasync function encryptTraditionalPem(\n\tlabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tder: Uint8Array,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tif (iv.length !== 16) {\n\t\tthrow new Error('Traditional PEM encryption requires a 16-byte IV');\n\t}\n\tconst cipher = options.cipher ?? 'AES-256-CBC';\n\tconst key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, [\n\t\t'encrypt',\n\t]);\n\tconst encrypted = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(der),\n\t\t),\n\t);\n\tconst body =\n\t\tbase64Encode(encrypted)\n\t\t\t.match(/.{1,64}/g)\n\t\t\t?.join('\\n') ?? '';\n\treturn [\n\t\t`-----BEGIN ${label}-----`,\n\t\t'Proc-Type: 4,ENCRYPTED',\n\t\t`DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,\n\t\t'',\n\t\tbody,\n\t\t`-----END ${label}-----`,\n\t].join('\\n');\n}\n\n/** Decrypt an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back to plaintext DER. */\nasync function decryptTraditionalPem(\n\texpectedLabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tpem: string,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parsed = parseTraditionalPem(pem);\n\tif (parsed.label !== expectedLabel) {\n\t\tthrow new Error(`Expected ${expectedLabel} PEM block`);\n\t}\n\tconst dekInfo = parsed.headers.get('DEK-Info');\n\tif (parsed.headers.get('Proc-Type') !== '4,ENCRYPTED' || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',');\n\tif (!isTraditionalPemCipher(cipher) || ivHex === undefined) {\n\t\tthrow new Error(\n\t\t\t'Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported',\n\t\t);\n\t}\n\tif (!isTraditionalPemIvHex(ivHex)) {\n\t\tthrow new Error(\n\t\t\t'Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters',\n\t\t);\n\t}\n\tconst iv = hexToBytes(ivHex);\n\tconst key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ['decrypt']);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(base64Decode(parsed.base64Body)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted PEM content');\n\t}\n}\n\n/** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */\nasync function importTraditionalPemAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst keyLength = traditionalPemCipherKeyLength(cipher);\n\tconst keyBytes = opensslBytesToKey(password, salt, keyLength / 8);\n\treturn getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'AES-CBC', length: keyLength },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */\nfunction isTraditionalPemCipher(\n\tcipher: string | undefined,\n): cipher is 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC' {\n\treturn cipher === 'AES-128-CBC' || cipher === 'AES-192-CBC' || cipher === 'AES-256-CBC';\n}\n\nfunction isTraditionalPemIvHex(value: string): boolean {\n\treturn value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);\n}\n\n/** Return the AES key size in bits for a given cipher name. */\nfunction traditionalPemCipherKeyLength(\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n): 128 | 192 | 256 {\n\tswitch (cipher) {\n\t\tcase 'AES-128-CBC':\n\t\t\treturn 128;\n\t\tcase 'AES-192-CBC':\n\t\t\treturn 192;\n\t\tcase 'AES-256-CBC':\n\t\t\treturn 256;\n\t}\n}\n\n/** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */\nfunction opensslBytesToKey(password: string, salt: Uint8Array, length: number): Uint8Array {\n\tconst passwordBytes = new TextEncoder().encode(password);\n\tconst chunks: Uint8Array[] = [];\n\tlet previous = new Uint8Array();\n\tlet total = 0;\n\twhile (total < length) {\n\t\tconst input = new Uint8Array(previous.length + passwordBytes.length + salt.length);\n\t\tinput.set(previous, 0);\n\t\tinput.set(passwordBytes, previous.length);\n\t\tinput.set(salt, previous.length + passwordBytes.length);\n\t\tprevious = md5(input);\n\t\tchunks.push(previous);\n\t\ttotal += previous.length;\n\t}\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tconst slice = chunk.slice(0, Math.min(chunk.length, length - offset));\n\t\tout.set(slice, offset);\n\t\toffset += slice.length;\n\t\tif (offset >= length) {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */\nfunction parseTraditionalPem(pem: string): {\n\t/** PEM type label between `BEGIN` and `END` markers. */\n\treadonly label: string;\n\t/** RFC 1421 encapsulated headers (e.g. `Proc-Type`, `DEK-Info`). */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n} {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst lines = normalized.split('\\n');\n\tconst begin = lines[0];\n\tconst end = lines[lines.length - 1];\n\tif (\n\t\tbegin === undefined ||\n\t\tend === undefined ||\n\t\t!begin.startsWith('-----BEGIN ') ||\n\t\t!end.startsWith('-----END ')\n\t) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tconst label = begin.slice(11, -5);\n\tif (end !== `-----END ${label}-----`) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tconst delimiter = line.indexOf(': ');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 2));\n\t\tindex += 1;\n\t}\n\tconst body = lines.slice(index, lines.length - 1).join('');\n\treturn { label, headers, base64Body: body };\n}\n\nfunction parseSpkiDer(der: Uint8Array): {\n\treadonly algorithmOid: string;\n\treadonly parametersOid?: string;\n\treadonly parametersTag?: number;\n} {\n\ttry {\n\t\tconst children = readSequenceChildren(der);\n\t\tif (children.length !== 2) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst algorithm = children[0];\n\t\tconst subjectPublicKey = children[1];\n\t\tif (\n\t\t\talgorithm === undefined ||\n\t\t\talgorithm.tag !== 0x30 ||\n\t\t\tsubjectPublicKey === undefined ||\n\t\t\tsubjectPublicKey.tag !== 0x03\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\textractBitStringValue(subjectPublicKey);\n\t\tconst algorithmChildren = readSequenceChildren(\n\t\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\t);\n\t\tconst algorithmOid = algorithmChildren[0];\n\t\tif (\n\t\t\talgorithmOid === undefined ||\n\t\t\talgorithmOid.tag !== 0x06 ||\n\t\t\talgorithmChildren.length < 1 ||\n\t\t\talgorithmChildren.length > 2\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst parameters = algorithmChildren[1];\n\t\treturn {\n\t\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t\t...(parameters?.tag === 0x06\n\t\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t\t: {}),\n\t\t};\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\nfunction assertSpkiMatchesRequestedAlgorithm(\n\tparsedSpki: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PublicKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedSpki.parametersTag !== undefined && parsedSpki.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedSpki.parametersTag !== 0x06 ||\n\t\t\t\tparsedSpki.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== undefined) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n\nfunction assertPkcs8MatchesRequestedAlgorithm(\n\tparsedPrivateKey: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedPrivateKey.parametersTag !== undefined && parsedPrivateKey.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedPrivateKey.parametersTag !== 0x06 ||\n\t\t\t\tparsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ed25519 ||\n\t\t\t\tparsedPrivateKey.parametersTag !== undefined\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n\nfunction assertPublicJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): void {\n\tif (\n\t\tjwk.k !== undefined ||\n\t\tjwk.d !== undefined ||\n\t\tjwk.p !== undefined ||\n\t\tjwk.q !== undefined ||\n\t\tjwk.dp !== undefined ||\n\t\tjwk.dq !== undefined ||\n\t\tjwk.qi !== undefined ||\n\t\tjwk.oth !== undefined\n\t) {\n\t\tthrow new Error('Public JWK must not contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n"],"mappings":"4xBA6NA,eAAsB,GACrB,EAA+B,CAAE,KAAM,QAAS,MAAO,OAAQ,EACpC,CAE3B,IAAM,EAAY,MADH,EAAU,CAAC,CAAC,OACI,YAAY,GAAuB,CAAS,EAAG,GAAM,CACnF,OACA,QACD,CAAC,EAED,GAAI,EAAE,cAAe,IAAc,EAAE,eAAgB,GACpD,MAAU,MAAM,iCAAiC,EAGlD,OAAO,EAAY,EAAU,UAAW,EAAU,UAAU,CAC7D,CAEA,SAAS,EAAY,EAAsB,EAAwC,CAClF,MAAO,CACN,YACA,aACA,MAAM,eAAgB,CACrB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,OAAQ,CAAS,CAAC,CAC5E,EACA,MAAM,eAAgB,CACrB,OAAO,EAAU,aAAc,MAAM,KAAK,cAAc,CAAC,CAC1D,EACA,MAAM,gBAAiB,CACtB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,QAAS,CAAU,CAAC,CAC9E,EACA,MAAM,gBAAiB,CACtB,OAAO,EAAU,cAAe,MAAM,KAAK,eAAe,CAAC,CAC5D,EACA,MAAM,iBAAkB,CACvB,OAAO,EAAU,CAAC,CAAC,OAAO,UAAU,MAAO,CAAS,CACrD,EACA,MAAM,kBAAmB,CACxB,OAAO,EAAU,CAAC,CAAC,OAAO,UAAU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I,MAAQ,MACZ,EAAI,MAAQ,EAAU,OACtB,OAAO,EAAI,GAAM,UACjB,OAAO,EAAI,GAAM,SAEjB,MAAU,MAAM,gEAAgE,EAEjF,OACD,IAAK,UACJ,GAAI,EAAI,MAAQ,OAAS,EAAI,MAAQ,WAAa,OAAO,EAAI,GAAM,SAClE,MAAU,MAAM,gEAAgE,EAEjF,MACF,CACD"}
1
+ {"version":3,"file":"keys.js","names":[],"sources":["../../src/keys/keys.ts"],"sourcesContent":["/**\n * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.\n *\n * Supports RSA (PKCS#1v1.5 and PSS), ECDSA (P-256, P-384, P-521), and Ed25519 keys.\n * All functions use the WebCrypto API and return extractable keys.\n *\n * @example\n * ```ts\n * import { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const privatePem = await exportPkcs8Pem(keys.privateKey);\n *\n * // Import\n * const publicKey = await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @module\n */\n\nimport {\n\tdecodeObjectIdentifier,\n\textractBitStringValue,\n\thexToBytes,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { md5 } from '#micro509/internal/crypto/hash.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\n\n/** Hash algorithm paired with an RSA key. */\nexport type RsaHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** RSA signature padding scheme. */\nexport type RsaScheme = 'pkcs1-v1_5' | 'pss';\n\n/** NIST elliptic curve for ECDSA keys. */\nexport type EcNamedCurve = 'P-256' | 'P-384' | 'P-521';\n\n/** RSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface RsaKeyAlgorithmInput {\n\t/** Discriminant selecting RSA key generation. */\n\treadonly kind: 'rsa';\n\t/** RSA modulus size in bits. Defaults to `2048`. */\n\treadonly modulusLength?: 2048 | 3072 | 4096;\n\t/** Hash algorithm for the key. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface EcKeyAlgorithmInput {\n\t/** Discriminant selecting ECDSA key generation. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve. Defaults to `'P-256'`. */\n\treadonly curve?: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode KeyAlgorithmInput}. */\nexport interface Ed25519KeyAlgorithmInput {\n\t/** Discriminant selecting Ed25519 key generation. */\n\treadonly kind: 'ed25519';\n}\n\n/** Input for {@linkcode generateKeyPair}. Selects algorithm family and parameters. */\nexport type KeyAlgorithmInput =\n\t| RsaKeyAlgorithmInput\n\t| EcKeyAlgorithmInput\n\t| Ed25519KeyAlgorithmInput;\n\n/** Key pair with convenience export helpers. Returned by {@linkcode generateKeyPair}. */\nexport interface KeyPairMaterial {\n\t/** The WebCrypto public key (extractable, `verify` usage). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage). */\n\treadonly privateKey: CryptoKey;\n\t/** Export the public key as DER-encoded SubjectPublicKeyInfo. */\n\texportSpkiDer(): Promise<Uint8Array>;\n\t/** Export the public key as PEM-encoded SubjectPublicKeyInfo. */\n\texportSpkiPem(): Promise<string>;\n\t/** Export the private key as DER-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Der(): Promise<Uint8Array>;\n\t/** Export the private key as PEM-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Pem(): Promise<string>;\n\t/** Export the public key as a JSON Web Key. */\n\texportPublicJwk(): Promise<JsonWebKey>;\n\t/** Export the private key as a JSON Web Key. */\n\texportPrivateJwk(): Promise<JsonWebKey>;\n}\n\n/** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportRsaKeyInput {\n\t/** Discriminant selecting RSA import. */\n\treadonly kind: 'rsa';\n\t/** Hash algorithm. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEcKeyInput {\n\t/** Discriminant selecting ECDSA import. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve the key belongs to. Required for EC import. */\n\treadonly curve: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEd25519KeyInput {\n\t/** Discriminant selecting Ed25519 import. */\n\treadonly kind: 'ed25519';\n}\n\n/** Algorithm descriptor for public key import functions. */\nexport type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\n/** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */\nexport type PrivateKeyImportInput = PublicKeyImportInput;\n\n/** PBES2 encryption options for the encrypted PKCS#8 export/import functions. */\nexport type EncryptedPkcs8Options = Pbes2EncryptionOptions;\n\n/** Options for OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM encryption (PKCS#1/SEC1). */\nexport interface LegacyPemEncryptionOptions {\n\t/** Passphrase used to derive the encryption key. */\n\treadonly password: string;\n\t/** 16-byte initialization vector. Random when omitted. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Defaults to `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n}\n\n/** Machine-readable failure reason for the `import*` key functions. */\nexport type ImportKeyErrorCode = 'malformed';\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `import*` key functions.\n *\n * On failure, `code` is always `'malformed'`: structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures all surface\n * the same way (see the throwing `*OrThrow` variants for raw error messages).\n */\nexport type ImportKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>;\n\n/**\n * Machine-readable failure reason for the `importEncrypted*` key functions.\n *\n * Distinguishes a wrong decryption password (`'invalid_password'`) from\n * structurally invalid input or algorithm mismatches (`'malformed'`).\n */\nexport type ImportEncryptedKeyErrorCode = 'malformed' | 'invalid_password';\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `importEncrypted*` key functions.\n *\n * On failure, `code` is `'invalid_password'` when decryption failed (wrong\n * password or corrupted ciphertext) and `'malformed'` for everything else.\n */\nexport type ImportEncryptedKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportEncryptedKeyErrorCode, Record<never, never>, ImportEncryptedKeyFailure>;\n\n/**\n * Generate an asymmetric key pair for signing and verification.\n *\n * @example\n * ```ts\n * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });\n * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });\n * const edKeys = await generateKeyPair({ kind: 'ed25519' });\n *\n * // Default: ECDSA P-256\n * const keys = await generateKeyPair();\n * const pem = await keys.exportPkcs8Pem();\n * ```\n */\nexport async function generateKeyPair(\n\talgorithm: KeyAlgorithmInput = { kind: 'ecdsa', curve: 'P-256' },\n): Promise<KeyPairMaterial> {\n\tconst subtle = getCrypto().subtle;\n\tconst generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, [\n\t\t'sign',\n\t\t'verify',\n\t]);\n\n\tif (!('publicKey' in generated) || !('privateKey' in generated)) {\n\t\tthrow new Error('Expected an asymmetric key pair');\n\t}\n\n\treturn wrapKeyPair(generated.publicKey, generated.privateKey);\n}\n\nfunction wrapKeyPair(publicKey: CryptoKey, privateKey: CryptoKey): KeyPairMaterial {\n\treturn {\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tasync exportSpkiDer() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n\t\t},\n\t\tasync exportSpkiPem() {\n\t\t\treturn pemEncode('PUBLIC KEY', await this.exportSpkiDer());\n\t\t},\n\t\tasync exportPkcs8Der() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n\t\t},\n\t\tasync exportPkcs8Pem() {\n\t\t\treturn pemEncode('PRIVATE KEY', await this.exportPkcs8Der());\n\t\t},\n\t\tasync exportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\tasync exportPrivateJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n\t\t},\n\t};\n}\n\n/**\n * Export a public key as DER-encoded SubjectPublicKeyInfo.\n *\n * @see {@linkcode importSpkiDer} for the inverse operation\n * @see {@linkcode exportSpkiPem} for PEM output\n */\nexport async function exportSpkiDer(publicKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n}\n\n/**\n * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see {@linkcode importPkcs8Der} for the inverse operation\n * @see {@linkcode exportPkcs8Pem} for PEM output\n * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export\n */\nexport async function exportPkcs8Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n}\n\n/**\n * Export a public key as a JSON Web Key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const jwk = await exportPublicJwk(keys.publicKey);\n * ```\n */\nexport async function exportPublicJwk(publicKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n}\n\n/**\n * Export a private key as a JSON Web Key.\n *\n * @see {@linkcode importPrivateJwk} for the inverse operation\n * @see {@linkcode exportPublicJwk} for public key export\n */\nexport async function exportPrivateJwk(privateKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n}\n\n/**\n * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportPkcs8Pem(keys.privateKey);\n * // -----BEGIN PRIVATE KEY-----\n * // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...\n * // -----END PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importPkcs8Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export\n */\nexport async function exportPkcs8Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PRIVATE KEY', await exportPkcs8Der(privateKey));\n}\n\n/**\n * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.\n *\n * @param privateKey - The private key to export\n * @param options - Encryption options including password and optional algorithm settings\n *\n * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output\n */\nexport async function exportEncryptedPkcs8Der(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst encryption = await encryptPbes2(pkcs8, options);\n\treturn sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);\n}\n\n/**\n * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });\n * // -----BEGIN ENCRYPTED PRIVATE KEY-----\n * // MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...\n * // -----END ENCRYPTED PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs8Pem(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<string> {\n\treturn pemEncode('ENCRYPTED PRIVATE KEY', await exportEncryptedPkcs8Der(privateKey, options));\n}\n\n/**\n * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Der} for the inverse operation\n * @see {@linkcode exportPkcs1Pem} for PEM output\n */\nexport async function exportPkcs1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.rsaEncryption) {\n\t\tthrow new Error('PKCS#1 export requires an RSA private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export\n */\nexport async function exportPkcs1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('RSA PRIVATE KEY', await exportPkcs1Der(privateKey));\n}\n\n/**\n * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('RSA PRIVATE KEY', await exportPkcs1Der(privateKey), options);\n}\n\n/**\n * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Der} for the inverse operation\n * @see {@linkcode exportSec1Pem} for PEM output\n */\nexport async function exportSec1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.ecPublicKey) {\n\t\tthrow new Error('SEC1 export requires an EC private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedSec1Pem} for password-protected export\n */\nexport async function exportSec1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('EC PRIVATE KEY', await exportSec1Der(privateKey));\n}\n\n/**\n * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importEncryptedSec1Pem} for the inverse operation\n */\nexport async function exportEncryptedSec1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('EC PRIVATE KEY', await exportSec1Der(privateKey), options);\n}\n\n/**\n * Export a public key as PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportSpkiPem(keys.publicKey);\n * ```\n */\nexport async function exportSpkiPem(publicKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PUBLIC KEY', await exportSpkiDer(publicKey));\n}\n\n/**\n * Export a key as raw base64 (no PEM headers).\n *\n * Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys.\n * Useful for compact storage or transmission where PEM overhead is undesirable.\n *\n * @throws {Error} If the key is a symmetric/secret key\n *\n * @see {@linkcode importSpkiBase64} for public key import\n * @see {@linkcode importPkcs8Base64} for private key import\n */\nexport async function exportBinaryBase64(key: CryptoKey): Promise<string> {\n\tif (key.type === 'public') {\n\t\treturn base64Encode(await exportSpkiDer(key));\n\t}\n\tif (key.type === 'private') {\n\t\treturn base64Encode(await exportPkcs8Der(key));\n\t}\n\tthrow new Error('Cannot export secret/symmetric CryptoKey');\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\n *\n * @see {@linkcode exportSpkiDer} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input\n */\nexport async function importSpkiDerOrThrow(\n\tder: Uint8Array,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst parsedSpki = parseSpkiDer(der);\n\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['verify'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` result; invariants rethrow. */\nasync function importResult(run: () => Promise<CryptoKey>): Promise<ImportKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed key');\n\t}\n}\n\n/** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */\nasync function encryptedImportResult(\n\trun: () => Promise<CryptoKey>,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn failureResult('invalid_password', error.message);\n\t\t}\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed encrypted key',\n\t\t);\n\t}\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiDerOrThrow` for the throwing variant\n */\nexport function importSpkiDer(\n\tder: Uint8Array,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiDerOrThrow(der, algorithm));\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const pem = `-----BEGIN PUBLIC KEY-----\n * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n * -----END PUBLIC KEY-----`;\n * const key = await importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport async function importSpkiPemOrThrow(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importSpkiDerOrThrow(pemDecodeOrThrow('PUBLIC KEY', pem), algorithm);\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiPemOrThrow` for the throwing variant\n */\nexport function importSpkiPem(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiPemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input with headers\n */\nexport async function importSpkiBase64OrThrow(\n\tbase64: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 SubjectPublicKeyInfo');\n\t}\n\treturn importSpkiDerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see `importSpkiBase64OrThrow` for the throwing variant\n */\nexport function importSpkiBase64(\n\tbase64: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiBase64OrThrow(base64, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\n *\n * @see {@linkcode exportPkcs8Der} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input\n * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8\n */\nexport async function importPkcs8DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet parsedPrivateKey: ReturnType<typeof parsePkcs8PrivateKey>;\n\ttry {\n\t\tparsedPrivateKey = parsePkcs8PrivateKey(der);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['sign'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8DerOrThrow` for the throwing variant\n */\nexport function importPkcs8Der(\n\tder: Uint8Array,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8DerOrThrow(der, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPkcs8PemOrThrow(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(pemDecodeOrThrow('PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8PemOrThrow` for the throwing variant\n */\nexport function importPkcs8Pem(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Decrypts the PBES2 envelope using the provided password, then imports the key.\n *\n * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Expected algorithm (must match decrypted key)\n *\n * @throws {Error} If DER is malformed, password is wrong, or algorithm doesn't match\n *\n * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation\n */\nexport async function importEncryptedPkcs8DerOrThrow(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst algorithmIdentifier = children[0];\n\tconst encryptedData = children[1];\n\tif (\n\t\tchildren.length !== 2 ||\n\t\talgorithmIdentifier === undefined ||\n\t\tencryptedData === undefined ||\n\t\tencryptedData.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst decrypted = await decryptPbes2(\n\t\tder.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData.value,\n\t\tpassword,\n\t);\n\ttry {\n\t\tparsePkcs8PrivateKey(decrypted);\n\t} catch {\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes. Plaintext\n\t\t// that is not a PrivateKeyInfo means the password was wrong, not that\n\t\t// the input was malformed.\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Der(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importEncryptedPkcs8DerOrThrow(\n\t\tpemDecodeOrThrow('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportPkcs1Der} for the inverse operation\n * @see {@linkcode importPkcs1Pem} for PEM input\n */\nexport async function importPkcs1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1DerOrThrow` for the throwing variant\n */\nexport function importPkcs1Der(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * Expects the `-----BEGIN RSA PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM\n */\nexport async function importPkcs1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs1DerOrThrow(pemDecodeOrThrow('RSA PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1PemOrThrow` for the throwing variant\n */\nexport function importPkcs1Pem(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedPkcs1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('RSA PRIVATE KEY', pem, password);\n\treturn importPkcs1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input with headers\n */\nexport async function importPkcs8Base64OrThrow(\n\tbase64: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 PKCS#8 private key');\n\t}\n\treturn importPkcs8DerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see `importPkcs8Base64OrThrow` for the throwing variant\n */\nexport function importPkcs8Base64(\n\tbase64: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8Base64OrThrow(base64, algorithm));\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportSec1Der} for the inverse operation\n * @see {@linkcode importSec1Pem} for PEM input\n */\nexport async function importSec1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1DerOrThrow` for the throwing variant\n */\nexport function importSec1Der(\n\tder: Uint8Array,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport async function importSec1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importSec1DerOrThrow(pemDecodeOrThrow('EC PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1PemOrThrow` for the throwing variant\n */\nexport function importSec1Pem(\n\tpem: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedSec1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('EC PRIVATE KEY', pem, password);\n\treturn importSec1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * @see `importEncryptedSec1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedSec1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed or algorithm doesn't match\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, [\n\t\t\t'verify',\n\t\t]);\n\t} catch {\n\t\tthrow new Error('Malformed public JWK');\n\t}\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @see `importPublicJwkOrThrow` for the throwing variant\n */\nexport function importPublicJwk(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPublicJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, ['sign']);\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @see `importPrivateJwkOrThrow` for the throwing variant\n */\nexport function importPrivateJwk(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPrivateJwkOrThrow(jwk, algorithm));\n}\n\n/** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */\nfunction toGenerateKeyAlgorithm(\n\talgorithm: KeyAlgorithmInput,\n): EcKeyGenParams | RsaHashedKeyGenParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\tmodulusLength: algorithm.modulusLength ?? 2048,\n\t\t\t\tpublicExponent: Uint8Array.of(0x01, 0x00, 0x01),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve ?? 'P-256',\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t}\n}\n\n/** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */\nfunction toImportAlgorithm(\n\talgorithm: PublicKeyImportInput,\n): EcKeyImportParams | RsaHashedImportParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve,\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t}\n}\n\n/** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */\nfunction parsePkcs8PrivateKey(der: Uint8Array): {\n\t/** OID identifying the algorithm family (e.g. rsaEncryption, ecPublicKey). */\n\treadonly algorithmOid: string;\n\t/** Optional algorithm parameter OID (e.g. named curve for EC keys). */\n\treadonly parametersOid?: string;\n\t/** Optional algorithm parameter tag. */\n\treadonly parametersTag?: number;\n\t/** Raw DER of the inner private key (PKCS#1 for RSA, SEC 1 for EC). */\n\treadonly privateKeyDer: Uint8Array;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tchildren.length > 4 ||\n\t\talgorithm === undefined ||\n\t\talgorithm.tag !== 0x30 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst algorithmChildren = readSequenceChildren(\n\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\talgorithmOid.tag !== 0x06 ||\n\t\talgorithmChildren.length < 1 ||\n\t\talgorithmChildren.length > 2\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst parameters = algorithmChildren[1];\n\treturn {\n\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t...(parameters?.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t: {}),\n\t\tprivateKeyDer: privateKey.value,\n\t};\n}\n\n/** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapPkcs1InPkcs8(der: Uint8Array): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapSec1InPkcs8(der: Uint8Array, curve: ImportEcKeyInput['curve']): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcKeyInput['curve']): string {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn OIDS.prime256v1;\n\t\tcase 'P-384':\n\t\t\treturn OIDS.secp384r1;\n\t\tcase 'P-521':\n\t\t\treturn OIDS.secp521r1;\n\t}\n}\n\n/** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */\nfunction rsaSchemeToWebCryptoAlgorithmName(\n\tscheme: RsaScheme | undefined,\n): 'RSASSA-PKCS1-v1_5' | 'RSA-PSS' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\n}\n\n/** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */\nasync function encryptTraditionalPem(\n\tlabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tder: Uint8Array,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tif (iv.length !== 16) {\n\t\tthrow new Error('Traditional PEM encryption requires a 16-byte IV');\n\t}\n\tconst cipher = options.cipher ?? 'AES-256-CBC';\n\tconst key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, [\n\t\t'encrypt',\n\t]);\n\tconst encrypted = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(der),\n\t\t),\n\t);\n\tconst body =\n\t\tbase64Encode(encrypted)\n\t\t\t.match(/.{1,64}/g)\n\t\t\t?.join('\\n') ?? '';\n\treturn [\n\t\t`-----BEGIN ${label}-----`,\n\t\t'Proc-Type: 4,ENCRYPTED',\n\t\t`DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,\n\t\t'',\n\t\tbody,\n\t\t`-----END ${label}-----`,\n\t].join('\\n');\n}\n\n/** Decrypt an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back to plaintext DER. */\nasync function decryptTraditionalPem(\n\texpectedLabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tpem: string,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parsed = parseTraditionalPem(pem);\n\tif (parsed.label !== expectedLabel) {\n\t\tthrow new Error(`Expected ${expectedLabel} PEM block`);\n\t}\n\tconst dekInfo = parsed.headers.get('DEK-Info');\n\tif (parsed.headers.get('Proc-Type') !== '4,ENCRYPTED' || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',');\n\tif (!isTraditionalPemCipher(cipher) || ivHex === undefined) {\n\t\tthrow new Error(\n\t\t\t'Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported',\n\t\t);\n\t}\n\tif (!isTraditionalPemIvHex(ivHex)) {\n\t\tthrow new Error(\n\t\t\t'Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters',\n\t\t);\n\t}\n\tconst iv = hexToBytes(ivHex);\n\tconst key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ['decrypt']);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(base64Decode(parsed.base64Body)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted PEM content');\n\t}\n}\n\n/** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */\nasync function importTraditionalPemAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst keyLength = traditionalPemCipherKeyLength(cipher);\n\tconst keyBytes = opensslBytesToKey(password, salt, keyLength / 8);\n\treturn getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'AES-CBC', length: keyLength },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */\nfunction isTraditionalPemCipher(\n\tcipher: string | undefined,\n): cipher is 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC' {\n\treturn cipher === 'AES-128-CBC' || cipher === 'AES-192-CBC' || cipher === 'AES-256-CBC';\n}\n\nfunction isTraditionalPemIvHex(value: string): boolean {\n\treturn value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);\n}\n\n/** Return the AES key size in bits for a given cipher name. */\nfunction traditionalPemCipherKeyLength(\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n): 128 | 192 | 256 {\n\tswitch (cipher) {\n\t\tcase 'AES-128-CBC':\n\t\t\treturn 128;\n\t\tcase 'AES-192-CBC':\n\t\t\treturn 192;\n\t\tcase 'AES-256-CBC':\n\t\t\treturn 256;\n\t}\n}\n\n/** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */\nfunction opensslBytesToKey(password: string, salt: Uint8Array, length: number): Uint8Array {\n\tconst passwordBytes = new TextEncoder().encode(password);\n\tconst chunks: Uint8Array[] = [];\n\tlet previous = new Uint8Array();\n\tlet total = 0;\n\twhile (total < length) {\n\t\tconst input = new Uint8Array(previous.length + passwordBytes.length + salt.length);\n\t\tinput.set(previous, 0);\n\t\tinput.set(passwordBytes, previous.length);\n\t\tinput.set(salt, previous.length + passwordBytes.length);\n\t\tprevious = md5(input);\n\t\tchunks.push(previous);\n\t\ttotal += previous.length;\n\t}\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tconst slice = chunk.slice(0, Math.min(chunk.length, length - offset));\n\t\tout.set(slice, offset);\n\t\toffset += slice.length;\n\t\tif (offset >= length) {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */\nfunction parseTraditionalPem(pem: string): {\n\t/** PEM type label between `BEGIN` and `END` markers. */\n\treadonly label: string;\n\t/** RFC 1421 encapsulated headers (e.g. `Proc-Type`, `DEK-Info`). */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n} {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst lines = normalized.split('\\n');\n\tconst begin = lines[0];\n\tconst end = lines[lines.length - 1];\n\tif (\n\t\tbegin === undefined ||\n\t\tend === undefined ||\n\t\t!begin.startsWith('-----BEGIN ') ||\n\t\t!end.startsWith('-----END ')\n\t) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tconst label = begin.slice(11, -5);\n\tif (end !== `-----END ${label}-----`) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tconst delimiter = line.indexOf(': ');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 2));\n\t\tindex += 1;\n\t}\n\tconst body = lines.slice(index, lines.length - 1).join('');\n\treturn { label, headers, base64Body: body };\n}\n\nfunction parseSpkiDer(der: Uint8Array): {\n\treadonly algorithmOid: string;\n\treadonly parametersOid?: string;\n\treadonly parametersTag?: number;\n} {\n\ttry {\n\t\tconst children = readSequenceChildren(der);\n\t\tif (children.length !== 2) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst algorithm = children[0];\n\t\tconst subjectPublicKey = children[1];\n\t\tif (\n\t\t\talgorithm === undefined ||\n\t\t\talgorithm.tag !== 0x30 ||\n\t\t\tsubjectPublicKey === undefined ||\n\t\t\tsubjectPublicKey.tag !== 0x03\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\textractBitStringValue(subjectPublicKey);\n\t\tconst algorithmChildren = readSequenceChildren(\n\t\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\t);\n\t\tconst algorithmOid = algorithmChildren[0];\n\t\tif (\n\t\t\talgorithmOid === undefined ||\n\t\t\talgorithmOid.tag !== 0x06 ||\n\t\t\talgorithmChildren.length < 1 ||\n\t\t\talgorithmChildren.length > 2\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst parameters = algorithmChildren[1];\n\t\treturn {\n\t\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t\t...(parameters?.tag === 0x06\n\t\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t\t: {}),\n\t\t};\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\nfunction assertSpkiMatchesRequestedAlgorithm(\n\tparsedSpki: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PublicKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedSpki.parametersTag !== undefined && parsedSpki.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedSpki.parametersTag !== 0x06 ||\n\t\t\t\tparsedSpki.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== undefined) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n\nfunction assertPkcs8MatchesRequestedAlgorithm(\n\tparsedPrivateKey: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedPrivateKey.parametersTag !== undefined && parsedPrivateKey.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedPrivateKey.parametersTag !== 0x06 ||\n\t\t\t\tparsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ed25519 ||\n\t\t\t\tparsedPrivateKey.parametersTag !== undefined\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n\nfunction assertPublicJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): void {\n\tif (\n\t\tjwk.k !== undefined ||\n\t\tjwk.d !== undefined ||\n\t\tjwk.p !== undefined ||\n\t\tjwk.q !== undefined ||\n\t\tjwk.dp !== undefined ||\n\t\tjwk.dq !== undefined ||\n\t\tjwk.qi !== undefined ||\n\t\tjwk.oth !== undefined\n\t) {\n\t\tthrow new Error('Public JWK must not contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t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.js CHANGED
@@ -1,2 +1,2 @@
1
- import{explicitContext as e,integerFromNumber as t,objectIdentifier as n,octetString as r,readElement as i,readSequenceChildren as a,sequence as o,setOf as s,tlv as c}from"../internal/asn1/der.js";import{childrenOf as l,decodeIntegerNumber as u,decodeObjectIdentifier as d,toHex as f}from"../internal/asn1/asn1.js";import{OIDS as p}from"../internal/asn1/oids.js";import{decryptPbes2 as m,encryptPbes2 as h}from"../internal/crypto/pbes2.js";import{base64Encode as g}from"../internal/shared/base64.js";import{failureResult as _}from"../result/result.js";import{pemEncode as v,splitPemBlocksOrThrow as y}from"../pem/pem.js";import{exportPkcs8Der as b}from"../keys/keys.js";import{parseCertificateDerOrThrow as x}from"../x509/parse.js";import{createPkcs12MacData as S,parsePkcs12MacData as C}from"./pkcs12-mac.js";async function w(e){let n=[],r=[];for(let t of e.certificates??[]){let e;try{e=V(t.certificate)}catch{return T(`invalid_certificate`,`Each PFX certificate source must be a single PEM or DER certificate`)}n.push(j(e,t.attributes))}for(let t of e.privateKeys??[])r.push(M(await B(t.privateKey),t.attributes));let i=[];if(n.length>0&&i.push(N(o(n))),r.length>0){let t=o(r);i.push(e.encryption===void 0?N(t):await P(t,e.encryption))}let a=o(i),s=e.mac===void 0?void 0:await S(a,e.mac),c=o([t(3),N(a),...s===void 0?[]:[s.der]]);return{ok:!0,value:{der:c,pem:v(`PKCS12`,c),base64:g(c)}}}function T(e,t){return _(e,t)}async function E(e,t){try{let n=a(e,{maxDepth:64});if(n.length<2||n.length>3)return O(`malformed`,`Malformed PFX structure`);let r=n[0],i=n[1];if(r===void 0||i===void 0||r.tag!==2)return O(`malformed`,`Malformed PFX structure`);if(u(r.value)!==3)return O(`malformed`,`Unsupported PFX version`);let o=k(e.slice(i.start-i.headerLength,i.end)),s=n[2],c;if(s!==void 0){let n=await C(e.slice(s.start-s.headerLength,s.end),o,t?.macPassword??t?.password);if(!n.ok)return O(`malformed`,`Malformed PFX MacData`);if(c=n.value,c.verification===`invalid`)return O(`invalid_password`,`Invalid PFX MAC password or corrupted content`)}let l=a(o),d=[];for(let e of l){let n=await A(o.slice(e.start-e.headerLength,e.end),t);if(n.error!==void 0)return n.error;let r=n.data;for(let e of a(r)){let t=r.slice(e.start-e.headerLength,e.end);d.push(I(t))}}return{ok:!0,value:{bags:d,certificates:d.flatMap(e=>e.kind===`certificate`?[e.certificate]:[]),privateKeys:d.flatMap(e=>e.kind===`privateKey`?[e.pkcs8Der]:[]),...c===void 0?{}:{macData:c}}}}catch{return O(`malformed`,`Malformed PFX structure`)}}async function D(e,t){try{let n=y(e).filter(e=>e.label===`PKCS12`),r=n[0];return r===void 0||n.length!==1?O(`malformed`,`Expected exactly one PKCS12 PEM block`):E(r.bytes,t)}catch{return O(`malformed`,`Expected exactly one PKCS12 PEM block`)}}function O(e,t){return _(e,t)}function k(e){let t=a(e),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2||n.tag!==6)throw Error(`Malformed ContentInfo`);if(d(n.value)!==p.pkcs7Data)throw Error(`Only passwordless data ContentInfo is supported`);return U(e,r)}async function A(e,t){let n=a(e),r=n[0],i=n[1];if(r===void 0||i===void 0||n.length!==2||r.tag!==6)return{error:O(`malformed`,`Malformed ContentInfo`)};let o=d(r.value);if(o===p.pkcs7Data)return{data:U(e,i)};if(o!==p.pkcs7EncryptedData)return{error:O(`malformed`,`Unsupported PFX ContentInfo type`)};if(t?.password===void 0)return{error:O(`password_required`,`Password required for encrypted PFX content`)};let s=W(e,i);try{let n=await H(e.slice(s.start-s.headerLength,s.end),t.password);return a(n),{data:n}}catch(e){return z(e)?{error:O(`malformed`,`Malformed PFX encrypted content`)}:{error:O(`invalid_password`,`Invalid PFX password or encrypted content`)}}}function j(t,i){let a=o([n(p.x509CertificateBagType),e(0,r(t))]);return o([n(p.pkcs12CertBag),e(0,a),...F(i)])}function M(t,r){return o([n(p.pkcs12KeyBag),e(0,t),...F(r)])}function N(t){return o([n(p.pkcs7Data),e(0,r(t))])}async function P(r,i){let a=await h(r,i),s=o([t(0),o([n(p.pkcs7Data),a.algorithmIdentifierDer,c(128,a.encryptedData)])]);return o([n(p.pkcs7EncryptedData),e(0,s)])}function F(e){if(e===void 0)return[];let t=[];return e.friendlyName!==void 0&&t.push(o([n(p.friendlyName),s([G(e.friendlyName)])])),e.localKeyId!==void 0&&t.push(o([n(p.localKeyId),s([r(e.localKeyId)])])),t.length===0?[]:[s(t)]}function I(e){let t=a(e),n=t[0],r=t[1],i=t[2];if(n===void 0||r===void 0||t.length>3)throw Error(`Malformed SafeBag`);let o=d(n.value),s=L(e,i);if(o===p.pkcs12CertBag){let t=W(e,r),n=e.slice(t.start-t.headerLength,t.end),i=a(n),c=i[0],l=i[1];if(c===void 0||l===void 0||i.length!==2||d(c.value)!==p.x509CertificateBagType)throw Error(`Malformed certBag`);return{kind:`certificate`,bagId:o,attributes:s,certificate:x(U(n,l))}}if(o===p.pkcs12KeyBag){let t=W(e,r);return{kind:`privateKey`,bagId:o,attributes:s,pkcs8Der:e.slice(t.start-t.headerLength,t.end)}}let c=W(e,r);return{kind:`unknown`,bagId:o,attributes:s,valueDer:e.slice(c.start-c.headerLength,c.end)}}function L(e,t){if(t===void 0)return{entries:[]};let n=[],r,i;for(let o of l(e,t)){let t=e.slice(o.start-o.headerLength,o.end),s=a(t),c=s[0],u=s[1];if(c===void 0||u===void 0||s.length!==2||u.tag!==49)throw Error(`Malformed PFX bag attribute`);let m=d(c.value),h=l(t,u).map(e=>t.slice(e.start-e.headerLength,e.end));if(n.push({oid:m,valuesHex:h.map(e=>f(e))}),m===p.friendlyName){let e=h[0];if(r!==void 0||h.length!==1||e===void 0)throw Error(`Malformed friendlyName attribute`);r=K(e);continue}if(m===p.localKeyId){let e=h[0];if(i!==void 0||h.length!==1||e===void 0)throw Error(`Malformed localKeyId attribute`);i=R(e)}}return{entries:n,...r===void 0?{}:{friendlyName:r},...i===void 0?{}:{localKeyId:i}}}function R(e){let t=i(e);if(t.tag!==4)throw Error(`localKeyId must use OCTET STRING`);return f(t.value)}function z(e){return e instanceof Error?e.message.startsWith(`Malformed `)||e.message.startsWith(`Unsupported `)||e.message.startsWith(`Invalid PBES2 `)||e.message===`Only passwordless data ContentInfo is supported`:!1}async function B(e){return e instanceof CryptoKey?b(e):new Uint8Array(e)}function V(e){if(typeof e==`string`){let t=y(e).find(e=>e.label===`CERTIFICATE`);if(t===void 0)throw Error(`Certificate PEM required`);return new Uint8Array(t.bytes)}return e instanceof Uint8Array?new Uint8Array(e):new Uint8Array(e.der)}async function H(e,t){let n=a(e),r=n[1];if(n.length!==2||r===void 0)throw Error(`Malformed EncryptedData`);let i=n[0];if(i===void 0||i.tag!==2||u(i.value)!==0)throw Error(`Malformed EncryptedData`);let o=e.slice(r.start-r.headerLength,r.end),s=a(o),c=s[1],l=s[2];if(c===void 0||l===void 0||s.length!==3||s[0]?.tag!==6)throw Error(`Malformed EncryptedContentInfo`);if(l.tag!==128)throw Error(`Malformed encrypted content`);return m(o.slice(c.start-c.headerLength,c.end),l.value,t)}function U(e,t){let n=W(e,t);if(n.tag!==4)throw Error(`Expected OCTET STRING in context value`);return n.value}function W(e,t){if((t.tag&224)!=160)throw Error(`Expected context-specific constructed value`);let n=l(e,t),r=n[0];if(n.length!==1||r===void 0)throw Error(`Expected context-specific wrapper with exactly one value`);return r}function G(e){let t=new Uint8Array(e.length*2);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);t[n*2]=r>>8,t[n*2+1]=r&255}return c(30,t)}function K(e){let t=i(e);if(t.tag!==30)throw Error(`Expected BMPString`);if(t.value.length%2!=0)throw Error(`BMPString must use an even number of bytes`);let n=``;for(let e=0;e<t.value.length;e+=2){let r=t.value[e]??0,i=t.value[e+1]??0;n+=String.fromCharCode(r<<8|i)}return n}export{w as createPfx,E as parsePfxDer,D as parsePfxPem};
1
+ import{explicitContext as e,integerFromNumber as t,objectIdentifier as n,octetString as r,readElement as i,readSequenceChildren as a,sequence as o,setOf as s,tlv as c}from"../internal/asn1/der.js";import{childrenOf as l,decodeIntegerNumber as u,decodeObjectIdentifier as d,toHex as f}from"../internal/asn1/asn1.js";import{OIDS as p}from"../internal/asn1/oids.js";import{decryptPbes2 as m,encryptPbes2 as h,isWrongPasswordError as g}from"../internal/crypto/pbes2.js";import{base64Encode as _}from"../internal/shared/base64.js";import{failureResult as v}from"../result/result.js";import{pemEncode as y,splitPemBlocksOrThrow as b}from"../pem/pem.js";import{exportPkcs8Der as x}from"../keys/keys.js";import{parseCertificateDerOrThrow as S}from"../x509/parse.js";import{createPkcs12MacData as C,parsePkcs12MacData as w}from"./pkcs12-mac.js";async function T(e){let n=[],r=[];for(let t of e.certificates??[]){let e;try{e=V(t.certificate)}catch{return E(`invalid_certificate`,`Each PFX certificate source must be a single PEM or DER certificate`)}n.push(M(e,t.attributes))}for(let t of e.privateKeys??[])r.push(N(await B(t.privateKey),t.attributes));let i=[];if(n.length>0&&i.push(P(o(n))),r.length>0){let t=o(r);i.push(e.encryption===void 0?P(t):await F(t,e.encryption))}let a=o(i),s=e.mac===void 0?void 0:await C(a,e.mac),c=o([t(3),P(a),...s===void 0?[]:[s.der]]);return{ok:!0,value:{der:c,pem:y(`PKCS12`,c),base64:_(c)}}}function E(e,t){return v(e,t)}async function D(e,t){try{let n=a(e,{maxDepth:64});if(n.length<2||n.length>3)return k(`malformed`,`Malformed PFX structure`);let r=n[0],i=n[1];if(r===void 0||i===void 0||r.tag!==2)return k(`malformed`,`Malformed PFX structure`);if(u(r.value)!==3)return k(`malformed`,`Unsupported PFX version`);let o=A(e.slice(i.start-i.headerLength,i.end)),s=n[2],c;if(s!==void 0){let n=await w(e.slice(s.start-s.headerLength,s.end),o,t?.macPassword??t?.password);if(!n.ok)return k(`malformed`,`Malformed PFX MacData`);if(c=n.value,c.verification===`invalid`)return k(`invalid_password`,`Invalid PFX MAC password or corrupted content`)}let l=a(o),d=[];for(let e of l){let n=await j(o.slice(e.start-e.headerLength,e.end),t);if(n.error!==void 0)return n.error;let r=n.data;for(let e of a(r)){let t=r.slice(e.start-e.headerLength,e.end);d.push(L(t))}}return{ok:!0,value:{bags:d,certificates:d.flatMap(e=>e.kind===`certificate`?[e.certificate]:[]),privateKeys:d.flatMap(e=>e.kind===`privateKey`?[e.pkcs8Der]:[]),...c===void 0?{}:{macData:c}}}}catch{return k(`malformed`,`Malformed PFX structure`)}}async function O(e,t){try{let n=b(e).filter(e=>e.label===`PKCS12`),r=n[0];return r===void 0||n.length!==1?k(`malformed`,`Expected exactly one PKCS12 PEM block`):D(r.bytes,t)}catch{return k(`malformed`,`Expected exactly one PKCS12 PEM block`)}}function k(e,t){return v(e,t)}function A(e){let t=a(e),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2||n.tag!==6)throw Error(`Malformed ContentInfo`);if(d(n.value)!==p.pkcs7Data)throw Error(`Only passwordless data ContentInfo is supported`);return U(e,r)}async function j(e,t){let n=a(e),r=n[0],i=n[1];if(r===void 0||i===void 0||n.length!==2||r.tag!==6)return{error:k(`malformed`,`Malformed ContentInfo`)};let o=d(r.value);if(o===p.pkcs7Data)return{data:U(e,i)};if(o!==p.pkcs7EncryptedData)return{error:k(`malformed`,`Unsupported PFX ContentInfo type`)};if(t?.password===void 0)return{error:k(`password_required`,`Password required for encrypted PFX content`)};let s=W(e,i),c;try{c=await H(e.slice(s.start-s.headerLength,s.end),t.password)}catch(e){return g(e)?{error:k(`invalid_password`,`Invalid PFX password or encrypted content`)}:{error:k(`malformed`,`Malformed PFX encrypted content`)}}try{a(c)}catch{return{error:k(`invalid_password`,`Invalid PFX password or encrypted content`)}}return{data:c}}function M(t,i){let a=o([n(p.x509CertificateBagType),e(0,r(t))]);return o([n(p.pkcs12CertBag),e(0,a),...I(i)])}function N(t,r){return o([n(p.pkcs12KeyBag),e(0,t),...I(r)])}function P(t){return o([n(p.pkcs7Data),e(0,r(t))])}async function F(r,i){let a=await h(r,i),s=o([t(0),o([n(p.pkcs7Data),a.algorithmIdentifierDer,c(128,a.encryptedData)])]);return o([n(p.pkcs7EncryptedData),e(0,s)])}function I(e){if(e===void 0)return[];let t=[];return e.friendlyName!==void 0&&t.push(o([n(p.friendlyName),s([G(e.friendlyName)])])),e.localKeyId!==void 0&&t.push(o([n(p.localKeyId),s([r(e.localKeyId)])])),t.length===0?[]:[s(t)]}function L(e){let t=a(e),n=t[0],r=t[1],i=t[2];if(n===void 0||r===void 0||t.length>3)throw Error(`Malformed SafeBag`);let o=d(n.value),s=R(e,i);if(o===p.pkcs12CertBag){let t=W(e,r),n=e.slice(t.start-t.headerLength,t.end),i=a(n),c=i[0],l=i[1];if(c===void 0||l===void 0||i.length!==2||d(c.value)!==p.x509CertificateBagType)throw Error(`Malformed certBag`);return{kind:`certificate`,bagId:o,attributes:s,certificate:S(U(n,l))}}if(o===p.pkcs12KeyBag){let t=W(e,r);return{kind:`privateKey`,bagId:o,attributes:s,pkcs8Der:e.slice(t.start-t.headerLength,t.end)}}let c=W(e,r);return{kind:`unknown`,bagId:o,attributes:s,valueDer:e.slice(c.start-c.headerLength,c.end)}}function R(e,t){if(t===void 0)return{entries:[]};let n=[],r,i;for(let o of l(e,t)){let t=e.slice(o.start-o.headerLength,o.end),s=a(t),c=s[0],u=s[1];if(c===void 0||u===void 0||s.length!==2||u.tag!==49)throw Error(`Malformed PFX bag attribute`);let m=d(c.value),h=l(t,u).map(e=>t.slice(e.start-e.headerLength,e.end));if(n.push({oid:m,valuesHex:h.map(e=>f(e))}),m===p.friendlyName){let e=h[0];if(r!==void 0||h.length!==1||e===void 0)throw Error(`Malformed friendlyName attribute`);r=K(e);continue}if(m===p.localKeyId){let e=h[0];if(i!==void 0||h.length!==1||e===void 0)throw Error(`Malformed localKeyId attribute`);i=z(e)}}return{entries:n,...r===void 0?{}:{friendlyName:r},...i===void 0?{}:{localKeyId:i}}}function z(e){let t=i(e);if(t.tag!==4)throw Error(`localKeyId must use OCTET STRING`);return f(t.value)}async function B(e){return e instanceof CryptoKey?x(e):new Uint8Array(e)}function V(e){if(typeof e==`string`){let t=b(e).find(e=>e.label===`CERTIFICATE`);if(t===void 0)throw Error(`Certificate PEM required`);return new Uint8Array(t.bytes)}return e instanceof Uint8Array?new Uint8Array(e):new Uint8Array(e.der)}async function H(e,t){let n=a(e),r=n[1];if(n.length!==2||r===void 0)throw Error(`Malformed EncryptedData`);let i=n[0];if(i===void 0||i.tag!==2||u(i.value)!==0)throw Error(`Malformed EncryptedData`);let o=e.slice(r.start-r.headerLength,r.end),s=a(o),c=s[1],l=s[2];if(c===void 0||l===void 0||s.length!==3||s[0]?.tag!==6)throw Error(`Malformed EncryptedContentInfo`);if(l.tag!==128)throw Error(`Malformed encrypted content`);return m(o.slice(c.start-c.headerLength,c.end),l.value,t)}function U(e,t){let n=W(e,t);if(n.tag!==4)throw Error(`Expected OCTET STRING in context value`);return n.value}function W(e,t){if((t.tag&224)!=160)throw Error(`Expected context-specific constructed value`);let n=l(e,t),r=n[0];if(n.length!==1||r===void 0)throw Error(`Expected context-specific wrapper with exactly one value`);return r}function G(e){let t=new Uint8Array(e.length*2);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);t[n*2]=r>>8,t[n*2+1]=r&255}return c(30,t)}function K(e){let t=i(e);if(t.tag!==30)throw Error(`Expected BMPString`);if(t.value.length%2!=0)throw Error(`BMPString must use an even number of bytes`);let n=``;for(let e=0;e<t.value.length;e+=2){let r=t.value[e]??0,i=t.value[e+1]??0;n+=String.fromCharCode(r<<8|i)}return n}export{T as createPfx,D as parsePfxDer,O as parsePfxPem};
2
2
  //# sourceMappingURL=pfx.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pfx.js","names":[],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport type { DerElement } from '#micro509/internal/asn1/der.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\ttype Pbes2EncryptionOptions,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { exportPkcs8Der } from '#micro509/keys/keys.ts';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem.ts';\nimport { type ErrorResult, failureResult, type Micro509Error } from '#micro509/result/result.ts';\nimport { type ParsedCertificate, parseCertificateDerOrThrow } from '#micro509/x509/parse.ts';\nimport {\n\tcreatePkcs12MacData,\n\ttype ParsedPkcs12MacData,\n\ttype Pkcs12MacOptions,\n\tparsePkcs12MacData,\n} from './pkcs12-mac.ts';\n\nexport type * from './pkcs12-mac.ts';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array | ParsedCertificate;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/** Human-readable label stored as a BMPString attribute. */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode Pbes2EncryptionOptions}. */\nexport type PfxEncryptionOptions = Pbes2EncryptionOptions;\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/** Hex-encoded DER of each attribute value. */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER of the unrecognized bag value. */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// ---------------------------------------------------------------------------\n// Result types for PFX parsing\n// ---------------------------------------------------------------------------\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode = 'malformed' | 'invalid_password' | 'password_required';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// Result types for PFX creation\n// ---------------------------------------------------------------------------\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// createPfx\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// ---------------------------------------------------------------------------\n// parsePfxDer / parsePfxPem — Result-returning\n// ---------------------------------------------------------------------------\n\n/**\n * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined || version.tag !== 0x02) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(version.value) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authSafeDer = der.slice(authSafe.start - authSafe.headerLength, authSafe.end);\n\t\tconst authenticatedSafeOctets = extractContentInfoData(authSafeDer);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await parsePkcs12MacData(\n\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t);\n\t\t\tif (!macResult.ok) {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tmacData = macResult.value;\n\t\t\tif (macData.verification === 'invalid') {\n\t\t\t\treturn pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content');\n\t\t\t}\n\t\t}\n\t\tconst authenticatedSafe = readSequenceChildren(authenticatedSafeOctets);\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of authenticatedSafe) {\n\t\t\tconst contentInfoDer = authenticatedSafeOctets.slice(\n\t\t\t\tcontentInfo.start - contentInfo.headerLength,\n\t\t\t\tcontentInfo.end,\n\t\t\t);\n\t\t\tconst safeContentsResult = await extractSafeContents(contentInfoDer, options);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of readSequenceChildren(safeContents)) {\n\t\t\t\tconst bagDer = safeContents.slice(bag.start - bag.headerLength, bag.end);\n\t\t\t\tbags.push(parseSafeBag(bagDer));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\treturn parsePfxDer(block.bytes, options);\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Private: PFX helpers\n// ---------------------------------------------------------------------------\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(contentInfoDer: Uint8Array): Uint8Array {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\tif (decodeObjectIdentifier(contentType.value) !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(contentInfoDer, content);\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tcontentInfoDer: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\treturn { error: pfxFailure('malformed', 'Malformed ContentInfo') };\n\t}\n\tconst oid = decodeObjectIdentifier(contentType.value);\n\tif (oid === OIDS.pkcs7Data) {\n\t\treturn { data: extractContextOctetString(contentInfoDer, content) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(contentInfoDer, content);\n\ttry {\n\t\tconst decrypted = await decryptEncryptedData(\n\t\t\tcontentInfoDer.slice(encryptedData.start - encryptedData.headerLength, encryptedData.end),\n\t\t\toptions.password,\n\t\t);\n\t\treadSequenceChildren(decrypted);\n\t\treturn { data: decrypted };\n\t} catch (error) {\n\t\tif (isMalformedPfxEncryptedContentError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('malformed', 'Malformed PFX encrypted content'),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.friendlyName), setOf([bmpString(attributes.friendlyName)])]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** Decodes a single SafeBag from DER into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(der: Uint8Array): ParsedPfxBag {\n\tconst children = readSequenceChildren(der);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(bagId.value);\n\tconst attributes = parseBagAttributes(der, attributeSet);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBag = extractContextChild(der, bagValue);\n\t\tconst certBagDer = der.slice(certBag.start - certBag.headerLength, certBag.end);\n\t\tconst certBagChildren = readSequenceChildren(certBagDer);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(certType.value) !== OIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\tconst certificateDer = extractContextOctetString(certBagDer, certValue);\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(certificateDer),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8 = extractContextChild(der, bagValue);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der: der.slice(pkcs8.start - pkcs8.headerLength, pkcs8.end),\n\t\t};\n\t}\n\tconst value = extractContextChild(der, bagValue);\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: der.slice(value.start - value.headerLength, value.end),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: DerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of childrenOf(source, attributeSet)) {\n\t\tconst attributeDer = source.slice(attribute.start - attribute.headerLength, attribute.end);\n\t\tconst parts = readSequenceChildren(attributeDer);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(oid.value);\n\t\tconst rawValues = childrenOf(attributeDer, values).map((value) =>\n\t\t\tattributeDer.slice(value.start - value.headerLength, value.end),\n\t\t);\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeBmpString(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\nfunction isMalformedPfxEncryptedContentError(error: unknown): boolean {\n\tif (!(error instanceof Error)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\terror.message.startsWith('Malformed ') ||\n\t\terror.message.startsWith('Unsupported ') ||\n\t\terror.message.startsWith('Invalid PBES2 ') ||\n\t\terror.message === 'Only passwordless data ContentInfo is supported'\n\t);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nasync function normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\tif (source instanceof CryptoKey) {\n\t\treturn exportPkcs8Der(source);\n\t}\n\treturn new Uint8Array(source);\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocksOrThrow(source).find(\n\t\t\t(candidate) => candidate.label === 'CERTIFICATE',\n\t\t);\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn new Uint8Array(source);\n\t}\n\treturn new Uint8Array(source.der);\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nasync function decryptEncryptedData(\n\tencryptedDataDer: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst topLevel = readSequenceChildren(encryptedDataDer);\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst version = topLevel[0];\n\tif (version === undefined || version.tag !== 0x02 || decodeIntegerNumber(version.value) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoDer = encryptedDataDer.slice(\n\t\tencryptedContentInfo.start - encryptedContentInfo.headerLength,\n\t\tencryptedContentInfo.end,\n\t);\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3 ||\n\t\tcontentInfoChildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tif (encryptedContent.tag !== 0x80) {\n\t\tthrow new Error('Malformed encrypted content');\n\t}\n\treturn decryptPbes2(\n\t\tcontentInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\tencryptedContent.value,\n\t\tpassword,\n\t);\n}\n\n/** Reads the first child of a context-tagged element, expecting an OCTET STRING. */\nfunction extractContextOctetString(source: Uint8Array, element: DerElement): Uint8Array {\n\tconst child = extractContextChild(source, element);\n\tif (child.tag !== 0x04) {\n\t\tthrow new Error('Expected OCTET STRING in context value');\n\t}\n\treturn child.value;\n}\n\n/** Reads the first child element inside a context-specific constructed wrapper. */\nfunction extractContextChild(source: Uint8Array, element: DerElement): DerElement {\n\tif ((element.tag & 0xe0) !== 0xa0) {\n\t\tthrow new Error('Expected context-specific constructed value');\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** Encodes a JS string as an ASN.1 BMPString (UCS-2 big-endian, tag 0x1e). */\nfunction bmpString(value: string): Uint8Array {\n\tconst bytes = new Uint8Array(value.length * 2);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst codePoint = value.charCodeAt(index);\n\t\tbytes[index * 2] = codePoint >> 8;\n\t\tbytes[index * 2 + 1] = codePoint & 0xff;\n\t}\n\treturn tlv(0x1e, bytes);\n}\n\n/** Decodes a DER-encoded BMPString (tag 0x1e) back to a JS string. */\nfunction decodeBmpString(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('Expected BMPString');\n\t}\n\tif (element.value.length % 2 !== 0) {\n\t\tthrow new Error('BMPString must use an even number of bytes');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < element.value.length; index += 2) {\n\t\tconst left = element.value[index] ?? 0;\n\t\tconst right = element.value[index + 1] ?? 0;\n\t\tvalue += String.fromCharCode((left << 8) | right);\n\t}\n\treturn value;\n}\n"],"mappings":"0yBAoQA,eAAsB,EAAU,EAAiD,CAChF,IAAM,EAAgC,CAAC,EACjC,EAA+B,CAAC,EACtC,IAAK,IAAM,KAAe,EAAM,cAAgB,CAAC,EAAG,CAGnD,IAAI,EACJ,GAAI,CACH,EAAiB,EAAqB,EAAY,WAAW,CAC9D,MAAQ,CACP,OAAO,EACN,sBACA,qEACD,CACD,CACA,EAAgB,KAAK,EAAqB,EAAgB,EAAY,UAAU,CAAC,CAClF,CACA,IAAK,IAAM,KAAc,EAAM,aAAe,CAAC,EAC9C,EAAe,KACd,EAAoB,MAAM,EAAoB,EAA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B,EAAiC,CACvF,IAAM,EAAQ,EAAoB,EAAQ,CAAO,EACjD,GAAI,EAAM,MAAQ,EACjB,MAAU,MAAM,wCAAwC,EAEzD,OAAO,EAAM,KACd,CAGA,SAAS,EAAoB,EAAoB,EAAiC,CACjF,IAAK,EAAQ,IAAM,MAAU,IAC5B,MAAU,MAAM,6CAA6C,EAE9D,IAAM,EAAW,EAAW,EAAQ,CAAO,EACrC,EAAQ,EAAS,GACvB,GAAI,EAAS,SAAW,GAAK,IAAU,IAAA,GACtC,MAAU,MAAM,0DAA0D,EAE3E,OAAO,CACR,CAGA,SAAS,EAAU,EAA2B,CAC7C,IAAM,EAAQ,IAAI,WAAW,EAAM,OAAS,CAAC,EAC7C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAY,EAAM,WAAW,CAAK,EACxC,EAAM,EAAQ,GAAK,GAAa,EAChC,EAAM,EAAQ,EAAI,GAAK,EAAY,GACpC,CACA,OAAO,EAAI,GAAM,CAAK,CACvB,CAGA,SAAS,EAAgB,EAAyB,CACjD,IAAM,EAAU,EAAY,CAAG,EAC/B,GAAI,EAAQ,MAAQ,GACnB,MAAU,MAAM,oBAAoB,EAErC,GAAI,EAAQ,MAAM,OAAS,GAAM,EAChC,MAAU,MAAM,4CAA4C,EAE7D,IAAI,EAAQ,GACZ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,MAAM,OAAQ,GAAS,EAAG,CAC7D,IAAM,EAAO,EAAQ,MAAM,IAAU,EAC/B,EAAQ,EAAQ,MAAM,EAAQ,IAAM,EAC1C,GAAS,OAAO,aAAc,GAAQ,EAAK,CAAK,CACjD,CACA,OAAO,CACR"}
1
+ {"version":3,"file":"pfx.js","names":[],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport type { DerElement } from '#micro509/internal/asn1/der.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { exportPkcs8Der } from '#micro509/keys/keys.ts';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem.ts';\nimport { type ErrorResult, failureResult, type Micro509Error } from '#micro509/result/result.ts';\nimport { type ParsedCertificate, parseCertificateDerOrThrow } from '#micro509/x509/parse.ts';\nimport {\n\tcreatePkcs12MacData,\n\ttype ParsedPkcs12MacData,\n\ttype Pkcs12MacOptions,\n\tparsePkcs12MacData,\n} from './pkcs12-mac.ts';\n\nexport type * from './pkcs12-mac.ts';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array | ParsedCertificate;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/** Human-readable label stored as a BMPString attribute. */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode Pbes2EncryptionOptions}. */\nexport type PfxEncryptionOptions = Pbes2EncryptionOptions;\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/** Hex-encoded DER of each attribute value. */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER of the unrecognized bag value. */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// ---------------------------------------------------------------------------\n// Result types for PFX parsing\n// ---------------------------------------------------------------------------\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode = 'malformed' | 'invalid_password' | 'password_required';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// Result types for PFX creation\n// ---------------------------------------------------------------------------\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// createPfx\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// ---------------------------------------------------------------------------\n// parsePfxDer / parsePfxPem — Result-returning\n// ---------------------------------------------------------------------------\n\n/**\n * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined || version.tag !== 0x02) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(version.value) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authSafeDer = der.slice(authSafe.start - authSafe.headerLength, authSafe.end);\n\t\tconst authenticatedSafeOctets = extractContentInfoData(authSafeDer);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await parsePkcs12MacData(\n\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t);\n\t\t\tif (!macResult.ok) {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tmacData = macResult.value;\n\t\t\tif (macData.verification === 'invalid') {\n\t\t\t\treturn pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content');\n\t\t\t}\n\t\t}\n\t\tconst authenticatedSafe = readSequenceChildren(authenticatedSafeOctets);\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of authenticatedSafe) {\n\t\t\tconst contentInfoDer = authenticatedSafeOctets.slice(\n\t\t\t\tcontentInfo.start - contentInfo.headerLength,\n\t\t\t\tcontentInfo.end,\n\t\t\t);\n\t\t\tconst safeContentsResult = await extractSafeContents(contentInfoDer, options);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of readSequenceChildren(safeContents)) {\n\t\t\t\tconst bagDer = safeContents.slice(bag.start - bag.headerLength, bag.end);\n\t\t\t\tbags.push(parseSafeBag(bagDer));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\treturn parsePfxDer(block.bytes, options);\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Private: PFX helpers\n// ---------------------------------------------------------------------------\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(contentInfoDer: Uint8Array): Uint8Array {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\tif (decodeObjectIdentifier(contentType.value) !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(contentInfoDer, content);\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tcontentInfoDer: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\treturn { error: pfxFailure('malformed', 'Malformed ContentInfo') };\n\t}\n\tconst oid = decodeObjectIdentifier(contentType.value);\n\tif (oid === OIDS.pkcs7Data) {\n\t\treturn { data: extractContextOctetString(contentInfoDer, content) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(contentInfoDer, content);\n\tlet decrypted: Uint8Array;\n\ttry {\n\t\tdecrypted = await decryptEncryptedData(\n\t\t\tcontentInfoDer.slice(encryptedData.start - encryptedData.headerLength, encryptedData.end),\n\t\t\toptions.password,\n\t\t);\n\t} catch (error) {\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Malformed PFX encrypted content'),\n\t\t};\n\t}\n\ttry {\n\t\treadSequenceChildren(decrypted);\n\t} catch {\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes that are not\n\t\t// a SafeContents SEQUENCE — a wrong password, not malformed input.\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n\treturn { data: decrypted };\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.friendlyName), setOf([bmpString(attributes.friendlyName)])]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** Decodes a single SafeBag from DER into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(der: Uint8Array): ParsedPfxBag {\n\tconst children = readSequenceChildren(der);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(bagId.value);\n\tconst attributes = parseBagAttributes(der, attributeSet);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBag = extractContextChild(der, bagValue);\n\t\tconst certBagDer = der.slice(certBag.start - certBag.headerLength, certBag.end);\n\t\tconst certBagChildren = readSequenceChildren(certBagDer);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(certType.value) !== OIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\tconst certificateDer = extractContextOctetString(certBagDer, certValue);\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(certificateDer),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8 = extractContextChild(der, bagValue);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der: der.slice(pkcs8.start - pkcs8.headerLength, pkcs8.end),\n\t\t};\n\t}\n\tconst value = extractContextChild(der, bagValue);\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: der.slice(value.start - value.headerLength, value.end),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: DerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of childrenOf(source, attributeSet)) {\n\t\tconst attributeDer = source.slice(attribute.start - attribute.headerLength, attribute.end);\n\t\tconst parts = readSequenceChildren(attributeDer);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(oid.value);\n\t\tconst rawValues = childrenOf(attributeDer, values).map((value) =>\n\t\t\tattributeDer.slice(value.start - value.headerLength, value.end),\n\t\t);\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeBmpString(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nasync function normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\tif (source instanceof CryptoKey) {\n\t\treturn exportPkcs8Der(source);\n\t}\n\treturn new Uint8Array(source);\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocksOrThrow(source).find(\n\t\t\t(candidate) => candidate.label === 'CERTIFICATE',\n\t\t);\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn new Uint8Array(source);\n\t}\n\treturn new Uint8Array(source.der);\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nasync function decryptEncryptedData(\n\tencryptedDataDer: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst topLevel = readSequenceChildren(encryptedDataDer);\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst version = topLevel[0];\n\tif (version === undefined || version.tag !== 0x02 || decodeIntegerNumber(version.value) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoDer = encryptedDataDer.slice(\n\t\tencryptedContentInfo.start - encryptedContentInfo.headerLength,\n\t\tencryptedContentInfo.end,\n\t);\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3 ||\n\t\tcontentInfoChildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tif (encryptedContent.tag !== 0x80) {\n\t\tthrow new Error('Malformed encrypted content');\n\t}\n\treturn decryptPbes2(\n\t\tcontentInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\tencryptedContent.value,\n\t\tpassword,\n\t);\n}\n\n/** Reads the first child of a context-tagged element, expecting an OCTET STRING. */\nfunction extractContextOctetString(source: Uint8Array, element: DerElement): Uint8Array {\n\tconst child = extractContextChild(source, element);\n\tif (child.tag !== 0x04) {\n\t\tthrow new Error('Expected OCTET STRING in context value');\n\t}\n\treturn child.value;\n}\n\n/** Reads the first child element inside a context-specific constructed wrapper. */\nfunction extractContextChild(source: Uint8Array, element: DerElement): DerElement {\n\tif ((element.tag & 0xe0) !== 0xa0) {\n\t\tthrow new Error('Expected context-specific constructed value');\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** Encodes a JS string as an ASN.1 BMPString (UCS-2 big-endian, tag 0x1e). */\nfunction bmpString(value: string): Uint8Array {\n\tconst bytes = new Uint8Array(value.length * 2);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst codePoint = value.charCodeAt(index);\n\t\tbytes[index * 2] = codePoint >> 8;\n\t\tbytes[index * 2 + 1] = codePoint & 0xff;\n\t}\n\treturn tlv(0x1e, bytes);\n}\n\n/** Decodes a DER-encoded BMPString (tag 0x1e) back to a JS string. */\nfunction decodeBmpString(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('Expected BMPString');\n\t}\n\tif (element.value.length % 2 !== 0) {\n\t\tthrow new Error('BMPString must use an even number of bytes');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < element.value.length; index += 2) {\n\t\tconst left = element.value[index] ?? 0;\n\t\tconst right = element.value[index + 1] ?? 0;\n\t\tvalue += String.fromCharCode((left << 8) | right);\n\t}\n\treturn value;\n}\n"],"mappings":"o0BAqQA,eAAsB,EAAU,EAAiD,CAChF,IAAM,EAAgC,CAAC,EACjC,EAA+B,CAAC,EACtC,IAAK,IAAM,KAAe,EAAM,cAAgB,CAAC,EAAG,CAGnD,IAAI,EACJ,GAAI,CACH,EAAiB,EAAqB,EAAY,WAAW,CAC9D,MAAQ,CACP,OAAO,EACN,sBACA,qEACD,CACD,CACA,EAA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ificate workflows.",
5
5
  "keywords": [
6
6
  "x509",