@signature-kit/crypto 0.1.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 (43) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +30 -0
  4. package/dist/base64.d.ts +3 -0
  5. package/dist/base64.d.ts.map +1 -0
  6. package/dist/base64.js +55 -0
  7. package/dist/config.d.ts +46 -0
  8. package/dist/config.d.ts.map +1 -0
  9. package/dist/config.js +78 -0
  10. package/dist/pem.d.ts +3 -0
  11. package/dist/pem.d.ts.map +1 -0
  12. package/dist/pem.js +15 -0
  13. package/dist/pkcs12.d.ts +13 -0
  14. package/dist/pkcs12.d.ts.map +1 -0
  15. package/dist/pkcs12.js +471 -0
  16. package/dist/primitives/aes.d.ts +17 -0
  17. package/dist/primitives/aes.d.ts.map +1 -0
  18. package/dist/primitives/aes.js +219 -0
  19. package/dist/primitives/des.d.ts +23 -0
  20. package/dist/primitives/des.d.ts.map +1 -0
  21. package/dist/primitives/des.js +271 -0
  22. package/dist/primitives/hmac.d.ts +39 -0
  23. package/dist/primitives/hmac.d.ts.map +1 -0
  24. package/dist/primitives/hmac.js +146 -0
  25. package/dist/primitives/padding.d.ts +11 -0
  26. package/dist/primitives/padding.d.ts.map +1 -0
  27. package/dist/primitives/padding.js +29 -0
  28. package/dist/primitives/pbkdf2.d.ts +19 -0
  29. package/dist/primitives/pbkdf2.d.ts.map +1 -0
  30. package/dist/primitives/pbkdf2.js +61 -0
  31. package/dist/primitives/rc2.d.ts +23 -0
  32. package/dist/primitives/rc2.d.ts.map +1 -0
  33. package/dist/primitives/rc2.js +192 -0
  34. package/dist/primitives/sha1.d.ts +15 -0
  35. package/dist/primitives/sha1.d.ts.map +1 -0
  36. package/dist/primitives/sha1.js +102 -0
  37. package/dist/primitives/sha256.d.ts +30 -0
  38. package/dist/primitives/sha256.d.ts.map +1 -0
  39. package/dist/primitives/sha256.js +146 -0
  40. package/dist/primitives/sha512.d.ts +22 -0
  41. package/dist/primitives/sha512.d.ts.map +1 -0
  42. package/dist/primitives/sha512.js +197 -0
  43. package/package.json +61 -0
package/dist/pkcs12.js ADDED
@@ -0,0 +1,471 @@
1
+ /**
2
+ * PKCS#12 (.pfx/.p12) parser — fully Effect-native.
3
+ *
4
+ * Navigates the ASN.1 structure with the typed `@signature-kit/asn1` accessors, so
5
+ * every read narrows without a cast. The MAC check is the password gate; once it
6
+ * passes, a later cipher failure is treated as a corrupt file. All failures are
7
+ * `CryptoError` constructed at the decision point — nothing throws.
8
+ */
9
+ import { Asn1Error, bytesOf, childrenOf, decode, encode, integerBigInt, oidString, } from "@signature-kit/asn1";
10
+ import { Effect, Redacted } from "effect";
11
+ import { CryptoError, CryptoErrorCodeValue, CryptoOperationValue, } from "./config";
12
+ import { hmac } from "./primitives/hmac";
13
+ import { pbkdf2 } from "./primitives/pbkdf2";
14
+ import { sha1 } from "./primitives/sha1";
15
+ import { sha256 } from "./primitives/sha256";
16
+ import { sha384, sha512 } from "./primitives/sha512";
17
+ import { aesCbcDecrypt } from "./primitives/aes";
18
+ import { tripleDesCbcDecrypt } from "./primitives/des";
19
+ import { rc2CbcDecrypt } from "./primitives/rc2";
20
+ const OID_DATA = "1.2.840.113549.1.7.1";
21
+ const OID_ENCRYPTED_DATA = "1.2.840.113549.1.7.6";
22
+ const OID_CERT_BAG = "1.2.840.113549.1.12.10.1.3";
23
+ const OID_PKCS8_SHROUDED_KEY_BAG = "1.2.840.113549.1.12.10.1.2";
24
+ const OID_X509_CERT = "1.2.840.113549.1.9.22.1";
25
+ const OID_LOCAL_KEY_ID = "1.2.840.113549.1.9.21";
26
+ const OID_PBE_SHA_3DES = "1.2.840.113549.1.12.1.3";
27
+ const OID_PBE_SHA_2DES = "1.2.840.113549.1.12.1.4";
28
+ const OID_PBE_SHA_RC2_128 = "1.2.840.113549.1.12.1.5";
29
+ const OID_PBE_SHA_RC2_40 = "1.2.840.113549.1.12.1.6";
30
+ const OID_PBES2 = "1.2.840.113549.1.5.13";
31
+ const OID_PBKDF2 = "1.2.840.113549.1.5.12";
32
+ const OID_AES_128_CBC = "2.16.840.1.101.3.4.1.2";
33
+ const OID_AES_192_CBC = "2.16.840.1.101.3.4.1.22";
34
+ const OID_AES_256_CBC = "2.16.840.1.101.3.4.1.42";
35
+ const OID_DES_EDE3_CBC = "1.2.840.113549.3.7";
36
+ const OID_HMAC_SHA256 = "1.2.840.113549.2.9";
37
+ const OID_HMAC_SHA384 = "1.2.840.113549.2.10";
38
+ const OID_HMAC_SHA512 = "1.2.840.113549.2.11";
39
+ const OID_SHA256 = "2.16.840.1.101.3.4.2.1";
40
+ const OID_SHA384 = "2.16.840.1.101.3.4.2.2";
41
+ const OID_SHA512 = "2.16.840.1.101.3.4.2.3";
42
+ const elementAt = (nodes, index, label) => {
43
+ const node = nodes[index];
44
+ return node === undefined
45
+ ? Effect.fail(new CryptoError({
46
+ code: CryptoErrorCodeValue.corruptedFile,
47
+ reason: `Missing ${label} (element ${index}).`,
48
+ operation: CryptoOperationValue.pkcs12Decode,
49
+ }))
50
+ : Effect.succeed(node);
51
+ };
52
+ const concatBytes = (parts) => {
53
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
54
+ const result = new Uint8Array(total);
55
+ let offset = 0;
56
+ for (const part of parts) {
57
+ result.set(part, offset);
58
+ offset += part.length;
59
+ }
60
+ return result;
61
+ };
62
+ /** Read an OCTET STRING, concatenating BER constructed fragments. */
63
+ const readOctetString = (node) => {
64
+ if (node.tag !== 0x04) {
65
+ return Effect.fail(new CryptoError({
66
+ code: CryptoErrorCodeValue.corruptedFile,
67
+ reason: `Expected OCTET STRING, got tag ${node.tag}.`,
68
+ operation: CryptoOperationValue.pkcs12Decode,
69
+ }));
70
+ }
71
+ if (node.kind === "primitive")
72
+ return Effect.succeed(node.bytes);
73
+ return Effect.map(Effect.forEach(node.children, readOctetString), concatBytes);
74
+ };
75
+ /** Unwrap an EXPLICIT/IMPLICIT context tag. */
76
+ const unwrapContextTag = (node, expectedTag) => {
77
+ if (node.class !== "context" || node.tag !== expectedTag) {
78
+ return Effect.fail(new CryptoError({
79
+ code: CryptoErrorCodeValue.corruptedFile,
80
+ reason: `Expected context tag [${expectedTag}], got ${node.class} tag ${node.tag}.`,
81
+ operation: CryptoOperationValue.pkcs12Decode,
82
+ }));
83
+ }
84
+ if (node.kind === "constructed") {
85
+ const first = node.children[0];
86
+ return node.children.length === 1 && first !== undefined
87
+ ? Effect.succeed(first)
88
+ : Effect.succeed(node);
89
+ }
90
+ return decode(node.bytes);
91
+ };
92
+ // =============================================================================
93
+ // PKCS#12 KDF (RFC 7292 Appendix B) — pure, total
94
+ // =============================================================================
95
+ const hashBytes = (algorithm, data) => {
96
+ switch (algorithm) {
97
+ case "sha1":
98
+ return sha1(data);
99
+ case "sha256":
100
+ return sha256(data);
101
+ case "sha384":
102
+ return sha384(data);
103
+ case "sha512":
104
+ return sha512(data);
105
+ }
106
+ };
107
+ const toBmpString = (text) => {
108
+ if (text.length === 0)
109
+ return new Uint8Array([0x00, 0x00]);
110
+ const result = new Uint8Array(text.length * 2 + 2);
111
+ for (let i = 0; i < text.length; i++) {
112
+ const code = text.charCodeAt(i);
113
+ result[i * 2] = (code >>> 8) & 0xff;
114
+ result[i * 2 + 1] = code & 0xff;
115
+ }
116
+ return result;
117
+ };
118
+ const padToMultiple = (data, blockSize) => {
119
+ if (data.length === 0)
120
+ return new Uint8Array(0);
121
+ const padded = new Uint8Array(Math.ceil(data.length / blockSize) * blockSize);
122
+ for (let i = 0; i < padded.length; i++) {
123
+ padded[i] = data[i % data.length];
124
+ }
125
+ return padded;
126
+ };
127
+ const hashOutputLength = (algorithm) => algorithm === "sha1" ? 20 : algorithm === "sha256" ? 32 : algorithm === "sha384" ? 48 : 64;
128
+ const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm) => {
129
+ const v = algorithm === "sha384" || algorithm === "sha512" ? 128 : 64;
130
+ const D = new Uint8Array(v);
131
+ D.fill(purpose);
132
+ const S = padToMultiple(salt, v);
133
+ const P = padToMultiple(bmpPassword, v);
134
+ const I = new Uint8Array(S.length + P.length);
135
+ I.set(S, 0);
136
+ I.set(P, S.length);
137
+ const DI = new Uint8Array(D.length + I.length);
138
+ DI.set(D, 0);
139
+ DI.set(I, D.length);
140
+ const result = new Uint8Array(keyLen);
141
+ let resultOffset = 0;
142
+ while (resultOffset < keyLen) {
143
+ let A = hashBytes(algorithm, DI);
144
+ for (let i = 1; i < iterations; i++) {
145
+ A = hashBytes(algorithm, A);
146
+ }
147
+ const toCopy = Math.min(keyLen - resultOffset, A.length);
148
+ result.set(A.subarray(0, toCopy), resultOffset);
149
+ resultOffset += toCopy;
150
+ if (resultOffset >= keyLen)
151
+ break;
152
+ const B = padToMultiple(A, v);
153
+ for (let j = 0; j < I.length; j += v) {
154
+ let carry = 1;
155
+ for (let k = v - 1; k >= 0; k--) {
156
+ const sum = I[j + k] + B[k] + carry;
157
+ I[j + k] = sum & 0xff;
158
+ DI[D.length + j + k] = sum & 0xff;
159
+ carry = sum >>> 8;
160
+ }
161
+ }
162
+ }
163
+ return result;
164
+ };
165
+ // =============================================================================
166
+ // MAC verification
167
+ // =============================================================================
168
+ const macHashAlgorithm = (oid) => oid === OID_SHA256
169
+ ? "sha256"
170
+ : oid === OID_SHA384
171
+ ? "sha384"
172
+ : oid === OID_SHA512
173
+ ? "sha512"
174
+ : "sha1";
175
+ const constantTimeEquals = (a, b) => {
176
+ if (a.length !== b.length)
177
+ return false;
178
+ let diff = 0;
179
+ for (let i = 0; i < a.length; i++) {
180
+ diff |= a[i] ^ b[i];
181
+ }
182
+ return diff === 0;
183
+ };
184
+ const verifyMac = (macNode, authSafeData, bmpPassword) => Effect.gen(function* () {
185
+ const macFields = yield* childrenOf(macNode);
186
+ const digestInfo = yield* childrenOf(yield* elementAt(macFields, 0, "DigestInfo"));
187
+ const algorithmSeq = yield* childrenOf(yield* elementAt(digestInfo, 0, "AlgorithmIdentifier"));
188
+ const macAlgOid = yield* oidString(yield* elementAt(algorithmSeq, 0, "MAC algorithm OID"));
189
+ const expectedDigest = yield* bytesOf(yield* elementAt(digestInfo, 1, "MAC digest"));
190
+ const macSalt = yield* bytesOf(yield* elementAt(macFields, 1, "MAC salt"));
191
+ const iterations = macFields.length >= 3
192
+ ? Number(yield* integerBigInt(yield* elementAt(macFields, 2, "MAC iterations")))
193
+ : 1;
194
+ const algorithm = macHashAlgorithm(macAlgOid);
195
+ const macKey = pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm);
196
+ const computed = hmac(algorithm, macKey, authSafeData);
197
+ if (!constantTimeEquals(computed, expectedDigest)) {
198
+ return yield* Effect.fail(new CryptoError({
199
+ code: CryptoErrorCodeValue.wrongPassword,
200
+ operation: CryptoOperationValue.pkcs12Mac,
201
+ }));
202
+ }
203
+ });
204
+ // =============================================================================
205
+ // PBE decryption
206
+ // =============================================================================
207
+ const pbkdf2HashAlgorithm = (oid) => oid === OID_HMAC_SHA256
208
+ ? "sha256"
209
+ : oid === OID_HMAC_SHA384
210
+ ? "sha384"
211
+ : oid === OID_HMAC_SHA512
212
+ ? "sha512"
213
+ : "sha1";
214
+ const decryptPbes2 = (encryptedData, params, passwordBytes) => Effect.gen(function* () {
215
+ const pbes2Params = yield* childrenOf(params);
216
+ const kdfInfo = yield* childrenOf(yield* elementAt(pbes2Params, 0, "KeyDerivationFunc"));
217
+ const encScheme = yield* childrenOf(yield* elementAt(pbes2Params, 1, "EncryptionScheme"));
218
+ const kdfOid = yield* oidString(yield* elementAt(kdfInfo, 0, "KDF OID"));
219
+ if (kdfOid !== OID_PBKDF2) {
220
+ return yield* Effect.fail(new CryptoError({
221
+ code: CryptoErrorCodeValue.unsupportedAlgorithm,
222
+ reason: `Unsupported KDF: ${kdfOid}`,
223
+ operation: CryptoOperationValue.pkcs12Decode,
224
+ }));
225
+ }
226
+ const pbkdf2Params = yield* childrenOf(yield* elementAt(kdfInfo, 1, "PBKDF2-params"));
227
+ const salt = yield* bytesOf(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
228
+ const iterations = Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations")));
229
+ let prf = "sha1";
230
+ for (let i = 2; i < pbkdf2Params.length; i++) {
231
+ const param = pbkdf2Params[i];
232
+ if (param !== undefined && param.kind === "constructed" && param.tag === 0x10) {
233
+ const prfOid = yield* oidString(yield* elementAt(param.children, 0, "PRF OID"));
234
+ prf = pbkdf2HashAlgorithm(prfOid);
235
+ }
236
+ }
237
+ const encOid = yield* oidString(yield* elementAt(encScheme, 0, "encryption OID"));
238
+ const iv = yield* bytesOf(yield* elementAt(encScheme, 1, "encryption IV"));
239
+ if (encOid === OID_AES_128_CBC || encOid === OID_AES_192_CBC || encOid === OID_AES_256_CBC) {
240
+ const keyLen = encOid === OID_AES_128_CBC ? 16 : encOid === OID_AES_192_CBC ? 24 : 32;
241
+ return yield* aesCbcDecrypt(pbkdf2(prf, passwordBytes, salt, iterations, keyLen), iv, encryptedData);
242
+ }
243
+ if (encOid === OID_DES_EDE3_CBC) {
244
+ return yield* tripleDesCbcDecrypt(pbkdf2(prf, passwordBytes, salt, iterations, 24), iv, encryptedData);
245
+ }
246
+ return yield* Effect.fail(new CryptoError({
247
+ code: CryptoErrorCodeValue.unsupportedAlgorithm,
248
+ reason: `Unsupported encryption scheme: ${encOid}`,
249
+ operation: CryptoOperationValue.pkcs12Decode,
250
+ }));
251
+ });
252
+ const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, passwordBytes) => {
253
+ if (algorithmOid === OID_PBES2) {
254
+ return decryptPbes2(encryptedData, algorithmParams, passwordBytes);
255
+ }
256
+ return Effect.gen(function* () {
257
+ const params = yield* childrenOf(algorithmParams);
258
+ const salt = yield* bytesOf(yield* elementAt(params, 0, "PBE salt"));
259
+ const iterations = Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations")));
260
+ const derive = (length, purpose) => pkcs12Kdf(bmpPassword, salt, iterations, purpose, length, "sha1");
261
+ if (algorithmOid === OID_PBE_SHA_3DES) {
262
+ return yield* tripleDesCbcDecrypt(derive(24, 1), derive(8, 2), encryptedData);
263
+ }
264
+ if (algorithmOid === OID_PBE_SHA_2DES) {
265
+ // 2-key 3DES: derive 16 bytes (K1||K2) and expand to the EDE key K1||K2||K1.
266
+ const k16 = derive(16, 1);
267
+ const key24 = concatBytes([k16, k16.subarray(0, 8)]);
268
+ return yield* tripleDesCbcDecrypt(key24, derive(8, 2), encryptedData);
269
+ }
270
+ if (algorithmOid === OID_PBE_SHA_RC2_128) {
271
+ return yield* rc2CbcDecrypt(derive(16, 1), 128, derive(8, 2), encryptedData);
272
+ }
273
+ if (algorithmOid === OID_PBE_SHA_RC2_40) {
274
+ return yield* rc2CbcDecrypt(derive(5, 1), 40, derive(8, 2), encryptedData);
275
+ }
276
+ return yield* Effect.fail(new CryptoError({
277
+ code: CryptoErrorCodeValue.unsupportedAlgorithm,
278
+ reason: `Unsupported PBE algorithm: ${algorithmOid}`,
279
+ operation: CryptoOperationValue.pkcs12Decode,
280
+ }));
281
+ });
282
+ };
283
+ const decryptEncryptedData = (node, bmpPassword, passwordBytes) => Effect.gen(function* () {
284
+ const edChildren = yield* childrenOf(node);
285
+ const eci = yield* childrenOf(yield* elementAt(edChildren, 1, "EncryptedContentInfo"));
286
+ const algSeq = yield* childrenOf(yield* elementAt(eci, 1, "AlgorithmIdentifier"));
287
+ const algOid = yield* oidString(yield* elementAt(algSeq, 0, "algorithm OID"));
288
+ const algParams = yield* elementAt(algSeq, 1, "algorithm parameters");
289
+ const encryptedContentNode = yield* elementAt(eci, 2, "encrypted content");
290
+ if (encryptedContentNode.class !== "context" || encryptedContentNode.tag !== 0) {
291
+ return yield* Effect.fail(new CryptoError({
292
+ code: CryptoErrorCodeValue.corruptedFile,
293
+ reason: "Expected [0] IMPLICIT encrypted content.",
294
+ operation: CryptoOperationValue.pkcs12Decode,
295
+ }));
296
+ }
297
+ const encryptedContent = encryptedContentNode.kind === "constructed"
298
+ ? concatBytes(yield* Effect.forEach(encryptedContentNode.children, (child) => child.kind === "primitive" ? Effect.succeed(child.bytes) : readOctetString(child)))
299
+ : encryptedContentNode.bytes;
300
+ return yield* decryptPbe(encryptedContent, algOid, algParams, bmpPassword, passwordBytes).pipe(Effect.mapError((error) => error.code === CryptoErrorCodeValue.cipherError
301
+ ? new CryptoError({
302
+ code: CryptoErrorCodeValue.wrongPassword,
303
+ operation: CryptoOperationValue.pkcs12Decrypt,
304
+ })
305
+ : error));
306
+ });
307
+ const bytesToHex = (bytes) => {
308
+ let output = "";
309
+ for (const byte of bytes)
310
+ output += byte.toString(16).padStart(2, "0");
311
+ return output;
312
+ };
313
+ /** Read the localKeyId (OID 1.2.840.113549.1.9.21) from a SafeBag's bagAttributes. */
314
+ const readLocalKeyId = (bagFields) => Effect.gen(function* () {
315
+ const attributesNode = bagFields[2];
316
+ if (attributesNode === undefined || attributesNode.kind !== "constructed")
317
+ return null;
318
+ for (const attribute of attributesNode.children) {
319
+ if (attribute.kind !== "constructed")
320
+ continue;
321
+ const attrId = yield* oidString(yield* elementAt(attribute.children, 0, "attrId"));
322
+ if (attrId !== OID_LOCAL_KEY_ID)
323
+ continue;
324
+ const valuesNode = attribute.children[1];
325
+ if (valuesNode === undefined || valuesNode.kind !== "constructed")
326
+ continue;
327
+ const valueNode = valuesNode.children[0];
328
+ if (valueNode === undefined)
329
+ continue;
330
+ return bytesToHex(yield* bytesOf(valueNode));
331
+ }
332
+ return null;
333
+ });
334
+ const extractCertFromBag = (certBagNode) => Effect.gen(function* () {
335
+ const fields = yield* childrenOf(certBagNode);
336
+ const certId = yield* oidString(yield* elementAt(fields, 0, "certId"));
337
+ if (certId !== OID_X509_CERT)
338
+ return [];
339
+ const certValue = yield* unwrapContextTag(yield* elementAt(fields, 1, "certValue"), 0);
340
+ return [yield* readOctetString(certValue)];
341
+ });
342
+ const parseSafeBags = (safeContents) => Effect.gen(function* () {
343
+ const children = yield* childrenOf(safeContents);
344
+ const bags = [];
345
+ for (const bagNode of children) {
346
+ const bagFields = yield* childrenOf(bagNode);
347
+ const bagId = yield* oidString(yield* elementAt(bagFields, 0, "bagId"));
348
+ const bagValue = yield* unwrapContextTag(yield* elementAt(bagFields, 1, "bagValue"), 0);
349
+ const localKeyId = yield* readLocalKeyId(bagFields);
350
+ if (bagId === OID_CERT_BAG) {
351
+ const certs = yield* extractCertFromBag(bagValue);
352
+ for (const cert of certs)
353
+ bags.push({ kind: "cert", data: cert, localKeyId });
354
+ }
355
+ else if (bagId === OID_PKCS8_SHROUDED_KEY_BAG) {
356
+ bags.push({ kind: "key", data: encode(bagValue), localKeyId });
357
+ }
358
+ }
359
+ return bags;
360
+ });
361
+ const decryptShroudedKeyBag = (encryptedKeyInfoDer, bmpPassword, passwordBytes) => Effect.gen(function* () {
362
+ const node = yield* decode(encryptedKeyInfoDer);
363
+ const fields = yield* childrenOf(node);
364
+ const algSeq = yield* childrenOf(yield* elementAt(fields, 0, "AlgorithmIdentifier"));
365
+ const algOid = yield* oidString(yield* elementAt(algSeq, 0, "algorithm OID"));
366
+ const algParams = yield* elementAt(algSeq, 1, "algorithm parameters");
367
+ const encryptedData = yield* bytesOf(yield* elementAt(fields, 1, "encrypted key"));
368
+ const pkcs8 = yield* decryptPbe(encryptedData, algOid, algParams, bmpPassword, passwordBytes).pipe(Effect.mapError((error) => error.code === CryptoErrorCodeValue.cipherError
369
+ ? new CryptoError({
370
+ code: CryptoErrorCodeValue.wrongPassword,
371
+ operation: CryptoOperationValue.pkcs12Decrypt,
372
+ })
373
+ : error));
374
+ if (pkcs8[0] !== 0x30) {
375
+ return yield* Effect.fail(new CryptoError({
376
+ code: CryptoErrorCodeValue.wrongPassword,
377
+ reason: "Decrypted private key is not valid PKCS#8.",
378
+ operation: CryptoOperationValue.pkcs12Decode,
379
+ }));
380
+ }
381
+ return pkcs8;
382
+ });
383
+ // =============================================================================
384
+ // Public API
385
+ // =============================================================================
386
+ /** Parse a `.pfx`/`.p12` container, returning DER certificate + private key. */
387
+ export const parsePkcs12 = (data, password) => Effect.gen(function* () {
388
+ const phrase = Redacted.value(password);
389
+ const bmpPassword = toBmpString(phrase);
390
+ const passwordBytes = new TextEncoder().encode(phrase);
391
+ const pfx = yield* decode(data);
392
+ const pfxChildren = yield* childrenOf(pfx);
393
+ const version = yield* integerBigInt(yield* elementAt(pfxChildren, 0, "PFX version"));
394
+ if (version !== 3n) {
395
+ return yield* Effect.fail(new CryptoError({
396
+ code: CryptoErrorCodeValue.invalidFormat,
397
+ reason: `Unsupported PFX version: ${version}.`,
398
+ operation: CryptoOperationValue.pkcs12Decode,
399
+ }));
400
+ }
401
+ const authSafe = yield* childrenOf(yield* elementAt(pfxChildren, 1, "authSafe ContentInfo"));
402
+ const authSafeOid = yield* oidString(yield* elementAt(authSafe, 0, "authSafe OID"));
403
+ if (authSafeOid !== OID_DATA) {
404
+ return yield* Effect.fail(new CryptoError({
405
+ code: CryptoErrorCodeValue.invalidFormat,
406
+ reason: `Expected data ContentInfo in authSafe, got ${authSafeOid}.`,
407
+ operation: CryptoOperationValue.pkcs12Decode,
408
+ }));
409
+ }
410
+ const authSafeContent = yield* unwrapContextTag(yield* elementAt(authSafe, 1, "authSafe content"), 0);
411
+ const authSafeData = yield* readOctetString(authSafeContent);
412
+ if (pfxChildren.length >= 3) {
413
+ yield* verifyMac(yield* elementAt(pfxChildren, 2, "MacData"), authSafeData, bmpPassword);
414
+ }
415
+ const safeContents = yield* childrenOf(yield* decode(authSafeData));
416
+ const certificates = [];
417
+ const keyBags = [];
418
+ for (const contentInfo of safeContents) {
419
+ const ciChildren = yield* childrenOf(contentInfo);
420
+ const ciOid = yield* oidString(yield* elementAt(ciChildren, 0, "ContentInfo OID"));
421
+ const safeBagsDer = ciOid === OID_DATA
422
+ ? yield* readOctetString(yield* unwrapContextTag(yield* elementAt(ciChildren, 1, "SafeContents"), 0))
423
+ : ciOid === OID_ENCRYPTED_DATA
424
+ ? yield* decryptEncryptedData(yield* unwrapContextTag(yield* elementAt(ciChildren, 1, "EncryptedData"), 0), bmpPassword, passwordBytes)
425
+ : undefined;
426
+ if (safeBagsDer === undefined)
427
+ continue;
428
+ const bags = yield* parseSafeBags(yield* decode(safeBagsDer));
429
+ for (const bag of bags) {
430
+ if (bag.kind === "cert")
431
+ certificates.push({ data: bag.data, localKeyId: bag.localKeyId });
432
+ else
433
+ keyBags.push({ data: bag.data, localKeyId: bag.localKeyId });
434
+ }
435
+ }
436
+ const firstCert = certificates[0];
437
+ if (firstCert === undefined) {
438
+ return yield* Effect.fail(new CryptoError({
439
+ code: CryptoErrorCodeValue.noCertificate,
440
+ reason: "No certificate in PKCS#12.",
441
+ operation: CryptoOperationValue.pkcs12Decode,
442
+ }));
443
+ }
444
+ const keyBag = keyBags[0];
445
+ if (keyBag === undefined) {
446
+ return yield* Effect.fail(new CryptoError({
447
+ code: CryptoErrorCodeValue.noPrivateKey,
448
+ reason: "No private key in PKCS#12.",
449
+ operation: CryptoOperationValue.pkcs12Decode,
450
+ }));
451
+ }
452
+ const privateKey = yield* decryptShroudedKeyBag(keyBag.data, bmpPassword, passwordBytes);
453
+ // Pair the end-entity to the key by localKeyId (RFC 7292); the chain is the rest.
454
+ // Fall back to the first cert when no localKeyId is present (the common leaf-first case).
455
+ const matched = keyBag.localKeyId === null
456
+ ? undefined
457
+ : certificates.find((entry) => entry.localKeyId === keyBag.localKeyId);
458
+ const endEntity = matched ?? firstCert;
459
+ const chain = certificates.filter((entry) => entry !== endEntity).map((entry) => entry.data);
460
+ return {
461
+ certificate: endEntity.data,
462
+ privateKey,
463
+ chain,
464
+ };
465
+ }).pipe(Effect.mapError((error) => error._tag === "Asn1Error"
466
+ ? new CryptoError({
467
+ code: CryptoErrorCodeValue.decodeError,
468
+ reason: error.reason ?? error.message,
469
+ operation: CryptoOperationValue.pkcs12Decode,
470
+ })
471
+ : error));
@@ -0,0 +1,17 @@
1
+ /**
2
+ * AES-CBC pure TypeScript implementation (FIPS 197).
3
+ *
4
+ * Supports AES-128, AES-192, and AES-256 in CBC mode with PKCS#7 padding.
5
+ * Zero runtime dependencies. Works in any JS environment.
6
+ */
7
+ import { Effect } from "effect";
8
+ import { CryptoError } from "../config";
9
+ /**
10
+ * Decrypt data encrypted with AES-CBC + PKCS#7 padding.
11
+ *
12
+ * @param key - 16, 24, or 32 bytes
13
+ * @param iv - 16 bytes
14
+ * @param ciphertext - Must be a multiple of 16 bytes
15
+ */
16
+ export declare const aesCbcDecrypt: (key: Uint8Array, iv: Uint8Array, ciphertext: Uint8Array) => Effect.Effect<Uint8Array, CryptoError>;
17
+ //# sourceMappingURL=aes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aes.d.ts","sourceRoot":"","sources":["../../src/primitives/aes.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,WAAW,EAA8C,MAAM,WAAW,CAAC;AAsMpF;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,GACxB,KAAK,UAAU,EACf,IAAI,UAAU,EACd,YAAY,UAAU,KACrB,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CA8BvC,CAAC"}