micro509 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +14 -11
  2. package/dist/index.d.ts +7 -7
  3. package/dist/index.js +1 -1
  4. package/dist/internal/asn1/oids.js +1 -1
  5. package/dist/internal/asn1/oids.js.map +1 -1
  6. package/dist/internal/crypto/pbes2.js +1 -1
  7. package/dist/internal/crypto/pbes2.js.map +1 -1
  8. package/dist/internal/crypto/sig-verify.js +1 -1
  9. package/dist/internal/crypto/sig-verify.js.map +1 -1
  10. package/dist/keys/keys.d.ts +72 -100
  11. package/dist/keys/keys.js +3 -3
  12. package/dist/keys/keys.js.map +1 -1
  13. package/dist/keys.d.ts +2 -2
  14. package/dist/pkcs/pfx.d.ts +31 -5
  15. package/dist/pkcs/pfx.js +1 -1
  16. package/dist/pkcs/pfx.js.map +1 -1
  17. package/dist/pkcs/pkcs7.d.ts +26 -5
  18. package/dist/pkcs/pkcs7.js +1 -1
  19. package/dist/pkcs/pkcs7.js.map +1 -1
  20. package/dist/pkcs.d.ts +3 -3
  21. package/dist/result/result.d.ts +54 -1
  22. package/dist/result/result.js +1 -1
  23. package/dist/result/result.js.map +1 -1
  24. package/dist/result.d.ts +2 -2
  25. package/dist/result.js +1 -1
  26. package/dist/revocation/chain.d.ts +8 -2
  27. package/dist/revocation/chain.js +1 -1
  28. package/dist/revocation/chain.js.map +1 -1
  29. package/dist/revocation/crl.d.ts +3 -1
  30. package/dist/revocation/crl.js +1 -1
  31. package/dist/revocation/crl.js.map +1 -1
  32. package/dist/revocation/ocsp.js +1 -1
  33. package/dist/revocation/ocsp.js.map +1 -1
  34. package/dist/revocation/revocation.d.ts +2 -2
  35. package/dist/revocation/revocation.js +1 -1
  36. package/dist/revocation/revocation.js.map +1 -1
  37. package/dist/revocation.d.ts +2 -2
  38. package/dist/verify/identity.js +1 -1
  39. package/dist/verify/identity.js.map +1 -1
  40. package/dist/verify/verify.d.ts +8 -5
  41. package/dist/verify/verify.js +1 -1
  42. package/dist/verify/verify.js.map +1 -1
  43. package/dist/verify.d.ts +2 -2
  44. package/dist/verify.js +1 -1
  45. package/dist/x509/parse.d.ts +35 -21
  46. package/dist/x509/parse.js +1 -1
  47. package/dist/x509/parse.js.map +1 -1
  48. package/dist/x509.d.ts +2 -2
  49. package/package.json +45 -65
package/dist/keys.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { Pbes2EncryptionOptions, Pbes2EncryptionScheme, Pbes2Prf } from "./internal/crypto/pbes2.js";
2
- import { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcPublicKeyInput, ImportEd25519PublicKeyInput, ImportRsaPublicKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem } from "./keys/keys.js";
3
- export { type EcKeyAlgorithmInput, type EcNamedCurve, type Ed25519KeyAlgorithmInput, type EncryptedPkcs8Options, type ImportEcPublicKeyInput, type ImportEd25519PublicKeyInput, type ImportRsaPublicKeyInput, type KeyAlgorithmInput, type KeyPairMaterial, type LegacyPemEncryptionOptions, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, type PrivateKeyImportInput, type PublicKeyImportInput, type RsaHash, type RsaKeyAlgorithmInput, type RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem };
2
+ import { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcPublicKeyInput, ImportEd25519PublicKeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaPublicKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem } from "./keys/keys.js";
3
+ export { type EcKeyAlgorithmInput, type EcNamedCurve, type Ed25519KeyAlgorithmInput, type EncryptedPkcs8Options, type ImportEcPublicKeyInput, type ImportEd25519PublicKeyInput, type ImportEncryptedKeyErrorCode, type ImportEncryptedKeyFailure, type ImportEncryptedKeyResult, type ImportKeyErrorCode, type ImportKeyFailure, type ImportKeyResult, type ImportRsaPublicKeyInput, type KeyAlgorithmInput, type KeyPairMaterial, type LegacyPemEncryptionOptions, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, type PrivateKeyImportInput, type PublicKeyImportInput, type RsaHash, type RsaKeyAlgorithmInput, type RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem };
@@ -119,25 +119,51 @@ type ParsePfxResult = {
119
119
  readonly value: ParsedPfx;
120
120
  } | ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;
121
121
  /**
122
+ * Caller-correctable failure code from {@linkcode createPfx}.
123
+ *
124
+ * The only parse boundary in creation is the certificate source: it is
125
+ * normalized from untrusted PEM/DER. Private keys are either a WebCrypto
126
+ * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through
127
+ * unvalidated, so there is no distinct `invalid_private_key` failure to model.
128
+ */
129
+ type CreatePfxErrorCode = "invalid_certificate";
130
+ /** Error payload for a failed PFX creation. */
131
+ interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {
132
+ /** Always `false` for failures. */
133
+ readonly ok: false;
134
+ }
135
+ /** Success-or-failure result from {@linkcode createPfx}. */
136
+ type CreatePfxResult = {
137
+ /** Creation succeeded. */readonly ok: true; /** DER, PEM, and base64 forms of the PFX container. */
138
+ readonly value: PfxMaterial;
139
+ } | ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;
140
+ /**
122
141
  * Builds a PKCS#12/PFX archive containing certificates and/or private keys.
123
142
  *
124
143
  * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.
125
144
  * When `mac` is provided, a PKCS#12 MAC integrity block is appended.
126
145
  *
146
+ * Returns a {@linkcode CreatePfxResult}: the container material on success, or a
147
+ * typed `invalid_certificate` failure when a certificate source is not a single
148
+ * PEM/DER certificate.
149
+ *
127
150
  * @example
128
151
  * ```ts
129
- * import { createPfx } from 'micro509';
152
+ * import { createPfx, unwrap } from 'micro509';
130
153
  *
131
- * const pfx = await createPfx({
154
+ * const result = await createPfx({
132
155
  * certificates: [{ certificate: certPem }],
133
156
  * privateKeys: [{ privateKey: keyPair.privateKey }],
134
157
  * encryption: { password: 's3cret' },
135
158
  * mac: { password: 's3cret' },
136
159
  * });
137
- * // pfx.der, pfx.pem, pfx.base64
160
+ * if (result.ok) {
161
+ * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64
162
+ * }
163
+ * // or, when inputs are already validated: const pfx = unwrap(result);
138
164
  * ```
139
165
  */
140
- declare function createPfx(input: CreatePfxInput): Promise<PfxMaterial>;
166
+ declare function createPfx(input: CreatePfxInput): Promise<CreatePfxResult>;
141
167
  /**
142
168
  * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.
143
169
  *
@@ -173,5 +199,5 @@ declare function parsePfxDer(der: Uint8Array, options?: ParsePfxOptions): Promis
173
199
  */
174
200
  declare function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult>;
175
201
  //#endregion
176
- export { CreatePfxInput, ParsePfxErrorCode, ParsePfxFailure, ParsePfxOptions, ParsePfxResult, ParsedPfx, ParsedPfxAttribute, ParsedPfxBag, ParsedPfxBagAttributes, type ParsedPkcs12MacData, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, PfxBagAttributesInput, PfxCertificateBagInput, PfxCertificateSource, PfxEncryptionOptions, PfxMaterial, PfxPrivateKeyBagInput, PfxPrivateKeySource, type Pkcs12MacOptions, createPfx, type createPkcs12MacData, parsePfxDer, parsePfxPem, type parsePkcs12MacData };
202
+ export { CreatePfxErrorCode, CreatePfxFailure, CreatePfxInput, CreatePfxResult, ParsePfxErrorCode, ParsePfxFailure, ParsePfxOptions, ParsePfxResult, ParsedPfx, ParsedPfxAttribute, ParsedPfxBag, ParsedPfxBagAttributes, type ParsedPkcs12MacData, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, PfxBagAttributesInput, PfxCertificateBagInput, PfxCertificateSource, PfxEncryptionOptions, PfxMaterial, PfxPrivateKeyBagInput, PfxPrivateKeySource, type Pkcs12MacOptions, createPfx, type createPkcs12MacData, parsePfxDer, parsePfxPem, type parsePkcs12MacData };
177
203
  //# sourceMappingURL=pfx.d.ts.map
package/dist/pkcs/pfx.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{pemEncode as _,splitPemBlocks as v}from"../pem/pem.js";import{exportPkcs8Der as y}from"../keys/keys.js";import{parseCertificateDer as b}from"../x509/parse.js";import{createPkcs12MacData as x,parsePkcs12MacData as S}from"./pkcs12-mac.js";async function C(e){let n=[],r=[];for(let t of e.certificates??[])n.push(k(z(t.certificate),t.attributes));for(let t of e.privateKeys??[])r.push(A(await R(t.privateKey),t.attributes));let i=[];if(n.length>0&&i.push(j(o(n))),r.length>0){let t=o(r);i.push(e.encryption===void 0?j(t):await M(t,e.encryption))}let a=o(i),s=e.mac===void 0?void 0:await x(a,e.mac),c=o([t(3),j(a),...s===void 0?[]:[s.der]]);return{der:c,pem:_(`PKCS12`,c),base64:g(c)}}async function w(e,t){try{let n=a(e,{maxDepth:64});if(n.length<2||n.length>3)return E(`malformed`,`Malformed PFX structure`);let r=n[0],i=n[1];if(r===void 0||i===void 0||r.tag!==2)return E(`malformed`,`Malformed PFX structure`);if(u(r.value)!==3)return E(`malformed`,`Unsupported PFX version`);let o=D(e.slice(i.start-i.headerLength,i.end)),s=n[2],c;if(s!==void 0){try{c=await S(e.slice(s.start-s.headerLength,s.end),o,t?.macPassword??t?.password)}catch{return E(`malformed`,`Malformed PFX MacData`)}if(c?.valid===!1)return E(`invalid_password`,`Invalid PFX MAC password or corrupted content`)}let l=a(o),d=[];for(let e of l){let n=await O(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(P(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 E(`malformed`,`Malformed PFX structure`)}}async function T(e,t){try{let n=v(e).filter(e=>e.label===`PKCS12`),r=n[0];return r===void 0||n.length!==1?E(`malformed`,`Expected exactly one PKCS12 PEM block`):w(r.bytes,t)}catch{return E(`malformed`,`Expected exactly one PKCS12 PEM block`)}}function E(e,t){return{ok:!1,error:{ok:!1,code:e,message:t},code:e,message:t}}function D(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 V(e,r)}async function O(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:E(`malformed`,`Malformed ContentInfo`)};let o=d(r.value);if(o===p.pkcs7Data)return{data:V(e,i)};if(o!==p.pkcs7EncryptedData)return{error:E(`malformed`,`Unsupported PFX ContentInfo type`)};if(t?.password===void 0)return{error:E(`password_required`,`Password required for encrypted PFX content`)};let s=H(e,i);try{let n=await B(e.slice(s.start-s.headerLength,s.end),t.password);return a(n),{data:n}}catch(e){return L(e)?{error:E(`malformed`,`Malformed PFX encrypted content`)}:{error:E(`invalid_password`,`Invalid PFX password or encrypted content`)}}}function k(t,i){let a=o([n(p.x509CertificateBagType),e(0,r(t))]);return o([n(p.pkcs12CertBag),e(0,a),...N(i)])}function A(t,r){return o([n(p.pkcs12KeyBag),e(0,t),...N(r)])}function j(t){return o([n(p.pkcs7Data),e(0,r(t))])}async function M(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 N(e){if(e===void 0)return[];let t=[];return e.friendlyName!==void 0&&t.push(o([n(p.friendlyName),s([U(e.friendlyName)])])),e.localKeyId!==void 0&&t.push(o([n(p.localKeyId),s([r(e.localKeyId)])])),t.length===0?[]:[s(t)]}function P(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=F(e,i);if(o===p.pkcs12CertBag){let t=H(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:b(V(n,l))}}if(o===p.pkcs12KeyBag){let t=H(e,r);return{kind:`privateKey`,bagId:o,attributes:s,pkcs8Der:e.slice(t.start-t.headerLength,t.end)}}let c=H(e,r);return{kind:`unknown`,bagId:o,attributes:s,valueDer:e.slice(c.start-c.headerLength,c.end)}}function F(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=W(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=I(e)}}return{entries:n,...r===void 0?{}:{friendlyName:r},...i===void 0?{}:{localKeyId:i}}}function I(e){let t=i(e);if(t.tag!==4)throw Error(`localKeyId must use OCTET STRING`);return f(t.value)}function L(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 R(e){return e instanceof CryptoKey?y(e):new Uint8Array(e)}function z(e){if(typeof e==`string`){let t=v(e).find(e=>e.label===`CERTIFICATE`);if(t===void 0)throw Error(`Certificate PEM required`);return new Uint8Array(t.bytes)}return new Uint8Array(e)}async function B(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 V(e,t){let n=H(e,t);if(n.tag!==4)throw Error(`Expected OCTET STRING in context value`);return n.value}function H(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 U(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 W(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{C as createPfx,w as parsePfxDer,T 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}from"../internal/crypto/pbes2.js";import{base64Encode as g}from"../internal/shared/base64.js";import{pemEncode as _,splitPemBlocks as v}from"../pem/pem.js";import{failureResult as y}from"../result/result.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:_(`PKCS12`,c),base64:g(c)}}}function T(e,t){return y(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){try{c=await C(e.slice(s.start-s.headerLength,s.end),o,t?.macPassword??t?.password)}catch{return O(`malformed`,`Malformed PFX MacData`)}if(c?.valid===!1)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=v(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 y(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=v(e).find(e=>e.label===`CERTIFICATE`);if(t===void 0)throw Error(`Certificate PEM required`);return new Uint8Array(t.bytes)}return new Uint8Array(e)}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};
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, splitPemBlocks } from '#micro509/pem/pem.ts';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result.ts';\nimport { type ParsedCertificate, parseCertificateDer } from '#micro509/x509/parse.ts';\nimport {\n\tcreatePkcs12MacData,\n\ttype ParsedPkcs12MacData,\n\ttype Pkcs12MacOptions,\n\tparsePkcs12MacData,\n} from './pkcs12-mac.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\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;\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// 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 * @example\n * ```ts\n * import { createPfx } from 'micro509';\n *\n * const pfx = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * // pfx.der, pfx.pem, pfx.base64\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<PfxMaterial> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\tcertificateBags.push(\n\t\t\tcreateCertificateBag(normalizeCertificate(certificate.certificate), certificate.attributes),\n\t\t);\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\tder,\n\t\tpem: pemEncode('PKCS12', der),\n\t\tbase64: base64Encode(der),\n\t};\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\ttry {\n\t\t\t\tmacData = await parsePkcs12MacData(\n\t\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tif (macData?.valid === false) {\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 = splitPemBlocks(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\tconst error: ParsePfxFailure = { ok: false, code, message };\n\treturn { ok: false, error, 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: parseCertificateDer(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 = splitPemBlocks(source).find((candidate) => candidate.label === 'CERTIFICATE');\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\treturn new Uint8Array(source);\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":"wuBAoOA,eAAsB,EAAU,EAA6C,CAC5E,IAAM,EAAgC,CAAC,EACjC,EAA+B,CAAC,EACtC,IAAK,IAAM,KAAe,EAAM,cAAgB,CAAC,EAChD,EAAgB,KACf,EAAqB,EAAqB,EAAY,WAAW,EAAG,EAAY,UAAU,CAC3F,EAED,IAAK,IAAM,KAAc,EAAM,aAAe,CAAC,EAC9C,EAAe,KACd,EAAoB,MAAM,EAAoB,EAAW,UAAU,EAAG,EAAW,UAAU,CAC5F,EAED,IAAM,EAA6B,CAAC,EAIpC,GAHI,EAAgB,OAAS,GAC5B,EAAa,KAAK,EAAsB,EAAS,CAAe,CAAC,CAAC,EAE/D,EAAe,OAAS,EAAG,CAC9B,IAAM,EAAe,EAAS,CAAc,EAC5C,EAAa,KACZ,EAAM,aAAe,IAAA,GAClB,EAAsB,CAAY,EAClC,MAAM,EAA+B,EAAc,EAAM,UAAU,CACvE,CACD,CACA,IAAM,EAAoB,EAAS,CAAY,EACzC,EACL,EAAM,MAAQ,IAAA,GAAY,IAAA,GAAY,MAAM,EAAoB,EAAmB,EAAM,GAAG,EACvF,EAAM,EAAS,CACpB,EAAkB,CAAC,EACnB,EAAsB,CAAiB,EACvC,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAC,EAAQ,GAAG,CAC9C,CAAC,EACD,MAAO,CACN,MACA,IAAK,EAAU,SAAU,CAAG,EAC5B,OAAQ,EAAa,CAAG,CACzB,CACD,CAuBA,eAAsB,EACrB,EACA,EAC0B,CAC1B,GAAI,CACH,IAAM,EAAW,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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\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, splitPemBlocks } 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 {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\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;\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\ttry {\n\t\t\t\tmacData = await parsePkcs12MacData(\n\t\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tif (macData?.valid === false) {\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 = splitPemBlocks(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 = splitPemBlocks(source).find((candidate) => candidate.label === 'CERTIFICATE');\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\treturn new Uint8Array(source);\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":"myBAyQA,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,EAAW,UAAU,EAAG,EAAW,UAAU,CAC5F,EAED,IAAM,EAA6B,CAAC,EAIpC,GAHI,EAAgB,OAAS,GAC5B,EAAa,KAAK,EAAsB,EAAS,CAAe,CAAC,CAAC,EAE/D,EAAe,OAAS,EAAG,CAC9B,IAAM,EAAe,EAAS,CAAc,EAC5C,EAAa,KACZ,EAAM,aAAe,IAAA,GAClB,EAAsB,CAAY,EAClC,MAAM,EAA+B,EAAc,EAAM,UAAU,CACvE,CACD,CACA,IAAM,EAAoB,EAAS,CAAY,EACzC,EACL,EAAM,MAAQ,IAAA,GAAY,IAAA,GAAY,MAAM,EAAoB,EAAmB,EAAM,GAAG,EACvF,EAAM,EAAS,CACpB,EAAkB,CAAC,EACnB,EAAsB,CAAiB,EACvC,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAC,EAAQ,GAAG,CAC9C,CAAC,EACD,MAAO,CACN,GAAI,GACJ,MAAO,CACN,MACA,IAAK,EAAU,SAAU,CAAG,EAC5B,OAAQ,EAAa,CAAG,CACzB,CACD,CACD,CAGA,SAAS,EACR,EACA,EAC0E,CAC1E,OAAO,EAAc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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"}
@@ -91,16 +91,37 @@ type VerifyPkcs7SignedDataResult = {
91
91
  /** Verification succeeded. */readonly ok: true; /** The verified SignedData structure. */
92
92
  readonly value: ParsedPkcs7SignedData;
93
93
  } | ErrorResult<"signer_not_found" | "signature_invalid" | "message_digest_mismatch" | "content_missing" | ParsePkcs7ErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>;
94
+ /** Caller-correctable failure code from {@linkcode createPkcs7CertBagDer} / {@linkcode createPkcs7CertBagPem}. */
95
+ type CreatePkcs7CertBagErrorCode = "invalid_certificate";
96
+ /** Error payload for a failed PKCS#7 certificate bag creation. */
97
+ interface CreatePkcs7CertBagFailure extends Micro509Error<CreatePkcs7CertBagErrorCode> {
98
+ /** Always `false` for failures. */
99
+ readonly ok: false;
100
+ }
101
+ /** Success-or-failure result from {@linkcode createPkcs7CertBagDer}. */
102
+ type CreatePkcs7CertBagDerResult = {
103
+ /** Creation succeeded. */readonly ok: true; /** Raw DER-encoded certificate bag. */
104
+ readonly value: Uint8Array;
105
+ } | ErrorResult<CreatePkcs7CertBagErrorCode, Record<never, never>, CreatePkcs7CertBagFailure>;
106
+ /** Success-or-failure result from {@linkcode createPkcs7CertBagPem}. */
107
+ type CreatePkcs7CertBagResult = {
108
+ /** Creation succeeded. */readonly ok: true; /** DER, PEM, and base64 forms of the certificate bag. */
109
+ readonly value: Pkcs7CertBag;
110
+ } | ErrorResult<CreatePkcs7CertBagErrorCode, Record<never, never>, CreatePkcs7CertBagFailure>;
94
111
  /**
95
112
  * Creates a degenerate PKCS#7 SignedData structure containing only certificates (no signers).
96
113
  *
97
- * Returns the raw DER encoding. Use {@linkcode createPkcs7CertBagPem} for PEM + base64.
114
+ * Returns a {@linkcode CreatePkcs7CertBagDerResult}: the raw DER on success, or a
115
+ * typed `invalid_certificate` failure when a certificate source is not valid
116
+ * PEM/DER. Use {@linkcode createPkcs7CertBagPem} for PEM + base64.
98
117
  */
99
- declare function createPkcs7CertBagDer(certificates: readonly Pkcs7CertificateSource[]): Uint8Array;
118
+ declare function createPkcs7CertBagDer(certificates: readonly Pkcs7CertificateSource[]): CreatePkcs7CertBagDerResult;
100
119
  /**
101
- * Creates a degenerate PKCS#7 SignedData certificate bag and returns DER, PEM, and base64 forms.
120
+ * Creates a degenerate PKCS#7 SignedData certificate bag and returns DER, PEM,
121
+ * and base64 forms, or a typed {@linkcode CreatePkcs7CertBagFailure} when a
122
+ * certificate source is not valid PEM/DER.
102
123
  */
103
- declare function createPkcs7CertBagPem(certificates: readonly Pkcs7CertificateSource[]): Pkcs7CertBag;
124
+ declare function createPkcs7CertBagPem(certificates: readonly Pkcs7CertificateSource[]): CreatePkcs7CertBagResult;
104
125
  /** A single signer for {@linkcode createPkcs7SignedDataDer} / {@linkcode createPkcs7SignedDataPem}. */
105
126
  interface Pkcs7Signer {
106
127
  /**
@@ -212,5 +233,5 @@ declare function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResul
212
233
  */
213
234
  declare function verifyPkcs7SignedData(input: string | Uint8Array | ParsedPkcs7SignedData): Promise<VerifyPkcs7SignedDataResult>;
214
235
  //#endregion
215
- export { CreatePkcs7SignedDataDerResult, CreatePkcs7SignedDataErrorCode, CreatePkcs7SignedDataFailure, CreatePkcs7SignedDataInput, CreatePkcs7SignedDataResult, ParsePkcs7CertBagResult, ParsePkcs7ErrorCode, ParsePkcs7Failure, ParsePkcs7SignedDataResult, ParsedPkcs7SignedData, ParsedPkcs7SignerInfo, Pkcs7CertBag, Pkcs7CertificateSource, Pkcs7SignedDataMaterial, Pkcs7Signer, VerifyPkcs7SignedDataFailure, VerifyPkcs7SignedDataResult, createPkcs7CertBagDer, createPkcs7CertBagPem, createPkcs7SignedDataDer, createPkcs7SignedDataPem, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData };
236
+ export { CreatePkcs7CertBagDerResult, CreatePkcs7CertBagErrorCode, CreatePkcs7CertBagFailure, CreatePkcs7CertBagResult, CreatePkcs7SignedDataDerResult, CreatePkcs7SignedDataErrorCode, CreatePkcs7SignedDataFailure, CreatePkcs7SignedDataInput, CreatePkcs7SignedDataResult, ParsePkcs7CertBagResult, ParsePkcs7ErrorCode, ParsePkcs7Failure, ParsePkcs7SignedDataResult, ParsedPkcs7SignedData, ParsedPkcs7SignerInfo, Pkcs7CertBag, Pkcs7CertificateSource, Pkcs7SignedDataMaterial, Pkcs7Signer, VerifyPkcs7SignedDataFailure, VerifyPkcs7SignedDataResult, createPkcs7CertBagDer, createPkcs7CertBagPem, createPkcs7SignedDataDer, createPkcs7SignedDataPem, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData };
216
237
  //# sourceMappingURL=pkcs7.d.ts.map
@@ -1,2 +1,2 @@
1
- import{concatBytes as e,explicitContext as t,integer as n,integerFromNumber as r,nullValue as i,objectIdentifier as a,octetString as o,readElement as s,readRootElement as c,readSequenceChildren as l,sequence as u,setOf as d}from"../internal/asn1/der.js";import{childrenOf as f,decodeIntegerNumber as p,decodeObjectIdentifier as m,decodeString as h,hexToBytes as g,requireElement as _,toArrayBuffer as v,toHex as y}from"../internal/asn1/asn1.js";import{OIDS as b}from"../internal/asn1/oids.js";import{getCrypto as x}from"../internal/crypto/webcrypto.js";import{base64Encode as S}from"../internal/shared/base64.js";import{pemEncode as C,splitPemBlocks as w}from"../pem/pem.js";import{describeHashAlgorithm as T,describeSignatureAlgorithm as E}from"../internal/crypto/algorithm-names.js";import{nameFieldKeyFromOid as D}from"../internal/x509/name-fields.js";import{parseCertificateDer as O}from"../x509/parse.js";import{verifySignedDataDetailed as k}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as A,getSignatureAlgorithm as j,signBytes as M}from"../internal/crypto/signing.js";import{compareDistinguishedNames as N}from"../internal/shared/dn.js";function P(n){let i=n.flatMap(G),o=u([r(1),d([]),u([a(b.pkcs7Data)]),t(0,e(i)),d([])]);return u([a(b.pkcs7SignedData),t(0,o)])}function F(e){let t=P(e);return{der:t,pem:C(`PKCS7`,t),base64:S(t)}}async function I(e){if(e.signers.length===0)return W(`no_signers`,`createPkcs7SignedData requires at least one signer`);let s=e.encapsulatedContentTypeOid??b.pkcs7Data,c=e.content.slice(),l=[],f=new Set,p=e=>{let t=y(e);f.has(t)||(f.add(t),l.push(e))},m=new Set,h=[];for(let t of e.signers){let e=G(t.certificate),l=e[0];if(l===void 0||e.length!==1)return W(`invalid_signer_certificate`,`Each PKCS#7 signer must provide exactly one certificate`);p(l);let d;try{d=O(l)}catch{return W(`invalid_signer_certificate`,`Each PKCS#7 signer certificate must be a parseable X.509 certificate`)}let f;try{f=j(t.privateKey,t.signature)}catch{return W(`unsupported_signer_key`,`Unsupported signer key or signature profile`)}let _=J(t.privateKey);if(_===void 0)return W(`unsupported_signer_key`,`Unsupported signer key algorithm for content digest`);m.add(_.digestOid);let{setForSigning:y,implicitForEmit:b}=Y(s,new Uint8Array(await x().subtle.digest(_.hashName,v(c)))),S=await M(t.privateKey,f,y);h.push(u([r(1),u([g(d.issuer.derHex),n(g(d.serialNumberHex))]),u([a(_.digestOid),i()]),b,A(f),o(S)]))}for(let t of e.additionalCertificates??[])for(let e of G(t))p(e);let _=s===b.pkcs7Data?1:3,S=new Uint8Array(d(l));S[0]=160;let C=u([r(_),d([...m].map(e=>u([a(e),i()]))),u([a(s),t(0,o(c))]),S,d(h)]);return{ok:!0,value:u([a(b.pkcs7SignedData),t(0,C)])}}async function ee(e){let t=await I(e);return t.ok?{ok:!0,value:{der:t.value,pem:C(`PKCS7`,t.value),base64:S(t.value)}}:t}function L(e){let t=z(e);return t.ok?{ok:!0,value:t.value.certificates}:t}function R(e){try{let t=w(e).filter(e=>e.label===`PKCS7`);if(t.length!==1)return H(`malformed`,`Expected exactly one PKCS7 PEM block`);let n=t[0];return n===void 0?H(`malformed`,`Missing PKCS7 block`):L(n.bytes)}catch{return H(`malformed`,`Expected exactly one PKCS7 PEM block`)}}function z(e){try{let t=l(e,{maxDepth:64}),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2||n.tag!==6||r.tag!==160||f(e,r).length!==1)return H(`malformed`,`Malformed PKCS#7 content info`);let i=m(n.value);if(i!==b.pkcs7SignedData)return H(`not_signed_data`,`PKCS#7 content is not signedData`);let a=f(e,ae(e,r,0,`signedData`)),o=a[0],s=a[1],c=a[2],u=a.slice(3),d=u[u.length-1],h,g;for(let e of u.slice(0,-1)){if(e?.tag===160){if(g!==void 0)return H(`malformed`,`SignedData certificates field must precede CRLs field`);if(h!==void 0)return H(`malformed`,`SignedData certificates field must not repeat`);h=e;continue}if(e?.tag===161){if(g!==void 0)return H(`malformed`,`SignedData CRLs field must not repeat`);g=e;continue}return H(`malformed`,`Malformed SignedData optional field`)}if(o===void 0||s===void 0||c===void 0||d===void 0||d.tag!==49)return H(`malformed`,`Malformed SignedData`);let _=e.slice(c.start-c.headerLength,c.end),v=l(_),y=v[0],x=v[1],S=Z(e,s);return y===void 0?H(`malformed`,`Malformed EncapsulatedContentInfo`):{ok:!0,value:{der:new Uint8Array(e),contentTypeOid:i,version:p(o.value),digestAlgorithmOids:S,digestAlgorithmNames:S.map(e=>T(e)),encapsulatedContentTypeOid:m(y.value),...x===void 0?{}:{encapsulatedContent:te(_,x)},certificates:X(e,h),signerInfos:Q(e,d)}}}catch{return H(`malformed`,`Malformed PKCS#7 structure`)}}function B(e){try{let t=w(e).filter(e=>e.label===`PKCS7`),n=t[0];return n===void 0||t.length!==1?H(`malformed`,`Expected exactly one PKCS7 PEM block`):z(n.bytes)}catch{return H(`malformed`,`Expected exactly one PKCS7 PEM block`)}}async function V(e){let t;if(typeof e==`string`){let n=B(e);if(!n.ok)return n;t=n.value}else if(e instanceof Uint8Array){let n=z(e);if(!n.ok)return n;t=n.value}else{if(!fe(e))return U(`malformed`,`SignedData parsed input is malformed`);let n=z(new Uint8Array(e.der));if(!n.ok)return n;t=n.value}if(t.encapsulatedContent===void 0)return U(`content_missing`,`SignedData encapsulated content is missing`);for(let e of t.signerInfos){let n=t.certificates.find(t=>ue(t,e));if(n===void 0)return U(`signer_not_found`,`Signer certificate not found in SignedData certificates`);if(e.hasSignedAttrs){let r=await le(e,n,t.encapsulatedContent,t.encapsulatedContentTypeOid);if(!r.ok)return r;continue}let r;try{let i=await k(e.signatureAlgorithmOid,e.signatureAlgorithmParametersDer,n.publicKeyAlgorithmOid,n.publicKeyParametersOid,n.subjectPublicKeyInfoDer,e.signature,t.encapsulatedContent);if(!i.ok)return i.code===`verification_error`?U(`malformed`,`SignedData signature verification failed`):U(`malformed`,`Unsupported signature algorithm in SignedData`);r=i.valid}catch{return U(`malformed`,`Unsupported signature algorithm in SignedData`)}if(!r)return U(`signature_invalid`,`SignedData signature does not verify`)}return{ok:!0,value:t}}function H(e,t){return{ok:!1,error:{ok:!1,code:e,message:t},code:e,message:t}}function U(e,t){return{ok:!1,error:{ok:!1,code:e,message:t},code:e,message:t}}function W(e,t){return{ok:!1,error:{ok:!1,code:e,message:t},code:e,message:t}}function G(e){return typeof e==`string`?w(e).filter(e=>e.label===`CERTIFICATE`).map(e=>new Uint8Array(e.bytes)):[new Uint8Array(e)]}function K(e){return`hash`in e}function q(e){return`namedCurve`in e}function J(e){let t=e.algorithm;if(t.name===`ECDSA`){if(!q(t))return;switch(t.namedCurve){case`P-256`:return{hashName:`SHA-256`,digestOid:b.sha256};case`P-384`:return{hashName:`SHA-384`,digestOid:b.sha384};case`P-521`:return{hashName:`SHA-512`,digestOid:b.sha512};default:return}}if(t.name===`RSASSA-PKCS1-v1_5`||t.name===`RSA-PSS`){if(!K(t))return;switch(t.hash.name){case`SHA-256`:return{hashName:`SHA-256`,digestOid:b.sha256};case`SHA-384`:return{hashName:`SHA-384`,digestOid:b.sha384};case`SHA-512`:return{hashName:`SHA-512`,digestOid:b.sha512};default:return}}if(t.name===`Ed25519`)return{hashName:`SHA-512`,digestOid:b.sha512}}function Y(e,t){let n=d([u([a(b.cmsContentType),d([a(e)])]),u([a(b.cmsMessageDigest),d([o(t)])])]),r=new Uint8Array(n);return r[0]=160,{setForSigning:n,implicitForEmit:r}}function X(e,t){if(t===void 0||t.tag!==160)return[];let n=[],r=t.start;for(;r<t.end;){let t=s(e,r);n.push(O(e.slice(r,t.end))),r=t.end}return n}function Z(e,t){let n=[];if(t.tag!==49)throw Error(`digestAlgorithms must use SET`);for(let r of f(e,t)){if(r.tag!==48)throw Error(`digestAlgorithm must use AlgorithmIdentifier SEQUENCE`);let t=l(e.slice(r.start-r.headerLength,r.end)),i=t[0];if(i===void 0||t.length<1||t.length>2||i.tag!==6)throw Error(`Malformed digest AlgorithmIdentifier`);n.push(m(i.value))}return n}function Q(e,t){let n=[];for(let r of f(e,t)){let t=e.slice(r.start-r.headerLength,r.end),i=l(t),a=i[0],o=i[1],s=i[2],c=3,u=i[c]?.tag===160?i[c]:void 0,d=u!==void 0;d&&(c+=1);let f=i[c],h=i[c+1],g=i[c+2];if(a===void 0||o===void 0||s===void 0||f===void 0||h===void 0||h.tag!==4||i.length>c+3||g!==void 0&&g.tag!==161)throw Error(`Malformed SignerInfo`);let v=m(_(l(t.slice(s.start-s.headerLength,s.end))[0],`digest algorithm OID`).value),b=t.slice(f.start-f.headerLength,f.end),x=l(b),S=m(_(x[0],`signature algorithm OID`).value),C=x[1],w=ne(t.slice(o.start-o.headerLength,o.end));n.push({version:p(a.value),...w.issuer===void 0?{}:{issuer:w.issuer},...w.serialNumberHex===void 0?{}:{serialNumberHex:w.serialNumberHex},...w.subjectKeyIdentifier===void 0?{}:{subjectKeyIdentifier:w.subjectKeyIdentifier},digestAlgorithmOid:v,digestAlgorithmName:T(v),signatureAlgorithmOid:S,signatureAlgorithmName:E(S,C===void 0?void 0:new Uint8Array(b.slice(C.start-C.headerLength,C.end))),...C===void 0?{}:{signatureAlgorithmParametersDer:new Uint8Array(b.slice(C.start-C.headerLength,C.end))},signatureHex:y(h.value),signature:new Uint8Array(h.value),hasSignedAttrs:d,...u===void 0?{}:{signedAttrsDer:new Uint8Array(t.slice(u.start-u.headerLength,u.end))}})}return n}function te(e,t){if(t.tag!==160)throw Error(`Unexpected encapsulated content tag`);let n=s(e,t.start);if(n.tag!==4)throw Error(`Expected encapsulated OCTET STRING`);return n.value}function ne(e){let t=c(e,{maxDepth:64});if(t.tag===128){if(t.value.length===0)throw Error(`SignerIdentifier subjectKeyIdentifier must not be empty`);return{subjectKeyIdentifier:y(t.value)}}if(t.tag===48){let t=l(e),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2)throw Error(`SignerIdentifier issuerAndSerialNumber is malformed`);if(n.tag!==48)throw Error(`SignerIdentifier issuer must use Name SEQUENCE`);if(r.tag!==2)throw Error(`SignerIdentifier serialNumber must use INTEGER`);return pe(r.value,`SignerIdentifier serialNumber`),{issuer:ie(e,n),serialNumberHex:y(r.value)}}throw Error(`Unsupported SignerIdentifier tag: ${String(t.tag)}`)}const re=new TextDecoder;function ie(e,t){let n=y(e.slice(t.start-t.headerLength,t.end)),r=[],i=[],a={};for(let n of f(e,t)){let t=[],o={};for(let r of f(e,n)){let n=f(e,r),s=_(n[0],`signer issuer attribute OID`),c=_(n[1],`signer issuer attribute value`),l=m(s.value),u;try{u=h(c.tag,c.value)}catch{u=re.decode(c.value)}let d=D(l),p=d===void 0?{oid:l,valueTag:c.tag,value:u}:{oid:l,key:d,valueTag:c.tag,value:u};t.push(p),i.push(p),d!==void 0&&(o[d]===void 0&&(o[d]=u),a[d]===void 0&&(a[d]=u))}r.push({derHex:y(e.slice(n.start-n.headerLength,n.end)),attributes:t,values:o})}return{derHex:n,rdns:r,attributes:i,values:a}}function ae(e,t,n,r){let i=t.start,a=0;for(;i<t.end;){let t=s(e,i);if(a===n)return t;i=t.end,a+=1}throw Error(`Missing ${r}`)}function oe(e){switch(e){case b.sha256:return`SHA-256`;case b.sha384:return`SHA-384`;case b.sha512:return`SHA-512`;default:throw Error(`Unsupported digest algorithm OID: ${e}`)}}function $(e){let t=s(e),n,r;for(let i of f(e,t)){let t=e.slice(i.start-i.headerLength,i.end),a=l(t),o=a[0],s=a[1];if(o===void 0||s===void 0||a.length!==2||s.tag!==49)throw Error(`Malformed signedAttrs attribute`);let c=m(o.value),u=f(t,s);if(c===b.cmsMessageDigest){if(n!==void 0||u.length!==1)throw Error(`messageDigest attribute must appear exactly once with one value`);let e=u[0];if(e===void 0||e.tag!==4)throw Error(`messageDigest attribute value must use OCTET STRING`);n=e.value;continue}if(c===b.cmsContentType){if(r!==void 0||u.length!==1)throw Error(`contentType attribute must appear exactly once with one value`);let e=u[0];if(e===void 0||e.tag!==6)throw Error(`contentType attribute value must use OBJECT IDENTIFIER`);r=m(e.value)}}if(n===void 0)throw Error(`Missing messageDigest attribute in signedAttrs`);if(r===void 0)throw Error(`Missing contentType attribute in signedAttrs`);return{messageDigest:n,contentTypeOid:r}}function se(e){let t=new Uint8Array(e);return t[0]=49,t}function ce(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=(e[r]??0)^(t[r]??0);return n===0}async function le(e,t,n,r){if(e.signedAttrsDer===void 0)return U(`malformed`,`Missing signedAttrs DER`);let i;try{de(e.signedAttrsDer),i=$(e.signedAttrsDer)}catch{return U(`malformed`,`Malformed signedAttrs in SignedData`)}if(i.contentTypeOid!==r)return U(`malformed`,`SignedData contentType attribute does not match`);let a;try{let t=oe(e.digestAlgorithmOid);a=new Uint8Array(await x().subtle.digest(t,v(n)))}catch{return U(`malformed`,`Unsupported digest algorithm in SignedData`)}if(!ce(a,i.messageDigest))return U(`message_digest_mismatch`,`Content digest does not match messageDigest attribute`);let o;try{o=se(e.signedAttrsDer)}catch{return U(`malformed`,`Malformed signedAttrs in SignedData`)}let s;try{let n=await k(e.signatureAlgorithmOid,e.signatureAlgorithmParametersDer,t.publicKeyAlgorithmOid,t.publicKeyParametersOid,t.subjectPublicKeyInfoDer,e.signature,o);if(!n.ok)return n.code===`verification_error`?U(`malformed`,`SignedData signature verification failed`):U(`malformed`,`Unsupported signature algorithm in SignedData`);s=n.valid}catch{return U(`malformed`,`Unsupported signature algorithm in SignedData`)}return s?{ok:!0}:U(`signature_invalid`,`SignedData signature over signedAttrs does not verify`)}function ue(e,t){return t.issuer!==void 0||t.serialNumberHex!==void 0?t.issuer!==void 0&&t.serialNumberHex!==void 0&&e.serialNumberHex===t.serialNumberHex&&N(e.issuer,t.issuer):t.subjectKeyIdentifier!==void 0&&e.subjectKeyIdentifier===t.subjectKeyIdentifier}function de(e){if(s(e).tag!==160)throw Error(`signedAttrs must use IMPLICIT [0] tag`)}function fe(e){return`der`in e&&e.der instanceof Uint8Array}function pe(e,t){let n=e[0];if(n===void 0)throw Error(`${t} must not be empty`);if(n&128)throw Error(`${t} must be non-negative`);if(e.length>1&&n===0&&!((e[1]??0)&128))throw Error(`${t} must use minimal encoding`)}export{P as createPkcs7CertBagDer,F as createPkcs7CertBagPem,I as createPkcs7SignedDataDer,ee as createPkcs7SignedDataPem,L as parsePkcs7CertBagDer,R as parsePkcs7CertBagPem,z as parsePkcs7SignedDataDer,B as parsePkcs7SignedDataPem,V as verifyPkcs7SignedData};
1
+ import{concatBytes as e,explicitContext as t,integer as n,integerFromNumber as r,nullValue as i,objectIdentifier as a,octetString as o,readElement as s,readRootElement as c,readSequenceChildren as l,sequence as u,setOf as d}from"../internal/asn1/der.js";import{childrenOf as f,decodeIntegerNumber as p,decodeObjectIdentifier as m,decodeString as h,hexToBytes as g,requireElement as _,toArrayBuffer as v,toHex as y}from"../internal/asn1/asn1.js";import{OIDS as b}from"../internal/asn1/oids.js";import{getCrypto as x}from"../internal/crypto/webcrypto.js";import{base64Encode as S}from"../internal/shared/base64.js";import{pemEncode as C,splitPemBlocks as w}from"../pem/pem.js";import{failureResult as T}from"../result/result.js";import{describeHashAlgorithm as E,describeSignatureAlgorithm as D}from"../internal/crypto/algorithm-names.js";import{nameFieldKeyFromOid as O}from"../internal/x509/name-fields.js";import{parseCertificateDerOrThrow as k}from"../x509/parse.js";import{verifySignedDataDetailed as A}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as j,getSignatureAlgorithm as M,signBytes as N}from"../internal/crypto/signing.js";import{compareDistinguishedNames as P}from"../internal/shared/dn.js";function F(n){let i;try{i=n.flatMap(q)}catch{return G(`invalid_certificate`,`Each PKCS#7 certificate source must be valid PEM or DER`)}let o=u([r(1),d([]),u([a(b.pkcs7Data)]),t(0,e(i)),d([])]);return{ok:!0,value:u([a(b.pkcs7SignedData),t(0,o)])}}function I(e){let t=F(e);return t.ok?{ok:!0,value:{der:t.value,pem:C(`PKCS7`,t.value),base64:S(t.value)}}:t}async function L(e){if(e.signers.length===0)return K(`no_signers`,`createPkcs7SignedData requires at least one signer`);let s=e.encapsulatedContentTypeOid??b.pkcs7Data,c=e.content.slice(),l=[],f=new Set,p=e=>{let t=y(e);f.has(t)||(f.add(t),l.push(e))},m=new Set,h=[];for(let t of e.signers){let e=q(t.certificate),l=e[0];if(l===void 0||e.length!==1)return K(`invalid_signer_certificate`,`Each PKCS#7 signer must provide exactly one certificate`);p(l);let d;try{d=k(l)}catch{return K(`invalid_signer_certificate`,`Each PKCS#7 signer certificate must be a parseable X.509 certificate`)}let f;try{f=M(t.privateKey,t.signature)}catch{return K(`unsupported_signer_key`,`Unsupported signer key or signature profile`)}let _=X(t.privateKey);if(_===void 0)return K(`unsupported_signer_key`,`Unsupported signer key algorithm for content digest`);m.add(_.digestOid);let{setForSigning:y,implicitForEmit:b}=Z(s,new Uint8Array(await x().subtle.digest(_.hashName,v(c)))),S=await N(t.privateKey,f,y);h.push(u([r(1),u([g(d.issuer.derHex),n(g(d.serialNumberHex))]),u([a(_.digestOid),i()]),b,j(f),o(S)]))}for(let t of e.additionalCertificates??[])for(let e of q(t))p(e);let _=s===b.pkcs7Data?1:3,S=new Uint8Array(d(l));S[0]=160;let C=u([r(_),d([...m].map(e=>u([a(e),i()]))),u([a(s),t(0,o(c))]),S,d(h)]);return{ok:!0,value:u([a(b.pkcs7SignedData),t(0,C)])}}async function ee(e){let t=await L(e);return t.ok?{ok:!0,value:{der:t.value,pem:C(`PKCS7`,t.value),base64:S(t.value)}}:t}function R(e){let t=B(e);return t.ok?{ok:!0,value:t.value.certificates}:t}function z(e){try{let t=w(e).filter(e=>e.label===`PKCS7`);if(t.length!==1)return U(`malformed`,`Expected exactly one PKCS7 PEM block`);let n=t[0];return n===void 0?U(`malformed`,`Missing PKCS7 block`):R(n.bytes)}catch{return U(`malformed`,`Expected exactly one PKCS7 PEM block`)}}function B(e){try{let t=l(e,{maxDepth:64}),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2||n.tag!==6||r.tag!==160||f(e,r).length!==1)return U(`malformed`,`Malformed PKCS#7 content info`);let i=m(n.value);if(i!==b.pkcs7SignedData)return U(`not_signed_data`,`PKCS#7 content is not signedData`);let a=f(e,$(e,r,0,`signedData`)),o=a[0],s=a[1],c=a[2],u=a.slice(3),d=u[u.length-1],h,g;for(let e of u.slice(0,-1)){if(e?.tag===160){if(g!==void 0)return U(`malformed`,`SignedData certificates field must precede CRLs field`);if(h!==void 0)return U(`malformed`,`SignedData certificates field must not repeat`);h=e;continue}if(e?.tag===161){if(g!==void 0)return U(`malformed`,`SignedData CRLs field must not repeat`);g=e;continue}return U(`malformed`,`Malformed SignedData optional field`)}if(o===void 0||s===void 0||c===void 0||d===void 0||d.tag!==49)return U(`malformed`,`Malformed SignedData`);let _=e.slice(c.start-c.headerLength,c.end),v=l(_),y=v[0],x=v[1],S=te(e,s);return y===void 0?U(`malformed`,`Malformed EncapsulatedContentInfo`):{ok:!0,value:{der:new Uint8Array(e),contentTypeOid:i,version:p(o.value),digestAlgorithmOids:S,digestAlgorithmNames:S.map(e=>E(e)),encapsulatedContentTypeOid:m(y.value),...x===void 0?{}:{encapsulatedContent:re(_,x)},certificates:Q(e,h),signerInfos:ne(e,d)}}}catch{return U(`malformed`,`Malformed PKCS#7 structure`)}}function V(e){try{let t=w(e).filter(e=>e.label===`PKCS7`),n=t[0];return n===void 0||t.length!==1?U(`malformed`,`Expected exactly one PKCS7 PEM block`):B(n.bytes)}catch{return U(`malformed`,`Expected exactly one PKCS7 PEM block`)}}async function H(e){let t;if(typeof e==`string`){let n=V(e);if(!n.ok)return n;t=n.value}else if(e instanceof Uint8Array){let n=B(e);if(!n.ok)return n;t=n.value}else{if(!me(e))return W(`malformed`,`SignedData parsed input is malformed`);let n=B(new Uint8Array(e.der));if(!n.ok)return n;t=n.value}if(t.encapsulatedContent===void 0)return W(`content_missing`,`SignedData encapsulated content is missing`);for(let e of t.signerInfos){let n=t.certificates.find(t=>fe(t,e));if(n===void 0)return W(`signer_not_found`,`Signer certificate not found in SignedData certificates`);if(e.hasSignedAttrs){let r=await de(e,n,t.encapsulatedContent,t.encapsulatedContentTypeOid);if(!r.ok)return r;continue}let r;try{let i=await A(e.signatureAlgorithmOid,e.signatureAlgorithmParametersDer,n.publicKeyAlgorithmOid,n.publicKeyParametersOid,n.subjectPublicKeyInfoDer,e.signature,t.encapsulatedContent);if(!i.ok)return i.code===`verification_error`?W(`malformed`,`SignedData signature verification failed`):W(`malformed`,`Unsupported signature algorithm in SignedData`);r=i.valid}catch{return W(`malformed`,`Unsupported signature algorithm in SignedData`)}if(!r)return W(`signature_invalid`,`SignedData signature does not verify`)}return{ok:!0,value:t}}function U(e,t){return T(e,t)}function W(e,t){return T(e,t)}function G(e,t){return T(e,t)}function K(e,t){return T(e,t)}function q(e){return typeof e==`string`?w(e).filter(e=>e.label===`CERTIFICATE`).map(e=>new Uint8Array(e.bytes)):[new Uint8Array(e)]}function J(e){return`hash`in e}function Y(e){return`namedCurve`in e}function X(e){let t=e.algorithm;if(t.name===`ECDSA`){if(!Y(t))return;switch(t.namedCurve){case`P-256`:return{hashName:`SHA-256`,digestOid:b.sha256};case`P-384`:return{hashName:`SHA-384`,digestOid:b.sha384};case`P-521`:return{hashName:`SHA-512`,digestOid:b.sha512};default:return}}if(t.name===`RSASSA-PKCS1-v1_5`||t.name===`RSA-PSS`){if(!J(t))return;switch(t.hash.name){case`SHA-256`:return{hashName:`SHA-256`,digestOid:b.sha256};case`SHA-384`:return{hashName:`SHA-384`,digestOid:b.sha384};case`SHA-512`:return{hashName:`SHA-512`,digestOid:b.sha512};default:return}}if(t.name===`Ed25519`)return{hashName:`SHA-512`,digestOid:b.sha512}}function Z(e,t){let n=d([u([a(b.cmsContentType),d([a(e)])]),u([a(b.cmsMessageDigest),d([o(t)])])]),r=new Uint8Array(n);return r[0]=160,{setForSigning:n,implicitForEmit:r}}function Q(e,t){if(t===void 0||t.tag!==160)return[];let n=[],r=t.start;for(;r<t.end;){let t=s(e,r);n.push(k(e.slice(r,t.end))),r=t.end}return n}function te(e,t){let n=[];if(t.tag!==49)throw Error(`digestAlgorithms must use SET`);for(let r of f(e,t)){if(r.tag!==48)throw Error(`digestAlgorithm must use AlgorithmIdentifier SEQUENCE`);let t=l(e.slice(r.start-r.headerLength,r.end)),i=t[0];if(i===void 0||t.length<1||t.length>2||i.tag!==6)throw Error(`Malformed digest AlgorithmIdentifier`);n.push(m(i.value))}return n}function ne(e,t){let n=[];for(let r of f(e,t)){let t=e.slice(r.start-r.headerLength,r.end),i=l(t),a=i[0],o=i[1],s=i[2],c=3,u=i[c]?.tag===160?i[c]:void 0,d=u!==void 0;d&&(c+=1);let f=i[c],h=i[c+1],g=i[c+2];if(a===void 0||o===void 0||s===void 0||f===void 0||h===void 0||h.tag!==4||i.length>c+3||g!==void 0&&g.tag!==161)throw Error(`Malformed SignerInfo`);let v=m(_(l(t.slice(s.start-s.headerLength,s.end))[0],`digest algorithm OID`).value),b=t.slice(f.start-f.headerLength,f.end),x=l(b),S=m(_(x[0],`signature algorithm OID`).value),C=x[1],w=ie(t.slice(o.start-o.headerLength,o.end));n.push({version:p(a.value),...w.issuer===void 0?{}:{issuer:w.issuer},...w.serialNumberHex===void 0?{}:{serialNumberHex:w.serialNumberHex},...w.subjectKeyIdentifier===void 0?{}:{subjectKeyIdentifier:w.subjectKeyIdentifier},digestAlgorithmOid:v,digestAlgorithmName:E(v),signatureAlgorithmOid:S,signatureAlgorithmName:D(S,C===void 0?void 0:new Uint8Array(b.slice(C.start-C.headerLength,C.end))),...C===void 0?{}:{signatureAlgorithmParametersDer:new Uint8Array(b.slice(C.start-C.headerLength,C.end))},signatureHex:y(h.value),signature:new Uint8Array(h.value),hasSignedAttrs:d,...u===void 0?{}:{signedAttrsDer:new Uint8Array(t.slice(u.start-u.headerLength,u.end))}})}return n}function re(e,t){if(t.tag!==160)throw Error(`Unexpected encapsulated content tag`);let n=s(e,t.start);if(n.tag!==4)throw Error(`Expected encapsulated OCTET STRING`);return n.value}function ie(e){let t=c(e,{maxDepth:64});if(t.tag===128){if(t.value.length===0)throw Error(`SignerIdentifier subjectKeyIdentifier must not be empty`);return{subjectKeyIdentifier:y(t.value)}}if(t.tag===48){let t=l(e),n=t[0],r=t[1];if(n===void 0||r===void 0||t.length!==2)throw Error(`SignerIdentifier issuerAndSerialNumber is malformed`);if(n.tag!==48)throw Error(`SignerIdentifier issuer must use Name SEQUENCE`);if(r.tag!==2)throw Error(`SignerIdentifier serialNumber must use INTEGER`);return he(r.value,`SignerIdentifier serialNumber`),{issuer:oe(e,n),serialNumberHex:y(r.value)}}throw Error(`Unsupported SignerIdentifier tag: ${String(t.tag)}`)}const ae=new TextDecoder;function oe(e,t){let n=y(e.slice(t.start-t.headerLength,t.end)),r=[],i=[],a={};for(let n of f(e,t)){let t=[],o={};for(let r of f(e,n)){let n=f(e,r),s=_(n[0],`signer issuer attribute OID`),c=_(n[1],`signer issuer attribute value`),l=m(s.value),u;try{u=h(c.tag,c.value)}catch{u=ae.decode(c.value)}let d=O(l),p=d===void 0?{oid:l,valueTag:c.tag,value:u}:{oid:l,key:d,valueTag:c.tag,value:u};t.push(p),i.push(p),d!==void 0&&(o[d]===void 0&&(o[d]=u),a[d]===void 0&&(a[d]=u))}r.push({derHex:y(e.slice(n.start-n.headerLength,n.end)),attributes:t,values:o})}return{derHex:n,rdns:r,attributes:i,values:a}}function $(e,t,n,r){let i=t.start,a=0;for(;i<t.end;){let t=s(e,i);if(a===n)return t;i=t.end,a+=1}throw Error(`Missing ${r}`)}function se(e){switch(e){case b.sha256:return`SHA-256`;case b.sha384:return`SHA-384`;case b.sha512:return`SHA-512`;default:throw Error(`Unsupported digest algorithm OID: ${e}`)}}function ce(e){let t=s(e),n,r;for(let i of f(e,t)){let t=e.slice(i.start-i.headerLength,i.end),a=l(t),o=a[0],s=a[1];if(o===void 0||s===void 0||a.length!==2||s.tag!==49)throw Error(`Malformed signedAttrs attribute`);let c=m(o.value),u=f(t,s);if(c===b.cmsMessageDigest){if(n!==void 0||u.length!==1)throw Error(`messageDigest attribute must appear exactly once with one value`);let e=u[0];if(e===void 0||e.tag!==4)throw Error(`messageDigest attribute value must use OCTET STRING`);n=e.value;continue}if(c===b.cmsContentType){if(r!==void 0||u.length!==1)throw Error(`contentType attribute must appear exactly once with one value`);let e=u[0];if(e===void 0||e.tag!==6)throw Error(`contentType attribute value must use OBJECT IDENTIFIER`);r=m(e.value)}}if(n===void 0)throw Error(`Missing messageDigest attribute in signedAttrs`);if(r===void 0)throw Error(`Missing contentType attribute in signedAttrs`);return{messageDigest:n,contentTypeOid:r}}function le(e){let t=new Uint8Array(e);return t[0]=49,t}function ue(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=(e[r]??0)^(t[r]??0);return n===0}async function de(e,t,n,r){if(e.signedAttrsDer===void 0)return W(`malformed`,`Missing signedAttrs DER`);let i;try{pe(e.signedAttrsDer),i=ce(e.signedAttrsDer)}catch{return W(`malformed`,`Malformed signedAttrs in SignedData`)}if(i.contentTypeOid!==r)return W(`malformed`,`SignedData contentType attribute does not match`);let a;try{let t=se(e.digestAlgorithmOid);a=new Uint8Array(await x().subtle.digest(t,v(n)))}catch{return W(`malformed`,`Unsupported digest algorithm in SignedData`)}if(!ue(a,i.messageDigest))return W(`message_digest_mismatch`,`Content digest does not match messageDigest attribute`);let o;try{o=le(e.signedAttrsDer)}catch{return W(`malformed`,`Malformed signedAttrs in SignedData`)}let s;try{let n=await A(e.signatureAlgorithmOid,e.signatureAlgorithmParametersDer,t.publicKeyAlgorithmOid,t.publicKeyParametersOid,t.subjectPublicKeyInfoDer,e.signature,o);if(!n.ok)return n.code===`verification_error`?W(`malformed`,`SignedData signature verification failed`):W(`malformed`,`Unsupported signature algorithm in SignedData`);s=n.valid}catch{return W(`malformed`,`Unsupported signature algorithm in SignedData`)}return s?{ok:!0}:W(`signature_invalid`,`SignedData signature over signedAttrs does not verify`)}function fe(e,t){return t.issuer!==void 0||t.serialNumberHex!==void 0?t.issuer!==void 0&&t.serialNumberHex!==void 0&&e.serialNumberHex===t.serialNumberHex&&P(e.issuer,t.issuer):t.subjectKeyIdentifier!==void 0&&e.subjectKeyIdentifier===t.subjectKeyIdentifier}function pe(e){if(s(e).tag!==160)throw Error(`signedAttrs must use IMPLICIT [0] tag`)}function me(e){return`der`in e&&e.der instanceof Uint8Array}function he(e,t){let n=e[0];if(n===void 0)throw Error(`${t} must not be empty`);if(n&128)throw Error(`${t} must be non-negative`);if(e.length>1&&n===0&&!((e[1]??0)&128))throw Error(`${t} must use minimal encoding`)}export{F as createPkcs7CertBagDer,I as createPkcs7CertBagPem,L as createPkcs7SignedDataDer,ee as createPkcs7SignedDataPem,R as parsePkcs7CertBagDer,z as parsePkcs7CertBagPem,B as parsePkcs7SignedDataDer,V as parsePkcs7SignedDataPem,H as verifyPkcs7SignedData};
2
2
  //# sourceMappingURL=pkcs7.js.map