@signature-kit/crypto 0.2.1 → 0.2.3

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 (41) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/base64.d.ts +1 -1
  3. package/dist/base64.d.ts.map +1 -1
  4. package/dist/base64.js +15 -14
  5. package/dist/config.d.ts +3 -7
  6. package/dist/config.d.ts.map +1 -1
  7. package/dist/config.js +1 -7
  8. package/dist/pem.d.ts +1 -1
  9. package/dist/pem.d.ts.map +1 -1
  10. package/dist/pem.js +14 -8
  11. package/dist/pkcs12.d.ts +2 -10
  12. package/dist/pkcs12.d.ts.map +1 -1
  13. package/dist/pkcs12.js +368 -124
  14. package/dist/primitives/aes.d.ts +1 -14
  15. package/dist/primitives/aes.d.ts.map +1 -1
  16. package/dist/primitives/aes.js +8 -47
  17. package/dist/primitives/des.d.ts +1 -20
  18. package/dist/primitives/des.d.ts.map +1 -1
  19. package/dist/primitives/des.js +6 -67
  20. package/dist/primitives/hmac.d.ts +0 -30
  21. package/dist/primitives/hmac.d.ts.map +1 -1
  22. package/dist/primitives/hmac.js +4 -46
  23. package/dist/primitives/padding.d.ts +1 -8
  24. package/dist/primitives/padding.d.ts.map +1 -1
  25. package/dist/primitives/padding.js +2 -11
  26. package/dist/primitives/pbkdf2.d.ts +1 -17
  27. package/dist/primitives/pbkdf2.d.ts.map +1 -1
  28. package/dist/primitives/pbkdf2.js +8 -30
  29. package/dist/primitives/rc2.d.ts +1 -20
  30. package/dist/primitives/rc2.d.ts.map +1 -1
  31. package/dist/primitives/rc2.js +11 -69
  32. package/dist/primitives/sha1.d.ts +0 -13
  33. package/dist/primitives/sha1.d.ts.map +1 -1
  34. package/dist/primitives/sha1.js +1 -28
  35. package/dist/primitives/sha256.d.ts +0 -26
  36. package/dist/primitives/sha256.d.ts.map +1 -1
  37. package/dist/primitives/sha256.js +0 -34
  38. package/dist/primitives/sha512.d.ts +0 -19
  39. package/dist/primitives/sha512.d.ts.map +1 -1
  40. package/dist/primitives/sha512.js +1 -32
  41. package/package.json +7 -5
package/dist/pkcs12.js CHANGED
@@ -1,22 +1,13 @@
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";
1
+ import { childrenOf, decode, encode, integerBigInt, oidString, } from "@signature-kit/asn1";
10
2
  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";
3
+ import { CryptoError, CryptoErrorCodeValue, CryptoOperationValue } from "./config.js";
4
+ import { createHmac, hmac } from "./primitives/hmac.js";
5
+ import { sha1 } from "./primitives/sha1.js";
6
+ import { sha256 } from "./primitives/sha256.js";
7
+ import { sha384, sha512 } from "./primitives/sha512.js";
8
+ import { aesCbcDecrypt } from "./primitives/aes.js";
9
+ import { tripleDesCbcDecrypt } from "./primitives/des.js";
10
+ import { rc2CbcDecrypt } from "./primitives/rc2.js";
20
11
  const OID_DATA = "1.2.840.113549.1.7.1";
21
12
  const OID_ENCRYPTED_DATA = "1.2.840.113549.1.7.6";
22
13
  const OID_CERT_BAG = "1.2.840.113549.1.12.10.1.3";
@@ -37,13 +28,14 @@ const OID_HMAC_SHA1 = "1.2.840.113549.2.7";
37
28
  const OID_HMAC_SHA256 = "1.2.840.113549.2.9";
38
29
  const OID_HMAC_SHA384 = "1.2.840.113549.2.10";
39
30
  const OID_HMAC_SHA512 = "1.2.840.113549.2.11";
31
+ const OID_SHA1 = "1.3.14.3.2.26";
40
32
  const OID_SHA256 = "2.16.840.1.101.3.4.2.1";
41
33
  const OID_SHA384 = "2.16.840.1.101.3.4.2.2";
42
34
  const OID_SHA512 = "2.16.840.1.101.3.4.2.3";
43
- // Iteration counts come from the (attacker-controlled) file; the KDFs run in
44
- // pure JS, so an unbounded count pins the event loop before the password is
45
- // even checked. OpenSSL defaults to 2048; 10M gives generous headroom.
46
35
  const MAX_KDF_ITERATIONS = 10_000_000;
36
+ const MAX_KDF_WORK = 10_000_000;
37
+ const KDF_YIELD_INTERVAL = 1_024;
38
+ const kdfYield = Effect.sleep("0 millis");
47
39
  const boundedIterations = (iterations, label) => Number.isSafeInteger(iterations) && iterations >= 1 && iterations <= MAX_KDF_ITERATIONS
48
40
  ? Effect.succeed(iterations)
49
41
  : Effect.fail(new CryptoError({
@@ -71,12 +63,11 @@ const concatBytes = (parts) => {
71
63
  }
72
64
  return result;
73
65
  };
74
- /** Read an OCTET STRING, concatenating BER constructed fragments. */
75
66
  const readOctetString = (node) => {
76
- if (node.tag !== 0x04) {
67
+ if (node.class !== "universal" || node.tag !== 0x04) {
77
68
  return Effect.fail(new CryptoError({
78
69
  code: CryptoErrorCodeValue.corruptedFile,
79
- reason: `Expected OCTET STRING, got tag ${node.tag}.`,
70
+ reason: `Expected universal OCTET STRING, got ${node.class} tag ${node.tag}.`,
80
71
  operation: CryptoOperationValue.pkcs12Decode,
81
72
  }));
82
73
  }
@@ -84,7 +75,6 @@ const readOctetString = (node) => {
84
75
  return Effect.succeed(node.bytes);
85
76
  return Effect.map(Effect.forEach(node.children, readOctetString), concatBytes);
86
77
  };
87
- /** Unwrap an EXPLICIT/IMPLICIT context tag. */
88
78
  const unwrapContextTag = (node, expectedTag) => {
89
79
  if (node.class !== "context" || node.tag !== expectedTag) {
90
80
  return Effect.fail(new CryptoError({
@@ -101,9 +91,6 @@ const unwrapContextTag = (node, expectedTag) => {
101
91
  }
102
92
  return decode(node.bytes);
103
93
  };
104
- // =============================================================================
105
- // PKCS#12 KDF (RFC 7292 Appendix B) — pure, total
106
- // =============================================================================
107
94
  const hashBytes = (algorithm, data) => {
108
95
  switch (algorithm) {
109
96
  case "sha1":
@@ -137,7 +124,21 @@ const padToMultiple = (data, blockSize) => {
137
124
  return padded;
138
125
  };
139
126
  const hashOutputLength = (algorithm) => algorithm === "sha1" ? 20 : algorithm === "sha256" ? 32 : algorithm === "sha384" ? 48 : 64;
140
- const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm) => {
127
+ const consumeKdfWork = (budget, label, iterations, blocks) => {
128
+ const work = iterations * blocks;
129
+ if (!Number.isSafeInteger(work) || work > budget.remaining) {
130
+ return Effect.fail(new CryptoError({
131
+ code: CryptoErrorCodeValue.corruptedFile,
132
+ reason: `PKCS#12 KDF work budget exceeded for ${label}: ${work} operations.`,
133
+ operation: CryptoOperationValue.pkcs12Decode,
134
+ }));
135
+ }
136
+ budget.remaining -= work;
137
+ return Effect.void;
138
+ };
139
+ const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm, budget) => Effect.gen(function* () {
140
+ const hashLength = hashOutputLength(algorithm);
141
+ yield* consumeKdfWork(budget, "PKCS#12", iterations, Math.ceil(keyLen / hashLength));
141
142
  const v = algorithm === "sha384" || algorithm === "sha512" ? 128 : 64;
142
143
  const D = new Uint8Array(v);
143
144
  D.fill(purpose);
@@ -151,10 +152,21 @@ const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm) =>
151
152
  DI.set(I, D.length);
152
153
  const result = new Uint8Array(keyLen);
153
154
  let resultOffset = 0;
155
+ let hashesSinceYield = 0;
154
156
  while (resultOffset < keyLen) {
155
157
  let A = hashBytes(algorithm, DI);
158
+ hashesSinceYield++;
159
+ if (hashesSinceYield === KDF_YIELD_INTERVAL) {
160
+ yield* kdfYield;
161
+ hashesSinceYield = 0;
162
+ }
156
163
  for (let i = 1; i < iterations; i++) {
157
164
  A = hashBytes(algorithm, A);
165
+ hashesSinceYield++;
166
+ if (hashesSinceYield === KDF_YIELD_INTERVAL) {
167
+ yield* kdfYield;
168
+ hashesSinceYield = 0;
169
+ }
158
170
  }
159
171
  const toCopy = Math.min(keyLen - resultOffset, A.length);
160
172
  result.set(A.subarray(0, toCopy), resultOffset);
@@ -173,17 +185,58 @@ const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm) =>
173
185
  }
174
186
  }
175
187
  return result;
188
+ });
189
+ const pbkdf2Kdf = (prf, password, salt, iterations, keyLength, budget) => Effect.gen(function* () {
190
+ const hashLength = hashOutputLength(prf);
191
+ const blockCount = Math.ceil(keyLength / hashLength);
192
+ yield* consumeKdfWork(budget, "PBKDF2", iterations, blockCount);
193
+ const hmacContext = createHmac(prf, password);
194
+ const derivedKey = new Uint8Array(keyLength);
195
+ let hashesSinceYield = 0;
196
+ for (let blockIndex = 1; blockIndex <= blockCount; blockIndex++) {
197
+ const saltWithIndex = new Uint8Array(salt.length + 4);
198
+ saltWithIndex.set(salt);
199
+ saltWithIndex[salt.length] = (blockIndex >>> 24) & 0xff;
200
+ saltWithIndex[salt.length + 1] = (blockIndex >>> 16) & 0xff;
201
+ saltWithIndex[salt.length + 2] = (blockIndex >>> 8) & 0xff;
202
+ saltWithIndex[salt.length + 3] = blockIndex & 0xff;
203
+ let u = hmacContext.compute(saltWithIndex);
204
+ const block = new Uint8Array(u);
205
+ hashesSinceYield++;
206
+ if (hashesSinceYield === KDF_YIELD_INTERVAL) {
207
+ yield* kdfYield;
208
+ hashesSinceYield = 0;
209
+ }
210
+ for (let iteration = 1; iteration < iterations; iteration++) {
211
+ u = hmacContext.compute(u);
212
+ for (let j = 0; j < hashLength; j++)
213
+ block[j] ^= u[j];
214
+ hashesSinceYield++;
215
+ if (hashesSinceYield === KDF_YIELD_INTERVAL) {
216
+ yield* kdfYield;
217
+ hashesSinceYield = 0;
218
+ }
219
+ }
220
+ const offset = (blockIndex - 1) * hashLength;
221
+ derivedKey.set(block.subarray(0, Math.min(hashLength, keyLength - offset)), offset);
222
+ }
223
+ return derivedKey;
224
+ });
225
+ const macHashAlgorithm = (oid) => {
226
+ if (oid === OID_SHA1)
227
+ return Effect.succeed("sha1");
228
+ if (oid === OID_SHA256)
229
+ return Effect.succeed("sha256");
230
+ if (oid === OID_SHA384)
231
+ return Effect.succeed("sha384");
232
+ if (oid === OID_SHA512)
233
+ return Effect.succeed("sha512");
234
+ return Effect.fail(new CryptoError({
235
+ code: CryptoErrorCodeValue.unsupportedAlgorithm,
236
+ reason: `Unsupported PKCS#12 MAC hash: ${oid}`,
237
+ operation: CryptoOperationValue.pkcs12Decode,
238
+ }));
176
239
  };
177
- // =============================================================================
178
- // MAC verification
179
- // =============================================================================
180
- const macHashAlgorithm = (oid) => oid === OID_SHA256
181
- ? "sha256"
182
- : oid === OID_SHA384
183
- ? "sha384"
184
- : oid === OID_SHA512
185
- ? "sha512"
186
- : "sha1";
187
240
  const constantTimeEquals = (a, b) => {
188
241
  if (a.length !== b.length)
189
242
  return false;
@@ -193,29 +246,26 @@ const constantTimeEquals = (a, b) => {
193
246
  }
194
247
  return diff === 0;
195
248
  };
196
- const verifyMac = (macNode, authSafeData, bmpPassword) => Effect.gen(function* () {
249
+ const verifyMac = (macNode, authSafeData, bmpPassword, budget) => Effect.gen(function* () {
197
250
  const macFields = yield* childrenOf(macNode);
198
251
  const digestInfo = yield* childrenOf(yield* elementAt(macFields, 0, "DigestInfo"));
199
252
  const algorithmSeq = yield* childrenOf(yield* elementAt(digestInfo, 0, "AlgorithmIdentifier"));
200
253
  const macAlgOid = yield* oidString(yield* elementAt(algorithmSeq, 0, "MAC algorithm OID"));
201
- const expectedDigest = yield* bytesOf(yield* elementAt(digestInfo, 1, "MAC digest"));
202
- const macSalt = yield* bytesOf(yield* elementAt(macFields, 1, "MAC salt"));
254
+ const expectedDigest = yield* readOctetString(yield* elementAt(digestInfo, 1, "MAC digest"));
255
+ const macSalt = yield* readOctetString(yield* elementAt(macFields, 1, "MAC salt"));
256
+ const algorithm = yield* macHashAlgorithm(macAlgOid);
203
257
  const iterations = yield* boundedIterations(macFields.length >= 3
204
258
  ? Number(yield* integerBigInt(yield* elementAt(macFields, 2, "MAC iterations")))
205
259
  : 1, "MAC");
206
- const algorithm = macHashAlgorithm(macAlgOid);
207
- const macKey = pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm);
260
+ const macKey = yield* pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm, budget);
208
261
  const computed = hmac(algorithm, macKey, authSafeData);
209
262
  if (!constantTimeEquals(computed, expectedDigest)) {
210
- return yield* Effect.fail(new CryptoError({
263
+ return yield* new CryptoError({
211
264
  code: CryptoErrorCodeValue.wrongPassword,
212
265
  operation: CryptoOperationValue.pkcs12Mac,
213
- }));
266
+ });
214
267
  }
215
268
  });
216
- // =============================================================================
217
- // PBE decryption
218
- // =============================================================================
219
269
  const pbkdf2HashAlgorithm = (oid) => {
220
270
  if (oid === OID_HMAC_SHA1)
221
271
  return Effect.succeed("sha1");
@@ -231,76 +281,112 @@ const pbkdf2HashAlgorithm = (oid) => {
231
281
  operation: CryptoOperationValue.pkcs12Decode,
232
282
  }));
233
283
  };
234
- const decryptPbes2 = (encryptedData, params, passwordBytes) => Effect.gen(function* () {
284
+ const validateCbcParameters = (algorithm, ivLength, ciphertext, blockSize) => {
285
+ if (ivLength !== blockSize) {
286
+ return Effect.fail(new CryptoError({
287
+ code: CryptoErrorCodeValue.corruptedFile,
288
+ reason: `Invalid ${algorithm} IV length: expected ${blockSize} bytes, got ${ivLength}.`,
289
+ operation: CryptoOperationValue.pkcs12Decode,
290
+ }));
291
+ }
292
+ if (ciphertext.length === 0 || ciphertext.length % blockSize !== 0) {
293
+ return Effect.fail(new CryptoError({
294
+ code: CryptoErrorCodeValue.corruptedFile,
295
+ reason: `Invalid ${algorithm} ciphertext length: ${ciphertext.length}.`,
296
+ operation: CryptoOperationValue.pkcs12Decode,
297
+ }));
298
+ }
299
+ return Effect.void;
300
+ };
301
+ const decryptPbes2 = (encryptedData, params, passwordBytes, budget) => Effect.gen(function* () {
235
302
  const pbes2Params = yield* childrenOf(params);
236
303
  const kdfInfo = yield* childrenOf(yield* elementAt(pbes2Params, 0, "KeyDerivationFunc"));
237
304
  const encScheme = yield* childrenOf(yield* elementAt(pbes2Params, 1, "EncryptionScheme"));
238
305
  const kdfOid = yield* oidString(yield* elementAt(kdfInfo, 0, "KDF OID"));
239
306
  if (kdfOid !== OID_PBKDF2) {
240
- return yield* Effect.fail(new CryptoError({
307
+ return yield* new CryptoError({
241
308
  code: CryptoErrorCodeValue.unsupportedAlgorithm,
242
309
  reason: `Unsupported KDF: ${kdfOid}`,
243
310
  operation: CryptoOperationValue.pkcs12Decode,
244
- }));
311
+ });
245
312
  }
246
313
  const pbkdf2Params = yield* childrenOf(yield* elementAt(kdfInfo, 1, "PBKDF2-params"));
247
- const salt = yield* bytesOf(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
314
+ const salt = yield* readOctetString(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
248
315
  const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations"))), "PBKDF2");
249
316
  let prf = "sha1";
250
317
  for (let i = 2; i < pbkdf2Params.length; i++) {
251
318
  const param = pbkdf2Params[i];
252
- if (param !== undefined && param.kind === "constructed" && param.tag === 0x10) {
319
+ if (param !== undefined &&
320
+ param.class === "universal" &&
321
+ param.kind === "constructed" &&
322
+ param.tag === 0x10) {
253
323
  const prfOid = yield* oidString(yield* elementAt(param.children, 0, "PRF OID"));
254
324
  prf = yield* pbkdf2HashAlgorithm(prfOid);
255
325
  }
256
326
  }
257
327
  const encOid = yield* oidString(yield* elementAt(encScheme, 0, "encryption OID"));
258
- const iv = yield* bytesOf(yield* elementAt(encScheme, 1, "encryption IV"));
328
+ const iv = yield* readOctetString(yield* elementAt(encScheme, 1, "encryption IV"));
259
329
  if (encOid === OID_AES_128_CBC || encOid === OID_AES_192_CBC || encOid === OID_AES_256_CBC) {
260
- const keyLen = encOid === OID_AES_128_CBC ? 16 : encOid === OID_AES_192_CBC ? 24 : 32;
261
- return yield* aesCbcDecrypt(pbkdf2(prf, passwordBytes, salt, iterations, keyLen), iv, encryptedData);
330
+ const keyLength = encOid === OID_AES_128_CBC ? 16 : encOid === OID_AES_192_CBC ? 24 : 32;
331
+ yield* validateCbcParameters("AES-CBC", iv.length, encryptedData, 16);
332
+ const key = yield* pbkdf2Kdf(prf, passwordBytes, salt, iterations, keyLength, budget);
333
+ return yield* aesCbcDecrypt(key, iv, encryptedData);
262
334
  }
263
335
  if (encOid === OID_DES_EDE3_CBC) {
264
- return yield* tripleDesCbcDecrypt(pbkdf2(prf, passwordBytes, salt, iterations, 24), iv, encryptedData);
336
+ yield* validateCbcParameters("3DES-CBC", iv.length, encryptedData, 8);
337
+ const key = yield* pbkdf2Kdf(prf, passwordBytes, salt, iterations, 24, budget);
338
+ return yield* tripleDesCbcDecrypt(key, iv, encryptedData);
265
339
  }
266
- return yield* Effect.fail(new CryptoError({
340
+ return yield* new CryptoError({
267
341
  code: CryptoErrorCodeValue.unsupportedAlgorithm,
268
342
  reason: `Unsupported encryption scheme: ${encOid}`,
269
343
  operation: CryptoOperationValue.pkcs12Decode,
270
- }));
344
+ });
271
345
  });
272
- const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, passwordBytes) => {
346
+ const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, passwordBytes, budget) => {
273
347
  if (algorithmOid === OID_PBES2) {
274
- return decryptPbes2(encryptedData, algorithmParams, passwordBytes);
348
+ return decryptPbes2(encryptedData, algorithmParams, passwordBytes, budget);
349
+ }
350
+ if (algorithmOid !== OID_PBE_SHA_3DES &&
351
+ algorithmOid !== OID_PBE_SHA_2DES &&
352
+ algorithmOid !== OID_PBE_SHA_RC2_128 &&
353
+ algorithmOid !== OID_PBE_SHA_RC2_40) {
354
+ return Effect.fail(new CryptoError({
355
+ code: CryptoErrorCodeValue.unsupportedAlgorithm,
356
+ reason: `Unsupported PBE algorithm: ${algorithmOid}`,
357
+ operation: CryptoOperationValue.pkcs12Decode,
358
+ }));
275
359
  }
276
360
  return Effect.gen(function* () {
277
361
  const params = yield* childrenOf(algorithmParams);
278
- const salt = yield* bytesOf(yield* elementAt(params, 0, "PBE salt"));
362
+ const salt = yield* readOctetString(yield* elementAt(params, 0, "PBE salt"));
279
363
  const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations"))), "PBE");
280
- const derive = (length, purpose) => pkcs12Kdf(bmpPassword, salt, iterations, purpose, length, "sha1");
281
364
  if (algorithmOid === OID_PBE_SHA_3DES) {
282
- return yield* tripleDesCbcDecrypt(derive(24, 1), derive(8, 2), encryptedData);
365
+ yield* validateCbcParameters("3DES-CBC", 8, encryptedData, 8);
366
+ const key = yield* pkcs12Kdf(bmpPassword, salt, iterations, 1, 24, "sha1", budget);
367
+ const iv = yield* pkcs12Kdf(bmpPassword, salt, iterations, 2, 8, "sha1", budget);
368
+ return yield* tripleDesCbcDecrypt(key, iv, encryptedData);
283
369
  }
284
370
  if (algorithmOid === OID_PBE_SHA_2DES) {
285
- // 2-key 3DES: derive 16 bytes (K1||K2) and expand to the EDE key K1||K2||K1.
286
- const k16 = derive(16, 1);
287
- const key24 = concatBytes([k16, k16.subarray(0, 8)]);
288
- return yield* tripleDesCbcDecrypt(key24, derive(8, 2), encryptedData);
371
+ yield* validateCbcParameters("3DES-CBC", 8, encryptedData, 8);
372
+ const key16 = yield* pkcs12Kdf(bmpPassword, salt, iterations, 1, 16, "sha1", budget);
373
+ const key = concatBytes([key16, key16.subarray(0, 8)]);
374
+ const iv = yield* pkcs12Kdf(bmpPassword, salt, iterations, 2, 8, "sha1", budget);
375
+ return yield* tripleDesCbcDecrypt(key, iv, encryptedData);
289
376
  }
290
377
  if (algorithmOid === OID_PBE_SHA_RC2_128) {
291
- return yield* rc2CbcDecrypt(derive(16, 1), 128, derive(8, 2), encryptedData);
292
- }
293
- if (algorithmOid === OID_PBE_SHA_RC2_40) {
294
- return yield* rc2CbcDecrypt(derive(5, 1), 40, derive(8, 2), encryptedData);
378
+ yield* validateCbcParameters("RC2-CBC", 8, encryptedData, 8);
379
+ const key = yield* pkcs12Kdf(bmpPassword, salt, iterations, 1, 16, "sha1", budget);
380
+ const iv = yield* pkcs12Kdf(bmpPassword, salt, iterations, 2, 8, "sha1", budget);
381
+ return yield* rc2CbcDecrypt(key, 128, iv, encryptedData);
295
382
  }
296
- return yield* Effect.fail(new CryptoError({
297
- code: CryptoErrorCodeValue.unsupportedAlgorithm,
298
- reason: `Unsupported PBE algorithm: ${algorithmOid}`,
299
- operation: CryptoOperationValue.pkcs12Decode,
300
- }));
383
+ yield* validateCbcParameters("RC2-CBC", 8, encryptedData, 8);
384
+ const key = yield* pkcs12Kdf(bmpPassword, salt, iterations, 1, 5, "sha1", budget);
385
+ const iv = yield* pkcs12Kdf(bmpPassword, salt, iterations, 2, 8, "sha1", budget);
386
+ return yield* rc2CbcDecrypt(key, 40, iv, encryptedData);
301
387
  });
302
388
  };
303
- const decryptEncryptedData = (node, bmpPassword, passwordBytes) => Effect.gen(function* () {
389
+ const decryptEncryptedData = (node, bmpPassword, passwordBytes, budget) => Effect.gen(function* () {
304
390
  const edChildren = yield* childrenOf(node);
305
391
  const eci = yield* childrenOf(yield* elementAt(edChildren, 1, "EncryptedContentInfo"));
306
392
  const algSeq = yield* childrenOf(yield* elementAt(eci, 1, "AlgorithmIdentifier"));
@@ -308,16 +394,16 @@ const decryptEncryptedData = (node, bmpPassword, passwordBytes) => Effect.gen(fu
308
394
  const algParams = yield* elementAt(algSeq, 1, "algorithm parameters");
309
395
  const encryptedContentNode = yield* elementAt(eci, 2, "encrypted content");
310
396
  if (encryptedContentNode.class !== "context" || encryptedContentNode.tag !== 0) {
311
- return yield* Effect.fail(new CryptoError({
397
+ return yield* new CryptoError({
312
398
  code: CryptoErrorCodeValue.corruptedFile,
313
399
  reason: "Expected [0] IMPLICIT encrypted content.",
314
400
  operation: CryptoOperationValue.pkcs12Decode,
315
- }));
401
+ });
316
402
  }
317
403
  const encryptedContent = encryptedContentNode.kind === "constructed"
318
- ? concatBytes(yield* Effect.forEach(encryptedContentNode.children, (child) => child.kind === "primitive" ? Effect.succeed(child.bytes) : readOctetString(child)))
404
+ ? concatBytes(yield* Effect.forEach(encryptedContentNode.children, readOctetString))
319
405
  : encryptedContentNode.bytes;
320
- return yield* decryptPbe(encryptedContent, algOid, algParams, bmpPassword, passwordBytes).pipe(Effect.mapError((error) => error.code === CryptoErrorCodeValue.cipherError
406
+ return yield* decryptPbe(encryptedContent, algOid, algParams, bmpPassword, passwordBytes, budget).pipe(Effect.mapError((error) => error.code === CryptoErrorCodeValue.cipherError
321
407
  ? new CryptoError({
322
408
  code: CryptoErrorCodeValue.wrongPassword,
323
409
  operation: CryptoOperationValue.pkcs12Decrypt,
@@ -330,11 +416,19 @@ const bytesToHex = (bytes) => {
330
416
  output += byte.toString(16).padStart(2, "0");
331
417
  return output;
332
418
  };
333
- /** Read the localKeyId (OID 1.2.840.113549.1.9.21) from a SafeBag's bagAttributes. */
334
419
  const readLocalKeyId = (bagFields) => Effect.gen(function* () {
335
420
  const attributesNode = bagFields[2];
336
- if (attributesNode === undefined || attributesNode.kind !== "constructed")
421
+ if (attributesNode === undefined)
337
422
  return null;
423
+ if (attributesNode.kind !== "constructed") {
424
+ return yield* new CryptoError({
425
+ code: CryptoErrorCodeValue.corruptedFile,
426
+ reason: "PKCS#12 bag attributes are not constructed.",
427
+ operation: CryptoOperationValue.pkcs12Decode,
428
+ });
429
+ }
430
+ let localKeyId = null;
431
+ let hasLocalKeyId = false;
338
432
  for (const attribute of attributesNode.children) {
339
433
  if (attribute.kind !== "constructed")
340
434
  continue;
@@ -342,14 +436,34 @@ const readLocalKeyId = (bagFields) => Effect.gen(function* () {
342
436
  if (attrId !== OID_LOCAL_KEY_ID)
343
437
  continue;
344
438
  const valuesNode = attribute.children[1];
345
- if (valuesNode === undefined || valuesNode.kind !== "constructed")
346
- continue;
439
+ if (valuesNode === undefined ||
440
+ valuesNode.kind !== "constructed" ||
441
+ valuesNode.children.length !== 1) {
442
+ return yield* new CryptoError({
443
+ code: CryptoErrorCodeValue.corruptedFile,
444
+ reason: "PKCS#12 localKeyId attribute must contain one value.",
445
+ operation: CryptoOperationValue.pkcs12Decode,
446
+ });
447
+ }
347
448
  const valueNode = valuesNode.children[0];
348
- if (valueNode === undefined)
349
- continue;
350
- return bytesToHex(yield* bytesOf(valueNode));
449
+ if (valueNode === undefined) {
450
+ return yield* new CryptoError({
451
+ code: CryptoErrorCodeValue.corruptedFile,
452
+ reason: "PKCS#12 localKeyId attribute has no value.",
453
+ operation: CryptoOperationValue.pkcs12Decode,
454
+ });
455
+ }
456
+ if (hasLocalKeyId) {
457
+ return yield* new CryptoError({
458
+ code: CryptoErrorCodeValue.corruptedFile,
459
+ reason: "PKCS#12 bag contains multiple localKeyId attributes.",
460
+ operation: CryptoOperationValue.pkcs12Decode,
461
+ });
462
+ }
463
+ localKeyId = bytesToHex(yield* readOctetString(valueNode));
464
+ hasLocalKeyId = true;
351
465
  }
352
- return null;
466
+ return localKeyId;
353
467
  });
354
468
  const extractCertFromBag = (certBagNode) => Effect.gen(function* () {
355
469
  const fields = yield* childrenOf(certBagNode);
@@ -378,59 +492,153 @@ const parseSafeBags = (safeContents) => Effect.gen(function* () {
378
492
  }
379
493
  return bags;
380
494
  });
381
- const decryptShroudedKeyBag = (encryptedKeyInfoDer, bmpPassword, passwordBytes) => Effect.gen(function* () {
495
+ const validatePrivateKeyInfo = (pkcs8) => Effect.gen(function* () {
496
+ const node = yield* decode(pkcs8).pipe(Effect.mapError((error) => new CryptoError({
497
+ code: CryptoErrorCodeValue.corruptedFile,
498
+ reason: `Invalid decrypted PKCS#8: ${error.reason ?? error.message}`,
499
+ operation: CryptoOperationValue.pkcs12Decode,
500
+ })));
501
+ if (node.class !== "universal" || node.kind !== "constructed" || node.tag !== 0x10) {
502
+ return yield* new CryptoError({
503
+ code: CryptoErrorCodeValue.corruptedFile,
504
+ reason: "Decrypted private key is not a PKCS#8 SEQUENCE.",
505
+ operation: CryptoOperationValue.pkcs12Decode,
506
+ });
507
+ }
508
+ const fields = node.children;
509
+ if (fields.length < 3 || fields.length > 4) {
510
+ return yield* new CryptoError({
511
+ code: CryptoErrorCodeValue.corruptedFile,
512
+ reason: "Decrypted private key has an invalid PKCS#8 field count.",
513
+ operation: CryptoOperationValue.pkcs12Decode,
514
+ });
515
+ }
516
+ const versionNode = yield* elementAt(fields, 0, "PKCS#8 version");
517
+ if (versionNode.class !== "universal" ||
518
+ versionNode.kind !== "primitive" ||
519
+ versionNode.tag !== 0x02 ||
520
+ versionNode.bytes.length === 0) {
521
+ return yield* new CryptoError({
522
+ code: CryptoErrorCodeValue.corruptedFile,
523
+ reason: "Decrypted private key has an invalid PKCS#8 version.",
524
+ operation: CryptoOperationValue.pkcs12Decode,
525
+ });
526
+ }
527
+ if ((yield* integerBigInt(versionNode)) !== 0n) {
528
+ return yield* new CryptoError({
529
+ code: CryptoErrorCodeValue.corruptedFile,
530
+ reason: "Unsupported decrypted PKCS#8 version.",
531
+ operation: CryptoOperationValue.pkcs12Decode,
532
+ });
533
+ }
534
+ const algorithmNode = yield* elementAt(fields, 1, "PKCS#8 AlgorithmIdentifier");
535
+ if (algorithmNode.class !== "universal" ||
536
+ algorithmNode.kind !== "constructed" ||
537
+ algorithmNode.tag !== 0x10) {
538
+ return yield* new CryptoError({
539
+ code: CryptoErrorCodeValue.corruptedFile,
540
+ reason: "Decrypted private key has an invalid AlgorithmIdentifier.",
541
+ operation: CryptoOperationValue.pkcs12Decode,
542
+ });
543
+ }
544
+ if (algorithmNode.children.length < 1 || algorithmNode.children.length > 2) {
545
+ return yield* new CryptoError({
546
+ code: CryptoErrorCodeValue.corruptedFile,
547
+ reason: "Decrypted private key has an invalid AlgorithmIdentifier field count.",
548
+ operation: CryptoOperationValue.pkcs12Decode,
549
+ });
550
+ }
551
+ const algorithmOid = yield* elementAt(algorithmNode.children, 0, "PKCS#8 algorithm OID");
552
+ if (algorithmOid.class !== "universal" ||
553
+ algorithmOid.kind !== "primitive" ||
554
+ algorithmOid.tag !== 0x06) {
555
+ return yield* new CryptoError({
556
+ code: CryptoErrorCodeValue.corruptedFile,
557
+ reason: "Decrypted private key has an invalid PKCS#8 algorithm OID.",
558
+ operation: CryptoOperationValue.pkcs12Decode,
559
+ });
560
+ }
561
+ yield* oidString(algorithmOid);
562
+ const privateKeyNode = yield* elementAt(fields, 2, "PKCS#8 private key");
563
+ if (privateKeyNode.class !== "universal" || privateKeyNode.tag !== 0x04) {
564
+ return yield* new CryptoError({
565
+ code: CryptoErrorCodeValue.corruptedFile,
566
+ reason: "Decrypted private key has an invalid PKCS#8 private key field.",
567
+ operation: CryptoOperationValue.pkcs12Decode,
568
+ });
569
+ }
570
+ yield* readOctetString(privateKeyNode);
571
+ const attributes = fields[3];
572
+ if (attributes !== undefined &&
573
+ (attributes.class !== "context" || attributes.kind !== "constructed" || attributes.tag !== 0)) {
574
+ return yield* new CryptoError({
575
+ code: CryptoErrorCodeValue.corruptedFile,
576
+ reason: "Decrypted private key has invalid PKCS#8 attributes.",
577
+ operation: CryptoOperationValue.pkcs12Decode,
578
+ });
579
+ }
580
+ });
581
+ const decryptShroudedKeyBag = (encryptedKeyInfoDer, bmpPassword, passwordBytes, budget) => Effect.gen(function* () {
382
582
  const node = yield* decode(encryptedKeyInfoDer);
383
583
  const fields = yield* childrenOf(node);
384
584
  const algSeq = yield* childrenOf(yield* elementAt(fields, 0, "AlgorithmIdentifier"));
385
585
  const algOid = yield* oidString(yield* elementAt(algSeq, 0, "algorithm OID"));
386
586
  const algParams = yield* elementAt(algSeq, 1, "algorithm parameters");
387
- const encryptedData = yield* bytesOf(yield* elementAt(fields, 1, "encrypted key"));
388
- const pkcs8 = yield* decryptPbe(encryptedData, algOid, algParams, bmpPassword, passwordBytes).pipe(Effect.mapError((error) => error.code === CryptoErrorCodeValue.cipherError
587
+ const encryptedData = yield* readOctetString(yield* elementAt(fields, 1, "encrypted key"));
588
+ const pkcs8 = yield* decryptPbe(encryptedData, algOid, algParams, bmpPassword, passwordBytes, budget).pipe(Effect.mapError((error) => error.code === CryptoErrorCodeValue.cipherError
389
589
  ? new CryptoError({
390
590
  code: CryptoErrorCodeValue.wrongPassword,
391
591
  operation: CryptoOperationValue.pkcs12Decrypt,
392
592
  })
393
593
  : error));
394
594
  if (pkcs8[0] !== 0x30) {
395
- return yield* Effect.fail(new CryptoError({
595
+ return yield* new CryptoError({
396
596
  code: CryptoErrorCodeValue.wrongPassword,
397
597
  reason: "Decrypted private key is not valid PKCS#8.",
398
598
  operation: CryptoOperationValue.pkcs12Decode,
399
- }));
599
+ });
400
600
  }
601
+ yield* validatePrivateKeyInfo(pkcs8);
401
602
  return pkcs8;
402
603
  });
403
- // =============================================================================
404
- // Public API
405
- // =============================================================================
406
- /** Parse a `.pfx`/`.p12` container, returning DER certificate + private key. */
407
604
  export const parsePkcs12 = (data, password) => Effect.gen(function* () {
408
605
  const phrase = Redacted.value(password);
409
606
  const bmpPassword = toBmpString(phrase);
410
607
  const passwordBytes = new TextEncoder().encode(phrase);
608
+ const kdfBudget = { remaining: MAX_KDF_WORK };
411
609
  const pfx = yield* decode(data);
412
610
  const pfxChildren = yield* childrenOf(pfx);
413
- const version = yield* integerBigInt(yield* elementAt(pfxChildren, 0, "PFX version"));
611
+ const versionNode = yield* elementAt(pfxChildren, 0, "PFX version");
612
+ if (versionNode.class !== "universal" ||
613
+ versionNode.kind !== "primitive" ||
614
+ versionNode.tag !== 0x02) {
615
+ return yield* new CryptoError({
616
+ code: CryptoErrorCodeValue.invalidFormat,
617
+ reason: "Expected universal INTEGER PFX version.",
618
+ operation: CryptoOperationValue.pkcs12Decode,
619
+ });
620
+ }
621
+ const version = yield* integerBigInt(versionNode);
414
622
  if (version !== 3n) {
415
- return yield* Effect.fail(new CryptoError({
623
+ return yield* new CryptoError({
416
624
  code: CryptoErrorCodeValue.invalidFormat,
417
625
  reason: `Unsupported PFX version: ${version}.`,
418
626
  operation: CryptoOperationValue.pkcs12Decode,
419
- }));
627
+ });
420
628
  }
421
629
  const authSafe = yield* childrenOf(yield* elementAt(pfxChildren, 1, "authSafe ContentInfo"));
422
630
  const authSafeOid = yield* oidString(yield* elementAt(authSafe, 0, "authSafe OID"));
423
631
  if (authSafeOid !== OID_DATA) {
424
- return yield* Effect.fail(new CryptoError({
632
+ return yield* new CryptoError({
425
633
  code: CryptoErrorCodeValue.invalidFormat,
426
634
  reason: `Expected data ContentInfo in authSafe, got ${authSafeOid}.`,
427
635
  operation: CryptoOperationValue.pkcs12Decode,
428
- }));
636
+ });
429
637
  }
430
638
  const authSafeContent = yield* unwrapContextTag(yield* elementAt(authSafe, 1, "authSafe content"), 0);
431
639
  const authSafeData = yield* readOctetString(authSafeContent);
432
640
  if (pfxChildren.length >= 3) {
433
- yield* verifyMac(yield* elementAt(pfxChildren, 2, "MacData"), authSafeData, bmpPassword);
641
+ yield* verifyMac(yield* elementAt(pfxChildren, 2, "MacData"), authSafeData, bmpPassword, kdfBudget);
434
642
  }
435
643
  const safeContents = yield* childrenOf(yield* decode(authSafeData));
436
644
  const certificates = [];
@@ -441,7 +649,7 @@ export const parsePkcs12 = (data, password) => Effect.gen(function* () {
441
649
  const safeBagsDer = ciOid === OID_DATA
442
650
  ? yield* readOctetString(yield* unwrapContextTag(yield* elementAt(ciChildren, 1, "SafeContents"), 0))
443
651
  : ciOid === OID_ENCRYPTED_DATA
444
- ? yield* decryptEncryptedData(yield* unwrapContextTag(yield* elementAt(ciChildren, 1, "EncryptedData"), 0), bmpPassword, passwordBytes)
652
+ ? yield* decryptEncryptedData(yield* unwrapContextTag(yield* elementAt(ciChildren, 1, "EncryptedData"), 0), bmpPassword, passwordBytes, kdfBudget)
445
653
  : undefined;
446
654
  if (safeBagsDer === undefined)
447
655
  continue;
@@ -453,32 +661,68 @@ export const parsePkcs12 = (data, password) => Effect.gen(function* () {
453
661
  keyBags.push({ data: bag.data, localKeyId: bag.localKeyId });
454
662
  }
455
663
  }
456
- const firstCert = certificates[0];
457
- if (firstCert === undefined) {
458
- return yield* Effect.fail(new CryptoError({
664
+ if (certificates.length === 0) {
665
+ return yield* new CryptoError({
459
666
  code: CryptoErrorCodeValue.noCertificate,
460
667
  reason: "No certificate in PKCS#12.",
461
668
  operation: CryptoOperationValue.pkcs12Decode,
462
- }));
669
+ });
463
670
  }
464
- const keyBag = keyBags[0];
465
- if (keyBag === undefined) {
466
- return yield* Effect.fail(new CryptoError({
671
+ if (keyBags.length === 0) {
672
+ return yield* new CryptoError({
467
673
  code: CryptoErrorCodeValue.noPrivateKey,
468
674
  reason: "No private key in PKCS#12.",
469
675
  operation: CryptoOperationValue.pkcs12Decode,
470
- }));
676
+ });
677
+ }
678
+ const matchingPairs = [];
679
+ for (const candidateKey of keyBags) {
680
+ if (candidateKey.localKeyId === null)
681
+ continue;
682
+ let match;
683
+ let matchCount = 0;
684
+ for (const candidateCertificate of certificates) {
685
+ if (candidateCertificate.localKeyId === candidateKey.localKeyId) {
686
+ match = candidateCertificate;
687
+ matchCount++;
688
+ }
689
+ }
690
+ if (matchCount === 1 && match !== undefined) {
691
+ matchingPairs.push({ key: candidateKey, certificate: match });
692
+ }
693
+ }
694
+ let selectedPair = matchingPairs[0];
695
+ if (matchingPairs.length !== 1)
696
+ selectedPair = undefined;
697
+ const onlyKey = keyBags[0];
698
+ const onlyCertificate = certificates[0];
699
+ if (selectedPair === undefined &&
700
+ keyBags.length === 1 &&
701
+ certificates.length === 1 &&
702
+ onlyKey !== undefined &&
703
+ onlyCertificate !== undefined &&
704
+ (onlyKey.localKeyId === null ||
705
+ onlyCertificate.localKeyId === null ||
706
+ onlyKey.localKeyId === onlyCertificate.localKeyId)) {
707
+ selectedPair = { key: onlyKey, certificate: onlyCertificate };
708
+ }
709
+ if (selectedPair === undefined) {
710
+ return yield* new CryptoError({
711
+ code: CryptoErrorCodeValue.corruptedFile,
712
+ reason: "PKCS#12 has no unambiguous private-key/certificate pairing.",
713
+ operation: CryptoOperationValue.pkcs12Decode,
714
+ });
715
+ }
716
+ const selectedKey = selectedPair.key;
717
+ const selectedCertificate = selectedPair.certificate;
718
+ const privateKey = yield* decryptShroudedKeyBag(selectedKey.data, bmpPassword, passwordBytes, kdfBudget);
719
+ const chain = [];
720
+ for (const entry of certificates) {
721
+ if (entry !== selectedCertificate)
722
+ chain.push(entry.data);
471
723
  }
472
- const privateKey = yield* decryptShroudedKeyBag(keyBag.data, bmpPassword, passwordBytes);
473
- // Pair the end-entity to the key by localKeyId (RFC 7292); the chain is the rest.
474
- // Fall back to the first cert when no localKeyId is present (the common leaf-first case).
475
- const matched = keyBag.localKeyId === null
476
- ? undefined
477
- : certificates.find((entry) => entry.localKeyId === keyBag.localKeyId);
478
- const endEntity = matched ?? firstCert;
479
- const chain = certificates.filter((entry) => entry !== endEntity).map((entry) => entry.data);
480
724
  return {
481
- certificate: endEntity.data,
725
+ certificate: selectedPair.certificate.data,
482
726
  privateKey,
483
727
  chain,
484
728
  };