@signature-kit/crypto 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +28 -11
  3. package/dist/base64.d.ts +1 -1
  4. package/dist/base64.d.ts.map +1 -1
  5. package/dist/base64.js +15 -14
  6. package/dist/config.d.ts +31 -7
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +42 -27
  9. package/dist/pem.d.ts +1 -1
  10. package/dist/pem.d.ts.map +1 -1
  11. package/dist/pem.js +14 -8
  12. package/dist/pkcs12.d.ts +2 -10
  13. package/dist/pkcs12.d.ts.map +1 -1
  14. package/dist/pkcs12.js +380 -125
  15. package/dist/primitives/aes.d.ts +1 -14
  16. package/dist/primitives/aes.d.ts.map +1 -1
  17. package/dist/primitives/aes.js +8 -47
  18. package/dist/primitives/des.d.ts +1 -20
  19. package/dist/primitives/des.d.ts.map +1 -1
  20. package/dist/primitives/des.js +6 -67
  21. package/dist/primitives/hmac.d.ts +0 -30
  22. package/dist/primitives/hmac.d.ts.map +1 -1
  23. package/dist/primitives/hmac.js +4 -46
  24. package/dist/primitives/padding.d.ts +1 -8
  25. package/dist/primitives/padding.d.ts.map +1 -1
  26. package/dist/primitives/padding.js +2 -11
  27. package/dist/primitives/pbkdf2.d.ts +1 -17
  28. package/dist/primitives/pbkdf2.d.ts.map +1 -1
  29. package/dist/primitives/pbkdf2.js +8 -30
  30. package/dist/primitives/rc2.d.ts +1 -20
  31. package/dist/primitives/rc2.d.ts.map +1 -1
  32. package/dist/primitives/rc2.js +11 -69
  33. package/dist/primitives/sha1.d.ts +0 -13
  34. package/dist/primitives/sha1.d.ts.map +1 -1
  35. package/dist/primitives/sha1.js +1 -28
  36. package/dist/primitives/sha256.d.ts +0 -26
  37. package/dist/primitives/sha256.d.ts.map +1 -1
  38. package/dist/primitives/sha256.js +0 -34
  39. package/dist/primitives/sha512.d.ts +0 -19
  40. package/dist/primitives/sha512.d.ts.map +1 -1
  41. package/dist/primitives/sha512.js +1 -32
  42. package/package.json +8 -6
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,9 +28,21 @@ 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";
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");
39
+ const boundedIterations = (iterations, label) => Number.isSafeInteger(iterations) && iterations >= 1 && iterations <= MAX_KDF_ITERATIONS
40
+ ? Effect.succeed(iterations)
41
+ : Effect.fail(new CryptoError({
42
+ code: CryptoErrorCodeValue.corruptedFile,
43
+ reason: `Unreasonable ${label} iteration count: ${iterations}.`,
44
+ operation: CryptoOperationValue.pkcs12Decode,
45
+ }));
43
46
  const elementAt = (nodes, index, label) => {
44
47
  const node = nodes[index];
45
48
  return node === undefined
@@ -60,12 +63,11 @@ const concatBytes = (parts) => {
60
63
  }
61
64
  return result;
62
65
  };
63
- /** Read an OCTET STRING, concatenating BER constructed fragments. */
64
66
  const readOctetString = (node) => {
65
- if (node.tag !== 0x04) {
67
+ if (node.class !== "universal" || node.tag !== 0x04) {
66
68
  return Effect.fail(new CryptoError({
67
69
  code: CryptoErrorCodeValue.corruptedFile,
68
- reason: `Expected OCTET STRING, got tag ${node.tag}.`,
70
+ reason: `Expected universal OCTET STRING, got ${node.class} tag ${node.tag}.`,
69
71
  operation: CryptoOperationValue.pkcs12Decode,
70
72
  }));
71
73
  }
@@ -73,7 +75,6 @@ const readOctetString = (node) => {
73
75
  return Effect.succeed(node.bytes);
74
76
  return Effect.map(Effect.forEach(node.children, readOctetString), concatBytes);
75
77
  };
76
- /** Unwrap an EXPLICIT/IMPLICIT context tag. */
77
78
  const unwrapContextTag = (node, expectedTag) => {
78
79
  if (node.class !== "context" || node.tag !== expectedTag) {
79
80
  return Effect.fail(new CryptoError({
@@ -90,9 +91,6 @@ const unwrapContextTag = (node, expectedTag) => {
90
91
  }
91
92
  return decode(node.bytes);
92
93
  };
93
- // =============================================================================
94
- // PKCS#12 KDF (RFC 7292 Appendix B) — pure, total
95
- // =============================================================================
96
94
  const hashBytes = (algorithm, data) => {
97
95
  switch (algorithm) {
98
96
  case "sha1":
@@ -126,7 +124,21 @@ const padToMultiple = (data, blockSize) => {
126
124
  return padded;
127
125
  };
128
126
  const hashOutputLength = (algorithm) => algorithm === "sha1" ? 20 : algorithm === "sha256" ? 32 : algorithm === "sha384" ? 48 : 64;
129
- 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));
130
142
  const v = algorithm === "sha384" || algorithm === "sha512" ? 128 : 64;
131
143
  const D = new Uint8Array(v);
132
144
  D.fill(purpose);
@@ -140,10 +152,21 @@ const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm) =>
140
152
  DI.set(I, D.length);
141
153
  const result = new Uint8Array(keyLen);
142
154
  let resultOffset = 0;
155
+ let hashesSinceYield = 0;
143
156
  while (resultOffset < keyLen) {
144
157
  let A = hashBytes(algorithm, DI);
158
+ hashesSinceYield++;
159
+ if (hashesSinceYield === KDF_YIELD_INTERVAL) {
160
+ yield* kdfYield;
161
+ hashesSinceYield = 0;
162
+ }
145
163
  for (let i = 1; i < iterations; i++) {
146
164
  A = hashBytes(algorithm, A);
165
+ hashesSinceYield++;
166
+ if (hashesSinceYield === KDF_YIELD_INTERVAL) {
167
+ yield* kdfYield;
168
+ hashesSinceYield = 0;
169
+ }
147
170
  }
148
171
  const toCopy = Math.min(keyLen - resultOffset, A.length);
149
172
  result.set(A.subarray(0, toCopy), resultOffset);
@@ -162,17 +185,58 @@ const pkcs12Kdf = (bmpPassword, salt, iterations, purpose, keyLen, algorithm) =>
162
185
  }
163
186
  }
164
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
+ }));
165
239
  };
166
- // =============================================================================
167
- // MAC verification
168
- // =============================================================================
169
- const macHashAlgorithm = (oid) => oid === OID_SHA256
170
- ? "sha256"
171
- : oid === OID_SHA384
172
- ? "sha384"
173
- : oid === OID_SHA512
174
- ? "sha512"
175
- : "sha1";
176
240
  const constantTimeEquals = (a, b) => {
177
241
  if (a.length !== b.length)
178
242
  return false;
@@ -182,29 +246,26 @@ const constantTimeEquals = (a, b) => {
182
246
  }
183
247
  return diff === 0;
184
248
  };
185
- const verifyMac = (macNode, authSafeData, bmpPassword) => Effect.gen(function* () {
249
+ const verifyMac = (macNode, authSafeData, bmpPassword, budget) => Effect.gen(function* () {
186
250
  const macFields = yield* childrenOf(macNode);
187
251
  const digestInfo = yield* childrenOf(yield* elementAt(macFields, 0, "DigestInfo"));
188
252
  const algorithmSeq = yield* childrenOf(yield* elementAt(digestInfo, 0, "AlgorithmIdentifier"));
189
253
  const macAlgOid = yield* oidString(yield* elementAt(algorithmSeq, 0, "MAC algorithm OID"));
190
- const expectedDigest = yield* bytesOf(yield* elementAt(digestInfo, 1, "MAC digest"));
191
- const macSalt = yield* bytesOf(yield* elementAt(macFields, 1, "MAC salt"));
192
- const iterations = macFields.length >= 3
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);
257
+ const iterations = yield* boundedIterations(macFields.length >= 3
193
258
  ? Number(yield* integerBigInt(yield* elementAt(macFields, 2, "MAC iterations")))
194
- : 1;
195
- const algorithm = macHashAlgorithm(macAlgOid);
196
- const macKey = pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm);
259
+ : 1, "MAC");
260
+ const macKey = yield* pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm, budget);
197
261
  const computed = hmac(algorithm, macKey, authSafeData);
198
262
  if (!constantTimeEquals(computed, expectedDigest)) {
199
- return yield* Effect.fail(new CryptoError({
263
+ return yield* new CryptoError({
200
264
  code: CryptoErrorCodeValue.wrongPassword,
201
265
  operation: CryptoOperationValue.pkcs12Mac,
202
- }));
266
+ });
203
267
  }
204
268
  });
205
- // =============================================================================
206
- // PBE decryption
207
- // =============================================================================
208
269
  const pbkdf2HashAlgorithm = (oid) => {
209
270
  if (oid === OID_HMAC_SHA1)
210
271
  return Effect.succeed("sha1");
@@ -220,76 +281,112 @@ const pbkdf2HashAlgorithm = (oid) => {
220
281
  operation: CryptoOperationValue.pkcs12Decode,
221
282
  }));
222
283
  };
223
- 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* () {
224
302
  const pbes2Params = yield* childrenOf(params);
225
303
  const kdfInfo = yield* childrenOf(yield* elementAt(pbes2Params, 0, "KeyDerivationFunc"));
226
304
  const encScheme = yield* childrenOf(yield* elementAt(pbes2Params, 1, "EncryptionScheme"));
227
305
  const kdfOid = yield* oidString(yield* elementAt(kdfInfo, 0, "KDF OID"));
228
306
  if (kdfOid !== OID_PBKDF2) {
229
- return yield* Effect.fail(new CryptoError({
307
+ return yield* new CryptoError({
230
308
  code: CryptoErrorCodeValue.unsupportedAlgorithm,
231
309
  reason: `Unsupported KDF: ${kdfOid}`,
232
310
  operation: CryptoOperationValue.pkcs12Decode,
233
- }));
311
+ });
234
312
  }
235
313
  const pbkdf2Params = yield* childrenOf(yield* elementAt(kdfInfo, 1, "PBKDF2-params"));
236
- const salt = yield* bytesOf(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
237
- const iterations = Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations")));
314
+ const salt = yield* readOctetString(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
315
+ const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations"))), "PBKDF2");
238
316
  let prf = "sha1";
239
317
  for (let i = 2; i < pbkdf2Params.length; i++) {
240
318
  const param = pbkdf2Params[i];
241
- 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) {
242
323
  const prfOid = yield* oidString(yield* elementAt(param.children, 0, "PRF OID"));
243
324
  prf = yield* pbkdf2HashAlgorithm(prfOid);
244
325
  }
245
326
  }
246
327
  const encOid = yield* oidString(yield* elementAt(encScheme, 0, "encryption OID"));
247
- const iv = yield* bytesOf(yield* elementAt(encScheme, 1, "encryption IV"));
328
+ const iv = yield* readOctetString(yield* elementAt(encScheme, 1, "encryption IV"));
248
329
  if (encOid === OID_AES_128_CBC || encOid === OID_AES_192_CBC || encOid === OID_AES_256_CBC) {
249
- const keyLen = encOid === OID_AES_128_CBC ? 16 : encOid === OID_AES_192_CBC ? 24 : 32;
250
- 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);
251
334
  }
252
335
  if (encOid === OID_DES_EDE3_CBC) {
253
- 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);
254
339
  }
255
- return yield* Effect.fail(new CryptoError({
340
+ return yield* new CryptoError({
256
341
  code: CryptoErrorCodeValue.unsupportedAlgorithm,
257
342
  reason: `Unsupported encryption scheme: ${encOid}`,
258
343
  operation: CryptoOperationValue.pkcs12Decode,
259
- }));
344
+ });
260
345
  });
261
- const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, passwordBytes) => {
346
+ const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, passwordBytes, budget) => {
262
347
  if (algorithmOid === OID_PBES2) {
263
- 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
+ }));
264
359
  }
265
360
  return Effect.gen(function* () {
266
361
  const params = yield* childrenOf(algorithmParams);
267
- const salt = yield* bytesOf(yield* elementAt(params, 0, "PBE salt"));
268
- const iterations = Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations")));
269
- const derive = (length, purpose) => pkcs12Kdf(bmpPassword, salt, iterations, purpose, length, "sha1");
362
+ const salt = yield* readOctetString(yield* elementAt(params, 0, "PBE salt"));
363
+ const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations"))), "PBE");
270
364
  if (algorithmOid === OID_PBE_SHA_3DES) {
271
- 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);
272
369
  }
273
370
  if (algorithmOid === OID_PBE_SHA_2DES) {
274
- // 2-key 3DES: derive 16 bytes (K1||K2) and expand to the EDE key K1||K2||K1.
275
- const k16 = derive(16, 1);
276
- const key24 = concatBytes([k16, k16.subarray(0, 8)]);
277
- 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);
278
376
  }
279
377
  if (algorithmOid === OID_PBE_SHA_RC2_128) {
280
- return yield* rc2CbcDecrypt(derive(16, 1), 128, derive(8, 2), encryptedData);
281
- }
282
- if (algorithmOid === OID_PBE_SHA_RC2_40) {
283
- 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);
284
382
  }
285
- return yield* Effect.fail(new CryptoError({
286
- code: CryptoErrorCodeValue.unsupportedAlgorithm,
287
- reason: `Unsupported PBE algorithm: ${algorithmOid}`,
288
- operation: CryptoOperationValue.pkcs12Decode,
289
- }));
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);
290
387
  });
291
388
  };
292
- const decryptEncryptedData = (node, bmpPassword, passwordBytes) => Effect.gen(function* () {
389
+ const decryptEncryptedData = (node, bmpPassword, passwordBytes, budget) => Effect.gen(function* () {
293
390
  const edChildren = yield* childrenOf(node);
294
391
  const eci = yield* childrenOf(yield* elementAt(edChildren, 1, "EncryptedContentInfo"));
295
392
  const algSeq = yield* childrenOf(yield* elementAt(eci, 1, "AlgorithmIdentifier"));
@@ -297,16 +394,16 @@ const decryptEncryptedData = (node, bmpPassword, passwordBytes) => Effect.gen(fu
297
394
  const algParams = yield* elementAt(algSeq, 1, "algorithm parameters");
298
395
  const encryptedContentNode = yield* elementAt(eci, 2, "encrypted content");
299
396
  if (encryptedContentNode.class !== "context" || encryptedContentNode.tag !== 0) {
300
- return yield* Effect.fail(new CryptoError({
397
+ return yield* new CryptoError({
301
398
  code: CryptoErrorCodeValue.corruptedFile,
302
399
  reason: "Expected [0] IMPLICIT encrypted content.",
303
400
  operation: CryptoOperationValue.pkcs12Decode,
304
- }));
401
+ });
305
402
  }
306
403
  const encryptedContent = encryptedContentNode.kind === "constructed"
307
- ? concatBytes(yield* Effect.forEach(encryptedContentNode.children, (child) => child.kind === "primitive" ? Effect.succeed(child.bytes) : readOctetString(child)))
404
+ ? concatBytes(yield* Effect.forEach(encryptedContentNode.children, readOctetString))
308
405
  : encryptedContentNode.bytes;
309
- 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
310
407
  ? new CryptoError({
311
408
  code: CryptoErrorCodeValue.wrongPassword,
312
409
  operation: CryptoOperationValue.pkcs12Decrypt,
@@ -319,11 +416,19 @@ const bytesToHex = (bytes) => {
319
416
  output += byte.toString(16).padStart(2, "0");
320
417
  return output;
321
418
  };
322
- /** Read the localKeyId (OID 1.2.840.113549.1.9.21) from a SafeBag's bagAttributes. */
323
419
  const readLocalKeyId = (bagFields) => Effect.gen(function* () {
324
420
  const attributesNode = bagFields[2];
325
- if (attributesNode === undefined || attributesNode.kind !== "constructed")
421
+ if (attributesNode === undefined)
326
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;
327
432
  for (const attribute of attributesNode.children) {
328
433
  if (attribute.kind !== "constructed")
329
434
  continue;
@@ -331,14 +436,34 @@ const readLocalKeyId = (bagFields) => Effect.gen(function* () {
331
436
  if (attrId !== OID_LOCAL_KEY_ID)
332
437
  continue;
333
438
  const valuesNode = attribute.children[1];
334
- if (valuesNode === undefined || valuesNode.kind !== "constructed")
335
- 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
+ }
336
448
  const valueNode = valuesNode.children[0];
337
- if (valueNode === undefined)
338
- continue;
339
- 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;
340
465
  }
341
- return null;
466
+ return localKeyId;
342
467
  });
343
468
  const extractCertFromBag = (certBagNode) => Effect.gen(function* () {
344
469
  const fields = yield* childrenOf(certBagNode);
@@ -367,59 +492,153 @@ const parseSafeBags = (safeContents) => Effect.gen(function* () {
367
492
  }
368
493
  return bags;
369
494
  });
370
- 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* () {
371
582
  const node = yield* decode(encryptedKeyInfoDer);
372
583
  const fields = yield* childrenOf(node);
373
584
  const algSeq = yield* childrenOf(yield* elementAt(fields, 0, "AlgorithmIdentifier"));
374
585
  const algOid = yield* oidString(yield* elementAt(algSeq, 0, "algorithm OID"));
375
586
  const algParams = yield* elementAt(algSeq, 1, "algorithm parameters");
376
- const encryptedData = yield* bytesOf(yield* elementAt(fields, 1, "encrypted key"));
377
- 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
378
589
  ? new CryptoError({
379
590
  code: CryptoErrorCodeValue.wrongPassword,
380
591
  operation: CryptoOperationValue.pkcs12Decrypt,
381
592
  })
382
593
  : error));
383
594
  if (pkcs8[0] !== 0x30) {
384
- return yield* Effect.fail(new CryptoError({
595
+ return yield* new CryptoError({
385
596
  code: CryptoErrorCodeValue.wrongPassword,
386
597
  reason: "Decrypted private key is not valid PKCS#8.",
387
598
  operation: CryptoOperationValue.pkcs12Decode,
388
- }));
599
+ });
389
600
  }
601
+ yield* validatePrivateKeyInfo(pkcs8);
390
602
  return pkcs8;
391
603
  });
392
- // =============================================================================
393
- // Public API
394
- // =============================================================================
395
- /** Parse a `.pfx`/`.p12` container, returning DER certificate + private key. */
396
604
  export const parsePkcs12 = (data, password) => Effect.gen(function* () {
397
605
  const phrase = Redacted.value(password);
398
606
  const bmpPassword = toBmpString(phrase);
399
607
  const passwordBytes = new TextEncoder().encode(phrase);
608
+ const kdfBudget = { remaining: MAX_KDF_WORK };
400
609
  const pfx = yield* decode(data);
401
610
  const pfxChildren = yield* childrenOf(pfx);
402
- 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);
403
622
  if (version !== 3n) {
404
- return yield* Effect.fail(new CryptoError({
623
+ return yield* new CryptoError({
405
624
  code: CryptoErrorCodeValue.invalidFormat,
406
625
  reason: `Unsupported PFX version: ${version}.`,
407
626
  operation: CryptoOperationValue.pkcs12Decode,
408
- }));
627
+ });
409
628
  }
410
629
  const authSafe = yield* childrenOf(yield* elementAt(pfxChildren, 1, "authSafe ContentInfo"));
411
630
  const authSafeOid = yield* oidString(yield* elementAt(authSafe, 0, "authSafe OID"));
412
631
  if (authSafeOid !== OID_DATA) {
413
- return yield* Effect.fail(new CryptoError({
632
+ return yield* new CryptoError({
414
633
  code: CryptoErrorCodeValue.invalidFormat,
415
634
  reason: `Expected data ContentInfo in authSafe, got ${authSafeOid}.`,
416
635
  operation: CryptoOperationValue.pkcs12Decode,
417
- }));
636
+ });
418
637
  }
419
638
  const authSafeContent = yield* unwrapContextTag(yield* elementAt(authSafe, 1, "authSafe content"), 0);
420
639
  const authSafeData = yield* readOctetString(authSafeContent);
421
640
  if (pfxChildren.length >= 3) {
422
- yield* verifyMac(yield* elementAt(pfxChildren, 2, "MacData"), authSafeData, bmpPassword);
641
+ yield* verifyMac(yield* elementAt(pfxChildren, 2, "MacData"), authSafeData, bmpPassword, kdfBudget);
423
642
  }
424
643
  const safeContents = yield* childrenOf(yield* decode(authSafeData));
425
644
  const certificates = [];
@@ -430,7 +649,7 @@ export const parsePkcs12 = (data, password) => Effect.gen(function* () {
430
649
  const safeBagsDer = ciOid === OID_DATA
431
650
  ? yield* readOctetString(yield* unwrapContextTag(yield* elementAt(ciChildren, 1, "SafeContents"), 0))
432
651
  : ciOid === OID_ENCRYPTED_DATA
433
- ? 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)
434
653
  : undefined;
435
654
  if (safeBagsDer === undefined)
436
655
  continue;
@@ -442,32 +661,68 @@ export const parsePkcs12 = (data, password) => Effect.gen(function* () {
442
661
  keyBags.push({ data: bag.data, localKeyId: bag.localKeyId });
443
662
  }
444
663
  }
445
- const firstCert = certificates[0];
446
- if (firstCert === undefined) {
447
- return yield* Effect.fail(new CryptoError({
664
+ if (certificates.length === 0) {
665
+ return yield* new CryptoError({
448
666
  code: CryptoErrorCodeValue.noCertificate,
449
667
  reason: "No certificate in PKCS#12.",
450
668
  operation: CryptoOperationValue.pkcs12Decode,
451
- }));
669
+ });
452
670
  }
453
- const keyBag = keyBags[0];
454
- if (keyBag === undefined) {
455
- return yield* Effect.fail(new CryptoError({
671
+ if (keyBags.length === 0) {
672
+ return yield* new CryptoError({
456
673
  code: CryptoErrorCodeValue.noPrivateKey,
457
674
  reason: "No private key in PKCS#12.",
458
675
  operation: CryptoOperationValue.pkcs12Decode,
459
- }));
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);
460
723
  }
461
- const privateKey = yield* decryptShroudedKeyBag(keyBag.data, bmpPassword, passwordBytes);
462
- // Pair the end-entity to the key by localKeyId (RFC 7292); the chain is the rest.
463
- // Fall back to the first cert when no localKeyId is present (the common leaf-first case).
464
- const matched = keyBag.localKeyId === null
465
- ? undefined
466
- : certificates.find((entry) => entry.localKeyId === keyBag.localKeyId);
467
- const endEntity = matched ?? firstCert;
468
- const chain = certificates.filter((entry) => entry !== endEntity).map((entry) => entry.data);
469
724
  return {
470
- certificate: endEntity.data,
725
+ certificate: selectedPair.certificate.data,
471
726
  privateKey,
472
727
  chain,
473
728
  };