@signature-kit/crypto 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Export English and pt-BR `cryptoErrorMessages` catalogs for code-keyed display
6
+ copy.
7
+
8
+ - Security: bound PKCS#12 MAC, PBKDF2, and legacy PBE iteration counts at 10M so
9
+ attacker-controlled `.pfx` files cannot pin the event loop before the password
10
+ is checked.
11
+ - Extend hardening coverage across PBES2/PBKDF2 encrypted-data, legacy PBE, and
12
+ the exact 10M boundary; runtime behavior is unchanged.
13
+
14
+ ## 0.2.0
15
+
16
+ - Fix SHA-512/SHA-384 message-length encoding for inputs ≥ 512 MiB (also corrects
17
+ HMAC-SHA384/512 and PKCS#12 MAC verification over such inputs).
18
+ - Zero-pad HMAC keys longer than the block size instead of relying on out-of-bounds reads.
19
+
3
20
  ## 0.1.0
4
21
 
5
22
  - Initial npm-ready release for `@signature-kit/crypto`.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @signature-kit/crypto
2
2
 
3
- Shared cryptographic primitives for PKCS#12, PEM, base64, hashing, and cipher operations.
3
+ Shared cryptographic primitives for base64, PEM, PKCS#12, hashing, and cipher operations.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,22 +8,39 @@ Shared cryptographic primitives for PKCS#12, PEM, base64, hashing, and cipher op
8
8
  bun add @signature-kit/crypto effect
9
9
  ```
10
10
 
11
- ## Exports
11
+ `effect` is a direct runtime dependency. This is a low-level support package; prefer higher-level SignatureKit packages unless you need the primitive directly.
12
12
 
13
- - `@signature-kit/crypto/base64`
14
- - `@signature-kit/crypto/config`
15
- - `@signature-kit/crypto/pem`
16
- - `@signature-kit/crypto/pkcs12`
13
+ ## Public surface
17
14
 
18
- ## Runtime model
15
+ - `@signature-kit/crypto/base64` — `bytesToBase64` and `base64ToBytes`.
16
+ - `@signature-kit/crypto/config` — `CryptoError`, `CryptoErrorCodeValue`, operation schemas, message catalogs, and `Pkcs12ResultSchema`.
17
+ - `@signature-kit/crypto/pem` — `pemToDer` and `derToPem`.
18
+ - `@signature-kit/crypto/pkcs12` — `parsePkcs12`.
19
19
 
20
- SignatureKit packages are Effect-native. Public APIs return typed `Effect.Effect` values; recoverable faults stay in the typed error channel; callers provide required services and layers explicitly at the application boundary.
20
+ ## Example
21
21
 
22
- This is a low-level support package: keep its surface narrow and prefer the higher-level SignatureKit packages unless you need the primitive directly.
22
+ ```ts
23
+ import { bytesToBase64 } from "@signature-kit/crypto/base64";
24
+ import { pemToDer } from "@signature-kit/crypto/pem";
25
+ import { Effect } from "effect";
23
26
 
24
- ## Version
27
+ declare const certificatePem: string;
25
28
 
26
- Current npm release line: `0.1.0`.
29
+ const program = Effect.gen(function* () {
30
+ const der = yield* pemToDer(certificatePem);
31
+
32
+ return {
33
+ der,
34
+ contentBase64: bytesToBase64(der),
35
+ };
36
+ });
37
+ ```
38
+
39
+ ## Errors and i18n
40
+
41
+ Crypto failures use the `CryptoError` code catalog and `cryptoErrorMessages`. Applications can render localized copy through `@signature-kit/i18n` by passing that catalog to `errorMessage`.
42
+
43
+ Docs: <https://signaturekit.dev/en-US/docs/concepts/document-formats>.
27
44
 
28
45
  ## License
29
46
 
package/dist/base64.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Effect } from "effect";
2
+ import { CryptoError } from "./config";
1
3
  export declare const bytesToBase64: (bytes: Uint8Array) => string;
2
- export declare const base64ToBytes: (base64: string) => Uint8Array<ArrayBuffer>;
4
+ export declare const base64ToBytes: (base64: string) => Effect.Effect<Uint8Array<ArrayBuffer>, CryptoError>;
3
5
  //# sourceMappingURL=base64.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,aAAa,GAAI,OAAO,UAAU,KAAG,MAajD,CAAC;AAEF,eAAO,MAAM,aAAa,GAAI,QAAQ,MAAM,KAAG,UAAU,CAAC,WAAW,CA4BpE,CAAC"}
1
+ {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,WAAW,EAA8C,MAAM,UAAU,CAAC;AAcnF,eAAO,MAAM,aAAa,GAAI,OAAO,UAAU,KAAG,MAajD,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,QAAQ,MAAM,KACb,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,WAAW,CA2DjD,CAAC"}
package/dist/base64.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { Effect } from "effect";
2
+ import { CryptoError, CryptoErrorCodeValue, CryptoOperationValue } from "./config";
1
3
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2
4
  const base64Value = (char) => {
3
5
  const code = char.charCodeAt(0);
@@ -27,16 +29,39 @@ export const bytesToBase64 = (bytes) => {
27
29
  }
28
30
  return output;
29
31
  };
30
- export const base64ToBytes = (base64) => {
32
+ export const base64ToBytes = (base64) => Effect.gen(function* () {
31
33
  const clean = base64.replace(/[\t\n\r ]/g, "");
32
- const padding = clean.endsWith("==") ? 2 : clean.endsWith("=") ? 1 : 0;
33
- const output = new Uint8Array(Math.floor((clean.length * 3) / 4) - padding);
34
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean)) {
35
+ return yield* Effect.fail(new CryptoError({
36
+ code: CryptoErrorCodeValue.invalidFormat,
37
+ reason: "Base64 input contains invalid characters.",
38
+ operation: CryptoOperationValue.base64Decode,
39
+ }));
40
+ }
41
+ if (clean.length % 4 === 1) {
42
+ return yield* Effect.fail(new CryptoError({
43
+ code: CryptoErrorCodeValue.invalidFormat,
44
+ reason: "Base64 input has an invalid length.",
45
+ operation: CryptoOperationValue.base64Decode,
46
+ }));
47
+ }
48
+ const firstPadding = clean.indexOf("=");
49
+ if (firstPadding >= 0 && firstPadding < clean.length - (clean.endsWith("==") ? 2 : 1)) {
50
+ return yield* Effect.fail(new CryptoError({
51
+ code: CryptoErrorCodeValue.invalidFormat,
52
+ reason: "Base64 padding must be at the end.",
53
+ operation: CryptoOperationValue.base64Decode,
54
+ }));
55
+ }
56
+ const normalized = clean.padEnd(Math.ceil(clean.length / 4) * 4, "=");
57
+ const padding = normalized.endsWith("==") ? 2 : normalized.endsWith("=") ? 1 : 0;
58
+ const output = new Uint8Array(Math.floor((normalized.length * 3) / 4) - padding);
34
59
  let outputOffset = 0;
35
- for (let offset = 0; offset < clean.length; offset += 4) {
36
- const first = base64Value(clean[offset] ?? "");
37
- const second = base64Value(clean[offset + 1] ?? "");
38
- const third = base64Value(clean[offset + 2] ?? "");
39
- const fourth = base64Value(clean[offset + 3] ?? "");
60
+ for (let offset = 0; offset < normalized.length; offset += 4) {
61
+ const first = base64Value(normalized[offset] ?? "");
62
+ const second = base64Value(normalized[offset + 1] ?? "");
63
+ const third = base64Value(normalized[offset + 2] ?? "");
64
+ const fourth = base64Value(normalized[offset + 3] ?? "");
40
65
  const chunk = (first << 18) | (second << 12) | (third << 6) | fourth;
41
66
  if (outputOffset < output.length) {
42
67
  output[outputOffset] = (chunk >> 16) & 0xff;
@@ -52,4 +77,4 @@ export const base64ToBytes = (base64) => {
52
77
  }
53
78
  }
54
79
  return output;
55
- };
80
+ });
package/dist/config.d.ts CHANGED
@@ -18,9 +18,11 @@ export declare const CryptoErrorCodeValue: {
18
18
  cipherError: "crypto.CIPHER_ERROR";
19
19
  unknown: "crypto.UNKNOWN";
20
20
  };
21
- export declare const CryptoOperationSchema: Schema.Literals<readonly ["pkcs12.decode", "pkcs12.mac", "pkcs12.decrypt", "cipher.aes", "cipher.des", "cipher.rc2"]>;
21
+ export declare const CryptoOperationSchema: Schema.Literals<readonly ["base64.decode", "pem.decode", "pkcs12.decode", "pkcs12.mac", "pkcs12.decrypt", "cipher.aes", "cipher.des", "cipher.rc2"]>;
22
22
  export type CryptoOperation = (typeof CryptoOperationSchema)["Type"];
23
23
  export declare const CryptoOperationValue: {
24
+ base64Decode: "base64.decode";
25
+ pemDecode: "pem.decode";
24
26
  pkcs12Decode: "pkcs12.decode";
25
27
  pkcs12Mac: "pkcs12.mac";
26
28
  pkcs12Decrypt: "pkcs12.decrypt";
@@ -28,10 +30,38 @@ export declare const CryptoOperationValue: {
28
30
  cipherDes: "cipher.des";
29
31
  cipherRc2: "cipher.rc2";
30
32
  };
33
+ export declare const CryptoErrorMessageLocaleSchema: Schema.Literals<readonly ["en-US", "pt-BR"]>;
34
+ export type CryptoErrorMessageLocale = (typeof CryptoErrorMessageLocaleSchema)["Type"];
35
+ export declare const CryptoErrorMessagesSchema: Schema.$Record<Schema.Literals<readonly ["en-US", "pt-BR"]>, Schema.$Record<Schema.Literals<readonly ["crypto.DECODE_ERROR", "crypto.INVALID_FORMAT", "crypto.UNSUPPORTED_ALGORITHM", "crypto.WRONG_PASSWORD", "crypto.NO_CERTIFICATE", "crypto.NO_PRIVATE_KEY", "crypto.CORRUPTED_FILE", "crypto.CIPHER_ERROR", "crypto.UNKNOWN"]>, Schema.String>>;
36
+ export type CryptoErrorMessages = (typeof CryptoErrorMessagesSchema)["Type"];
37
+ export declare const cryptoErrorMessages: {
38
+ "en-US": {
39
+ "crypto.DECODE_ERROR": string;
40
+ "crypto.INVALID_FORMAT": string;
41
+ "crypto.UNSUPPORTED_ALGORITHM": string;
42
+ "crypto.WRONG_PASSWORD": string;
43
+ "crypto.NO_CERTIFICATE": string;
44
+ "crypto.NO_PRIVATE_KEY": string;
45
+ "crypto.CORRUPTED_FILE": string;
46
+ "crypto.CIPHER_ERROR": string;
47
+ "crypto.UNKNOWN": string;
48
+ };
49
+ "pt-BR": {
50
+ "crypto.DECODE_ERROR": string;
51
+ "crypto.INVALID_FORMAT": string;
52
+ "crypto.UNSUPPORTED_ALGORITHM": string;
53
+ "crypto.WRONG_PASSWORD": string;
54
+ "crypto.NO_CERTIFICATE": string;
55
+ "crypto.NO_PRIVATE_KEY": string;
56
+ "crypto.CORRUPTED_FILE": string;
57
+ "crypto.CIPHER_ERROR": string;
58
+ "crypto.UNKNOWN": string;
59
+ };
60
+ };
31
61
  declare const CryptoError_base: Schema.Class<CryptoError, Schema.TaggedStruct<"CryptoError", {
32
62
  readonly code: Schema.Literals<readonly ["crypto.DECODE_ERROR", "crypto.INVALID_FORMAT", "crypto.UNSUPPORTED_ALGORITHM", "crypto.WRONG_PASSWORD", "crypto.NO_CERTIFICATE", "crypto.NO_PRIVATE_KEY", "crypto.CORRUPTED_FILE", "crypto.CIPHER_ERROR", "crypto.UNKNOWN"]>;
33
63
  readonly reason: Schema.optional<Schema.String>;
34
- readonly operation: Schema.optional<Schema.Literals<readonly ["pkcs12.decode", "pkcs12.mac", "pkcs12.decrypt", "cipher.aes", "cipher.des", "cipher.rc2"]>>;
64
+ readonly operation: Schema.optional<Schema.Literals<readonly ["base64.decode", "pem.decode", "pkcs12.decode", "pkcs12.mac", "pkcs12.decrypt", "cipher.aes", "cipher.des", "cipher.rc2"]>>;
35
65
  }>, import("effect/Cause").YieldableError>;
36
66
  export declare class CryptoError extends CryptoError_base {
37
67
  get message(): string;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,qBAAqB,yPAUhC,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC;AACrE,eAAO,MAAM,oBAAoB;;;;;;;;;;CAUU,CAAC;AAE5C,eAAO,MAAM,qBAAqB,uHAOhC,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC;AACrE,eAAO,MAAM,oBAAoB;;;;;;;CAOU,CAAC;;;;;;AAE5C,qBAAa,WAAY,SAAQ,gBAI/B;IACA,IAAI,OAAO,IAAI,MAAM,CAqBpB;CACF;AAED,eAAO,MAAM,kBAAkB;;;;EAI7B,CAAC;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,qBAAqB,yPAUhC,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC;AACrE,eAAO,MAAM,oBAAoB;;;;;;;;;;CAUU,CAAC;AAE5C,eAAO,MAAM,qBAAqB,sJAShC,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC;AACrE,eAAO,MAAM,oBAAoB;;;;;;;;;CASU,CAAC;AAE5C,eAAO,MAAM,8BAA8B,8CAAsC,CAAC;AAClF,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,8BAA8B,CAAC,CAAC,MAAM,CAAC,CAAC;AACvF,eAAO,MAAM,yBAAyB,sVAGrC,CAAC;AACF,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,yBAAyB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7E,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;CAuB6C,CAAC;;;;;;AAc9E,qBAAa,WAAY,SAAQ,gBAI/B;IACA,IAAI,OAAO,IAAI,MAAM,CAKpB;CACF;AAED,eAAO,MAAM,kBAAkB;;;;EAI7B,CAAC;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC"}
package/dist/config.js CHANGED
@@ -28,6 +28,8 @@ export const CryptoErrorCodeValue = {
28
28
  unknown: "crypto.UNKNOWN",
29
29
  };
30
30
  export const CryptoOperationSchema = Schema.Literals([
31
+ "base64.decode",
32
+ "pem.decode",
31
33
  "pkcs12.decode",
32
34
  "pkcs12.mac",
33
35
  "pkcs12.decrypt",
@@ -36,6 +38,8 @@ export const CryptoOperationSchema = Schema.Literals([
36
38
  "cipher.rc2",
37
39
  ]);
38
40
  export const CryptoOperationValue = {
41
+ base64Decode: "base64.decode",
42
+ pemDecode: "pem.decode",
39
43
  pkcs12Decode: "pkcs12.decode",
40
44
  pkcs12Mac: "pkcs12.mac",
41
45
  pkcs12Decrypt: "pkcs12.decrypt",
@@ -43,32 +47,53 @@ export const CryptoOperationValue = {
43
47
  cipherDes: "cipher.des",
44
48
  cipherRc2: "cipher.rc2",
45
49
  };
50
+ export const CryptoErrorMessageLocaleSchema = Schema.Literals(["en-US", "pt-BR"]);
51
+ export const CryptoErrorMessagesSchema = Schema.Record(CryptoErrorMessageLocaleSchema, Schema.Record(CryptoErrorCodeSchema, Schema.String));
52
+ export const cryptoErrorMessages = {
53
+ "en-US": {
54
+ "crypto.DECODE_ERROR": "Failed to decode PKCS#12 ASN.1.",
55
+ "crypto.INVALID_FORMAT": "Unsupported PKCS#12 format.",
56
+ "crypto.UNSUPPORTED_ALGORITHM": "Unsupported PKCS#12 encryption algorithm.",
57
+ "crypto.WRONG_PASSWORD": "Wrong PKCS#12 password.",
58
+ "crypto.NO_CERTIFICATE": "No certificate found in PKCS#12 file.",
59
+ "crypto.NO_PRIVATE_KEY": "No private key found in PKCS#12 file.",
60
+ "crypto.CORRUPTED_FILE": "Corrupted PKCS#12 file.",
61
+ "crypto.CIPHER_ERROR": "Cipher operation failed.",
62
+ "crypto.UNKNOWN": "Unknown crypto failure.",
63
+ },
64
+ "pt-BR": {
65
+ "crypto.DECODE_ERROR": "Não foi possível ler os dados ASN.1 do PKCS#12.",
66
+ "crypto.INVALID_FORMAT": "Formato PKCS#12 não suportado.",
67
+ "crypto.UNSUPPORTED_ALGORITHM": "O certificado usa um algoritmo de criptografia não suportado.",
68
+ "crypto.WRONG_PASSWORD": "Senha do certificado incorreta.",
69
+ "crypto.NO_CERTIFICATE": "O arquivo não contém um certificado.",
70
+ "crypto.NO_PRIVATE_KEY": "O arquivo não contém uma chave privada.",
71
+ "crypto.CORRUPTED_FILE": "Arquivo PKCS#12 corrompido.",
72
+ "crypto.CIPHER_ERROR": "Falha na operação de criptografia.",
73
+ "crypto.UNKNOWN": "Falha de criptografia desconhecida.",
74
+ },
75
+ };
76
+ const cryptoErrorReasonOverridableByCode = {
77
+ "crypto.DECODE_ERROR": true,
78
+ "crypto.INVALID_FORMAT": true,
79
+ "crypto.UNSUPPORTED_ALGORITHM": true,
80
+ "crypto.WRONG_PASSWORD": false,
81
+ "crypto.NO_CERTIFICATE": false,
82
+ "crypto.NO_PRIVATE_KEY": false,
83
+ "crypto.CORRUPTED_FILE": true,
84
+ "crypto.CIPHER_ERROR": true,
85
+ "crypto.UNKNOWN": true,
86
+ };
46
87
  export class CryptoError extends Schema.TaggedErrorClass()("CryptoError", {
47
88
  code: CryptoErrorCodeSchema,
48
89
  reason: Schema.optional(Schema.String),
49
90
  operation: Schema.optional(CryptoOperationSchema),
50
91
  }) {
51
92
  get message() {
52
- switch (this.code) {
53
- case "crypto.DECODE_ERROR":
54
- return this.reason ?? "Failed to decode PKCS#12 ASN.1.";
55
- case "crypto.INVALID_FORMAT":
56
- return this.reason ?? "Unsupported PKCS#12 format.";
57
- case "crypto.UNSUPPORTED_ALGORITHM":
58
- return this.reason ?? "Unsupported PKCS#12 encryption algorithm.";
59
- case "crypto.WRONG_PASSWORD":
60
- return "Wrong PKCS#12 password.";
61
- case "crypto.NO_CERTIFICATE":
62
- return "No certificate found in PKCS#12 file.";
63
- case "crypto.NO_PRIVATE_KEY":
64
- return "No private key found in PKCS#12 file.";
65
- case "crypto.CORRUPTED_FILE":
66
- return this.reason ?? "Corrupted PKCS#12 file.";
67
- case "crypto.CIPHER_ERROR":
68
- return this.reason ?? "Cipher operation failed.";
69
- case "crypto.UNKNOWN":
70
- return this.reason ?? "Unknown crypto failure.";
71
- }
93
+ const defaultMessage = cryptoErrorMessages["en-US"][this.code];
94
+ return cryptoErrorReasonOverridableByCode[this.code]
95
+ ? (this.reason ?? defaultMessage)
96
+ : defaultMessage;
72
97
  }
73
98
  }
74
99
  export const Pkcs12ResultSchema = Schema.Struct({
package/dist/pem.d.ts CHANGED
@@ -1,3 +1,5 @@
1
- export declare const pemToDer: (pem: string) => Uint8Array;
1
+ import { Effect } from "effect";
2
+ import { CryptoError } from "./config";
3
+ export declare const pemToDer: (pem: string) => Effect.Effect<Uint8Array, CryptoError>;
2
4
  export declare const derToPem: (der: Uint8Array, label: string) => string;
3
5
  //# sourceMappingURL=pem.d.ts.map
package/dist/pem.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pem.d.ts","sourceRoot":"","sources":["../src/pem.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,QAAQ,GAAI,KAAK,MAAM,KAAG,UAMpC,CAAC;AAEJ,eAAO,MAAM,QAAQ,GAAI,KAAK,UAAU,EAAE,OAAO,MAAM,KAAG,MASzD,CAAC"}
1
+ {"version":3,"file":"pem.d.ts","sourceRoot":"","sources":["../src/pem.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,WAAW,EAA8C,MAAM,UAAU,CAAC;AAGnF,eAAO,MAAM,QAAQ,GAAI,KAAK,MAAM,KAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAe3E,CAAC;AAEF,eAAO,MAAM,QAAQ,GAAI,KAAK,UAAU,EAAE,OAAO,MAAM,KAAG,MASzD,CAAC"}
package/dist/pem.js CHANGED
@@ -1,8 +1,20 @@
1
+ import { Effect } from "effect";
2
+ import { CryptoError, CryptoErrorCodeValue, CryptoOperationValue } from "./config";
1
3
  import { base64ToBytes, bytesToBase64 } from "./base64";
2
- export const pemToDer = (pem) => base64ToBytes(pem
3
- .split(/\r?\n/)
4
- .filter((line) => !line.startsWith("-----"))
5
- .join(""));
4
+ export const pemToDer = (pem) => {
5
+ const base64 = pem
6
+ .split(/\r?\n/)
7
+ .filter((line) => !line.startsWith("-----"))
8
+ .join("");
9
+ if (base64.length === 0) {
10
+ return Effect.fail(new CryptoError({
11
+ code: CryptoErrorCodeValue.invalidFormat,
12
+ reason: "PEM input does not contain base64 DER content.",
13
+ operation: CryptoOperationValue.pemDecode,
14
+ }));
15
+ }
16
+ return base64ToBytes(base64);
17
+ };
6
18
  export const derToPem = (der, label) => {
7
19
  const base64 = bytesToBase64(der);
8
20
  const lines = [];
@@ -1 +1 @@
1
- {"version":3,"file":"pkcs12.d.ts","sourceRoot":"","sources":["../src/pkcs12.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAYH,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EACL,WAAW,EAGX,KAAK,YAAY,EAClB,MAAM,UAAU,CAAC;AAohBlB,gFAAgF;AAChF,eAAO,MAAM,WAAW,GACtB,MAAM,UAAU,EAChB,UAAU,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,KAClC,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAyHvC,CAAC"}
1
+ {"version":3,"file":"pkcs12.d.ts","sourceRoot":"","sources":["../src/pkcs12.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAYH,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EACL,WAAW,EAGX,KAAK,YAAY,EAClB,MAAM,UAAU,CAAC;AAgjBlB,gFAAgF;AAChF,eAAO,MAAM,WAAW,GACtB,MAAM,UAAU,EAChB,UAAU,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,KAClC,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAyHvC,CAAC"}
package/dist/pkcs12.js CHANGED
@@ -33,12 +33,24 @@ const OID_AES_128_CBC = "2.16.840.1.101.3.4.1.2";
33
33
  const OID_AES_192_CBC = "2.16.840.1.101.3.4.1.22";
34
34
  const OID_AES_256_CBC = "2.16.840.1.101.3.4.1.42";
35
35
  const OID_DES_EDE3_CBC = "1.2.840.113549.3.7";
36
+ const OID_HMAC_SHA1 = "1.2.840.113549.2.7";
36
37
  const OID_HMAC_SHA256 = "1.2.840.113549.2.9";
37
38
  const OID_HMAC_SHA384 = "1.2.840.113549.2.10";
38
39
  const OID_HMAC_SHA512 = "1.2.840.113549.2.11";
39
40
  const OID_SHA256 = "2.16.840.1.101.3.4.2.1";
40
41
  const OID_SHA384 = "2.16.840.1.101.3.4.2.2";
41
42
  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
+ const MAX_KDF_ITERATIONS = 10_000_000;
47
+ const boundedIterations = (iterations, label) => Number.isSafeInteger(iterations) && iterations >= 1 && iterations <= MAX_KDF_ITERATIONS
48
+ ? Effect.succeed(iterations)
49
+ : Effect.fail(new CryptoError({
50
+ code: CryptoErrorCodeValue.corruptedFile,
51
+ reason: `Unreasonable ${label} iteration count: ${iterations}.`,
52
+ operation: CryptoOperationValue.pkcs12Decode,
53
+ }));
42
54
  const elementAt = (nodes, index, label) => {
43
55
  const node = nodes[index];
44
56
  return node === undefined
@@ -188,9 +200,9 @@ const verifyMac = (macNode, authSafeData, bmpPassword) => Effect.gen(function* (
188
200
  const macAlgOid = yield* oidString(yield* elementAt(algorithmSeq, 0, "MAC algorithm OID"));
189
201
  const expectedDigest = yield* bytesOf(yield* elementAt(digestInfo, 1, "MAC digest"));
190
202
  const macSalt = yield* bytesOf(yield* elementAt(macFields, 1, "MAC salt"));
191
- const iterations = macFields.length >= 3
203
+ const iterations = yield* boundedIterations(macFields.length >= 3
192
204
  ? Number(yield* integerBigInt(yield* elementAt(macFields, 2, "MAC iterations")))
193
- : 1;
205
+ : 1, "MAC");
194
206
  const algorithm = macHashAlgorithm(macAlgOid);
195
207
  const macKey = pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm);
196
208
  const computed = hmac(algorithm, macKey, authSafeData);
@@ -204,13 +216,21 @@ const verifyMac = (macNode, authSafeData, bmpPassword) => Effect.gen(function* (
204
216
  // =============================================================================
205
217
  // PBE decryption
206
218
  // =============================================================================
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";
219
+ const pbkdf2HashAlgorithm = (oid) => {
220
+ if (oid === OID_HMAC_SHA1)
221
+ return Effect.succeed("sha1");
222
+ if (oid === OID_HMAC_SHA256)
223
+ return Effect.succeed("sha256");
224
+ if (oid === OID_HMAC_SHA384)
225
+ return Effect.succeed("sha384");
226
+ if (oid === OID_HMAC_SHA512)
227
+ return Effect.succeed("sha512");
228
+ return Effect.fail(new CryptoError({
229
+ code: CryptoErrorCodeValue.unsupportedAlgorithm,
230
+ reason: `Unsupported PBKDF2 PRF: ${oid}`,
231
+ operation: CryptoOperationValue.pkcs12Decode,
232
+ }));
233
+ };
214
234
  const decryptPbes2 = (encryptedData, params, passwordBytes) => Effect.gen(function* () {
215
235
  const pbes2Params = yield* childrenOf(params);
216
236
  const kdfInfo = yield* childrenOf(yield* elementAt(pbes2Params, 0, "KeyDerivationFunc"));
@@ -225,13 +245,13 @@ const decryptPbes2 = (encryptedData, params, passwordBytes) => Effect.gen(functi
225
245
  }
226
246
  const pbkdf2Params = yield* childrenOf(yield* elementAt(kdfInfo, 1, "PBKDF2-params"));
227
247
  const salt = yield* bytesOf(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
228
- const iterations = Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations")));
248
+ const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations"))), "PBKDF2");
229
249
  let prf = "sha1";
230
250
  for (let i = 2; i < pbkdf2Params.length; i++) {
231
251
  const param = pbkdf2Params[i];
232
252
  if (param !== undefined && param.kind === "constructed" && param.tag === 0x10) {
233
253
  const prfOid = yield* oidString(yield* elementAt(param.children, 0, "PRF OID"));
234
- prf = pbkdf2HashAlgorithm(prfOid);
254
+ prf = yield* pbkdf2HashAlgorithm(prfOid);
235
255
  }
236
256
  }
237
257
  const encOid = yield* oidString(yield* elementAt(encScheme, 0, "encryption OID"));
@@ -256,7 +276,7 @@ const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, p
256
276
  return Effect.gen(function* () {
257
277
  const params = yield* childrenOf(algorithmParams);
258
278
  const salt = yield* bytesOf(yield* elementAt(params, 0, "PBE salt"));
259
- const iterations = Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations")));
279
+ const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations"))), "PBE");
260
280
  const derive = (length, purpose) => pkcs12Kdf(bmpPassword, salt, iterations, purpose, length, "sha1");
261
281
  if (algorithmOid === OID_PBE_SHA_3DES) {
262
282
  return yield* tripleDesCbcDecrypt(derive(24, 1), derive(8, 2), encryptedData);
@@ -1 +1 @@
1
- {"version":3,"file":"hmac.d.ts","sourceRoot":"","sources":["../../src/primitives/hmac.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAKhC,eAAO,MAAM,uBAAuB,kEAA0D,CAAC;AAC/F,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,uBAAuB,CAAC,CAAC,MAAM,CAAC,CAAC;AAyBzE;;;;;;;GAOG;AACH,wBAAgB,IAAI,CAAC,GAAG,EAAE,iBAAiB,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,GAAG,UAAU,CAgC1F;AAED;;;;;;;;GAQG;AAEH,MAAM,MAAM,WAAW,GAAG;IACxB,8CAA8C;IAC9C,QAAQ,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,UAAU,CAAC;CACpD,CAAC;AA0CF;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,iBAAiB,EAAE,GAAG,EAAE,UAAU,GAAG,WAAW,CAkC/E"}
1
+ {"version":3,"file":"hmac.d.ts","sourceRoot":"","sources":["../../src/primitives/hmac.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAKhC,eAAO,MAAM,uBAAuB,kEAA0D,CAAC;AAC/F,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,uBAAuB,CAAC,CAAC,MAAM,CAAC,CAAC;AAsCzE;;;;;;;GAOG;AACH,wBAAgB,IAAI,CAAC,GAAG,EAAE,iBAAiB,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,GAAG,UAAU,CAwB1F;AAED;;;;;;;;GAQG;AAEH,MAAM,MAAM,WAAW,GAAG;IACxB,8CAA8C;IAC9C,QAAQ,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,UAAU,CAAC;CACpD,CAAC;AAkCF;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,iBAAiB,EAAE,GAAG,EAAE,UAAU,GAAG,WAAW,CA4B/E"}
@@ -31,6 +31,18 @@ function hashFn(alg, data) {
31
31
  return sha512(data);
32
32
  }
33
33
  }
34
+ const normalizeHmacKey = (alg, key) => {
35
+ const blockLength = blockSize(alg);
36
+ if (key.length <= blockLength) {
37
+ const normalized = new Uint8Array(blockLength);
38
+ normalized.set(key);
39
+ return normalized;
40
+ }
41
+ const hashed = hashFn(alg, key);
42
+ const normalized = new Uint8Array(blockLength);
43
+ normalized.set(hashed);
44
+ return normalized;
45
+ };
34
46
  /**
35
47
  * Compute HMAC(key, data) using the specified hash algorithm.
36
48
  *
@@ -41,15 +53,7 @@ function hashFn(alg, data) {
41
53
  */
42
54
  export function hmac(alg, key, data) {
43
55
  const B = blockSize(alg);
44
- // Step 1: If key > block size, hash it; if shorter, pad with zeros.
45
- let k;
46
- if (key.length > B) {
47
- k = hashFn(alg, key);
48
- }
49
- else {
50
- k = new Uint8Array(B);
51
- k.set(key);
52
- }
56
+ const k = normalizeHmacKey(alg, key);
53
57
  // Step 2: ipad = k XOR 0x36, opad = k XOR 0x5c
54
58
  const ipad = new Uint8Array(B);
55
59
  const opad = new Uint8Array(B);
@@ -77,15 +81,7 @@ export function hmac(alg, key, data) {
77
81
  */
78
82
  function createHmacSha256Context(key) {
79
83
  const B = 64; // SHA-256 block size
80
- // Normalize key
81
- let k;
82
- if (key.length > B) {
83
- k = sha256(key);
84
- }
85
- else {
86
- k = new Uint8Array(B);
87
- k.set(key);
88
- }
84
+ const k = normalizeHmacKey("sha256", key);
89
85
  // Precompute padded ipad and opad blocks
90
86
  const ipadBlock = new Uint8Array(B);
91
87
  const opadBlock = new Uint8Array(B);
@@ -117,14 +113,7 @@ export function createHmac(alg, key) {
117
113
  }
118
114
  // Generic fallback: precompute padded ipad/opad (saves XOR and alloc per call)
119
115
  const B = blockSize(alg);
120
- let k;
121
- if (key.length > B) {
122
- k = hashFn(alg, key);
123
- }
124
- else {
125
- k = new Uint8Array(B);
126
- k.set(key);
127
- }
116
+ const k = normalizeHmacKey(alg, key);
128
117
  const ipad = new Uint8Array(B);
129
118
  const opad = new Uint8Array(B);
130
119
  for (let i = 0; i < B; i++) {
@@ -1 +1 @@
1
- {"version":3,"file":"sha512.d.ts","sourceRoot":"","sources":["../../src/primitives/sha512.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAwNH;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAEnD;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAEnD"}
1
+ {"version":3,"file":"sha512.d.ts","sourceRoot":"","sources":["../../src/primitives/sha512.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAoNH;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAEnD;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAEnD"}
@@ -63,10 +63,8 @@ function xor3_64(ah, al, bh, bl, ch_, cl) {
63
63
  return [(ah ^ bh ^ ch_) >>> 0, (al ^ bl ^ cl) >>> 0];
64
64
  }
65
65
  function sha512Core(data, initH) {
66
- const byteLenHi = Math.floor(data.length / 0x20000000) | 0;
67
- const byteLenLo = data.length >>> 0;
68
- const bitLenHi = ((byteLenHi << 3) | (byteLenLo >>> 29)) >>> 0;
69
- const bitLenLo = (byteLenLo << 3) >>> 0;
66
+ const bitLenHi = Math.floor(data.length / 0x20000000);
67
+ const bitLenLo = (data.length << 3) >>> 0;
70
68
  const padLen = data.length % 128 < 112 ? 112 - (data.length % 128) : 240 - (data.length % 128);
71
69
  const totalLen = data.length + padLen + 16;
72
70
  const msg = new Uint8Array(totalLen);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signature-kit/crypto",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -37,7 +37,7 @@
37
37
  "test": "vitest run"
38
38
  },
39
39
  "dependencies": {
40
- "@signature-kit/asn1": "^0.1.0",
40
+ "@signature-kit/asn1": "^0.2.1",
41
41
  "effect": "4.0.0-beta.86"
42
42
  },
43
43
  "nx": {