@signature-kit/crypto 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +30 -0
  4. package/dist/base64.d.ts +3 -0
  5. package/dist/base64.d.ts.map +1 -0
  6. package/dist/base64.js +55 -0
  7. package/dist/config.d.ts +46 -0
  8. package/dist/config.d.ts.map +1 -0
  9. package/dist/config.js +78 -0
  10. package/dist/pem.d.ts +3 -0
  11. package/dist/pem.d.ts.map +1 -0
  12. package/dist/pem.js +15 -0
  13. package/dist/pkcs12.d.ts +13 -0
  14. package/dist/pkcs12.d.ts.map +1 -0
  15. package/dist/pkcs12.js +471 -0
  16. package/dist/primitives/aes.d.ts +17 -0
  17. package/dist/primitives/aes.d.ts.map +1 -0
  18. package/dist/primitives/aes.js +219 -0
  19. package/dist/primitives/des.d.ts +23 -0
  20. package/dist/primitives/des.d.ts.map +1 -0
  21. package/dist/primitives/des.js +271 -0
  22. package/dist/primitives/hmac.d.ts +39 -0
  23. package/dist/primitives/hmac.d.ts.map +1 -0
  24. package/dist/primitives/hmac.js +146 -0
  25. package/dist/primitives/padding.d.ts +11 -0
  26. package/dist/primitives/padding.d.ts.map +1 -0
  27. package/dist/primitives/padding.js +29 -0
  28. package/dist/primitives/pbkdf2.d.ts +19 -0
  29. package/dist/primitives/pbkdf2.d.ts.map +1 -0
  30. package/dist/primitives/pbkdf2.js +61 -0
  31. package/dist/primitives/rc2.d.ts +23 -0
  32. package/dist/primitives/rc2.d.ts.map +1 -0
  33. package/dist/primitives/rc2.js +192 -0
  34. package/dist/primitives/sha1.d.ts +15 -0
  35. package/dist/primitives/sha1.d.ts.map +1 -0
  36. package/dist/primitives/sha1.js +102 -0
  37. package/dist/primitives/sha256.d.ts +30 -0
  38. package/dist/primitives/sha256.d.ts.map +1 -0
  39. package/dist/primitives/sha256.js +146 -0
  40. package/dist/primitives/sha512.d.ts +22 -0
  41. package/dist/primitives/sha512.d.ts.map +1 -0
  42. package/dist/primitives/sha512.js +197 -0
  43. package/package.json +61 -0
@@ -0,0 +1,146 @@
1
+ /**
2
+ * HMAC pure TypeScript implementation (RFC 2104).
3
+ *
4
+ * Supports SHA-1, SHA-256, SHA-384, and SHA-512 as the underlying hash.
5
+ * Zero runtime dependencies. Works in any JS environment.
6
+ */
7
+ import { Schema } from "effect";
8
+ import { sha1 } from "./sha1";
9
+ import { sha256, sha256ProcessBlock, sha256WithState } from "./sha256";
10
+ import { sha384, sha512 } from "./sha512";
11
+ export const HmacHashAlgorithmSchema = Schema.Literals(["sha1", "sha256", "sha384", "sha512"]);
12
+ /**
13
+ * Returns the block size (in bytes) for the given hash algorithm.
14
+ * SHA-1/SHA-256: 64 bytes; SHA-384/SHA-512: 128 bytes.
15
+ */
16
+ function blockSize(alg) {
17
+ return alg === "sha384" || alg === "sha512" ? 128 : 64;
18
+ }
19
+ /**
20
+ * Dispatch to the appropriate hash function.
21
+ */
22
+ function hashFn(alg, data) {
23
+ switch (alg) {
24
+ case "sha1":
25
+ return sha1(data);
26
+ case "sha256":
27
+ return sha256(data);
28
+ case "sha384":
29
+ return sha384(data);
30
+ case "sha512":
31
+ return sha512(data);
32
+ }
33
+ }
34
+ /**
35
+ * Compute HMAC(key, data) using the specified hash algorithm.
36
+ *
37
+ * @param alg - Hash algorithm: 'sha1' | 'sha256' | 'sha384' | 'sha512'
38
+ * @param key - Secret key (any length)
39
+ * @param data - Message data
40
+ * @returns HMAC digest as Uint8Array (same length as hash output)
41
+ */
42
+ export function hmac(alg, key, data) {
43
+ 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
+ }
53
+ // Step 2: ipad = k XOR 0x36, opad = k XOR 0x5c
54
+ const ipad = new Uint8Array(B);
55
+ const opad = new Uint8Array(B);
56
+ for (let i = 0; i < B; i++) {
57
+ ipad[i] = k[i] ^ 0x36;
58
+ opad[i] = k[i] ^ 0x5c;
59
+ }
60
+ // Step 3: inner = H(ipad || data)
61
+ const inner = new Uint8Array(B + data.length);
62
+ inner.set(ipad);
63
+ inner.set(data, B);
64
+ const innerHash = hashFn(alg, inner);
65
+ // Step 4: outer = H(opad || inner)
66
+ const outer = new Uint8Array(B + innerHash.length);
67
+ outer.set(opad);
68
+ outer.set(innerHash, B);
69
+ return hashFn(alg, outer);
70
+ }
71
+ /**
72
+ * Create a precomputed HMAC context for SHA-256 with a fixed key.
73
+ *
74
+ * Precomputes the ipad and opad block states so each call to `compute()`
75
+ * only needs to process the message data portion — saving ~2 SHA-256 block
76
+ * compressions per call.
77
+ */
78
+ function createHmacSha256Context(key) {
79
+ 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
+ }
89
+ // Precompute padded ipad and opad blocks
90
+ const ipadBlock = new Uint8Array(B);
91
+ const opadBlock = new Uint8Array(B);
92
+ for (let i = 0; i < B; i++) {
93
+ ipadBlock[i] = k[i] ^ 0x36;
94
+ opadBlock[i] = k[i] ^ 0x5c;
95
+ }
96
+ // Process each block through SHA-256 to get half-states
97
+ const ipadState = sha256ProcessBlock(ipadBlock);
98
+ const opadState = sha256ProcessBlock(opadBlock);
99
+ return {
100
+ compute(data) {
101
+ // inner = H(ipad_state, data) — skip the ipad block compression
102
+ const innerHash = sha256WithState(ipadState, data, B);
103
+ // outer = H(opad_state, innerHash) — skip the opad block compression
104
+ return sha256WithState(opadState, innerHash, B);
105
+ },
106
+ };
107
+ }
108
+ /**
109
+ * Create a precomputed HMAC context for a fixed key and algorithm.
110
+ *
111
+ * For SHA-256, this uses block-state precomputation for best performance.
112
+ * For other algorithms, falls back to standard HMAC with cached key pads.
113
+ */
114
+ export function createHmac(alg, key) {
115
+ if (alg === "sha256") {
116
+ return createHmacSha256Context(key);
117
+ }
118
+ // Generic fallback: precompute padded ipad/opad (saves XOR and alloc per call)
119
+ 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
+ }
128
+ const ipad = new Uint8Array(B);
129
+ const opad = new Uint8Array(B);
130
+ for (let i = 0; i < B; i++) {
131
+ ipad[i] = k[i] ^ 0x36;
132
+ opad[i] = k[i] ^ 0x5c;
133
+ }
134
+ return {
135
+ compute(data) {
136
+ const inner = new Uint8Array(B + data.length);
137
+ inner.set(ipad);
138
+ inner.set(data, B);
139
+ const innerHash = hashFn(alg, inner);
140
+ const outer = new Uint8Array(B + innerHash.length);
141
+ outer.set(opad);
142
+ outer.set(innerHash, B);
143
+ return hashFn(alg, outer);
144
+ },
145
+ };
146
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * PKCS#7 unpadding helper.
3
+ *
4
+ * Validates the trailing PKCS#7 padding of a decrypted block stream and returns
5
+ * the plaintext with the padding removed. Invalid padding fails with a tagged
6
+ * `CryptoError` at the decision point rather than throwing.
7
+ */
8
+ import { Effect } from "effect";
9
+ import { CryptoError } from "../config";
10
+ export declare const removePkcs7Padding: (data: Uint8Array, blockSize: number) => Effect.Effect<Uint8Array, CryptoError>;
11
+ //# sourceMappingURL=padding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"padding.d.ts","sourceRoot":"","sources":["../../src/primitives/padding.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,WAAW,EAAwB,MAAM,WAAW,CAAC;AAE9D,eAAO,MAAM,kBAAkB,GAC7B,MAAM,UAAU,EAChB,WAAW,MAAM,KAChB,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAsBvC,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * PKCS#7 unpadding helper.
3
+ *
4
+ * Validates the trailing PKCS#7 padding of a decrypted block stream and returns
5
+ * the plaintext with the padding removed. Invalid padding fails with a tagged
6
+ * `CryptoError` at the decision point rather than throwing.
7
+ */
8
+ import { Effect } from "effect";
9
+ import { CryptoError, CryptoErrorCodeValue } from "../config";
10
+ export const removePkcs7Padding = (data, blockSize) => {
11
+ if (data.length === 0)
12
+ return Effect.succeed(data);
13
+ const pad = data[data.length - 1];
14
+ if (pad === 0 || pad > blockSize) {
15
+ return Effect.fail(new CryptoError({
16
+ code: CryptoErrorCodeValue.cipherError,
17
+ reason: "Invalid PKCS#7 padding.",
18
+ }));
19
+ }
20
+ for (let i = data.length - pad; i < data.length; i++) {
21
+ if (data[i] !== pad) {
22
+ return Effect.fail(new CryptoError({
23
+ code: CryptoErrorCodeValue.cipherError,
24
+ reason: "Invalid PKCS#7 padding.",
25
+ }));
26
+ }
27
+ }
28
+ return Effect.succeed(data.subarray(0, data.length - pad));
29
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * PBKDF2 pure TypeScript implementation (RFC 2898 / PKCS#5).
3
+ *
4
+ * Uses HMAC with any supported hash as the pseudo-random function.
5
+ * Zero runtime dependencies. Works in any JS environment.
6
+ */
7
+ import { type HmacHashAlgorithm } from "./hmac";
8
+ /**
9
+ * Derive a key of `dkLen` bytes from a password and salt using PBKDF2.
10
+ *
11
+ * @param prf - Hash algorithm for HMAC PRF: 'sha1' | 'sha256' | 'sha384' | 'sha512'
12
+ * @param password - Password as raw Uint8Array
13
+ * @param salt - Cryptographic salt
14
+ * @param iterations - Iteration count (must be >= 1)
15
+ * @param dkLen - Desired derived key length in bytes
16
+ * @returns Derived key as Uint8Array
17
+ */
18
+ export declare function pbkdf2(prf: HmacHashAlgorithm, password: Uint8Array, salt: Uint8Array, iterations: number, dkLen: number): Uint8Array;
19
+ //# sourceMappingURL=pbkdf2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pbkdf2.d.ts","sourceRoot":"","sources":["../../src/primitives/pbkdf2.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAc,KAAK,iBAAiB,EAAQ,MAAM,QAAQ,CAAC;AAElE;;;;;;;;;GASG;AACH,wBAAgB,MAAM,CACpB,GAAG,EAAE,iBAAiB,EACtB,QAAQ,EAAE,UAAU,EACpB,IAAI,EAAE,UAAU,EAChB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,GACZ,UAAU,CAqBZ"}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * PBKDF2 pure TypeScript implementation (RFC 2898 / PKCS#5).
3
+ *
4
+ * Uses HMAC with any supported hash as the pseudo-random function.
5
+ * Zero runtime dependencies. Works in any JS environment.
6
+ */
7
+ import { createHmac, hmac } from "./hmac";
8
+ /**
9
+ * Derive a key of `dkLen` bytes from a password and salt using PBKDF2.
10
+ *
11
+ * @param prf - Hash algorithm for HMAC PRF: 'sha1' | 'sha256' | 'sha384' | 'sha512'
12
+ * @param password - Password as raw Uint8Array
13
+ * @param salt - Cryptographic salt
14
+ * @param iterations - Iteration count (must be >= 1)
15
+ * @param dkLen - Desired derived key length in bytes
16
+ * @returns Derived key as Uint8Array
17
+ */
18
+ export function pbkdf2(prf, password, salt, iterations, dkLen) {
19
+ // Precompute HMAC context for this key — avoids re-deriving ipad/opad per iteration
20
+ const hmacCtx = createHmac(prf, password);
21
+ // hLen = output length of PRF (HMAC hash output)
22
+ // Compute once using the standard hmac for length detection
23
+ const hLen = hmac(prf, password, new Uint8Array(0)).length;
24
+ // Number of blocks needed
25
+ const blockCount = Math.ceil(dkLen / hLen);
26
+ const dk = new Uint8Array(dkLen);
27
+ for (let i = 1; i <= blockCount; i++) {
28
+ const block = f(hmacCtx, salt, iterations, i, hLen);
29
+ const offset = (i - 1) * hLen;
30
+ const toCopy = Math.min(hLen, dkLen - offset);
31
+ dk.set(block.subarray(0, toCopy), offset);
32
+ }
33
+ return dk;
34
+ }
35
+ /**
36
+ * Compute one PRF block: F(Password, Salt, c, i)
37
+ * = U1 XOR U2 XOR ... XOR Uc
38
+ * where U1 = PRF(Password, Salt || INT(i))
39
+ * Uk = PRF(Password, U_{k-1})
40
+ */
41
+ function f(hmacCtx, salt, iterations, blockIndex, hLen) {
42
+ // Build Salt || INT(i) (4-byte big-endian block index)
43
+ const saltWithIndex = new Uint8Array(salt.length + 4);
44
+ saltWithIndex.set(salt);
45
+ saltWithIndex[salt.length] = (blockIndex >>> 24) & 0xff;
46
+ saltWithIndex[salt.length + 1] = (blockIndex >>> 16) & 0xff;
47
+ saltWithIndex[salt.length + 2] = (blockIndex >>> 8) & 0xff;
48
+ saltWithIndex[salt.length + 3] = blockIndex & 0xff;
49
+ // U1
50
+ let u = hmacCtx.compute(saltWithIndex);
51
+ const result = new Uint8Array(hLen);
52
+ for (let j = 0; j < hLen; j++)
53
+ result[j] = u[j];
54
+ // U2 ... Uc
55
+ for (let c = 1; c < iterations; c++) {
56
+ u = hmacCtx.compute(u);
57
+ for (let j = 0; j < hLen; j++)
58
+ result[j] ^= u[j];
59
+ }
60
+ return result;
61
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * RC2-CBC pure TypeScript implementation (RFC 2268).
3
+ *
4
+ * Supports 40-bit (effectiveBits=40) and 128-bit (effectiveBits=128) effective
5
+ * key lengths, both in CBC mode with PKCS#7 unpadding.
6
+ *
7
+ * RC2 is a legacy cipher. It is used here exclusively for PKCS#12
8
+ * compatibility (pbeWithSHAAnd40BitRC2-CBC / pbeWithSHAAnd128BitRC2-CBC).
9
+ *
10
+ * Zero runtime dependencies. Works in any JS environment.
11
+ */
12
+ import { Effect } from "effect";
13
+ import { CryptoError } from "../config";
14
+ /**
15
+ * Decrypt data encrypted with RC2-CBC + PKCS#7 unpadding.
16
+ *
17
+ * @param key - Raw key bytes
18
+ * @param effectiveBits - Effective key length in bits (40 or 128)
19
+ * @param iv - 8 bytes
20
+ * @param ciphertext - Must be a multiple of 8 bytes
21
+ */
22
+ export declare const rc2CbcDecrypt: (key: Uint8Array, effectiveBits: number, iv: Uint8Array, ciphertext: Uint8Array) => Effect.Effect<Uint8Array, CryptoError>;
23
+ //# sourceMappingURL=rc2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rc2.d.ts","sourceRoot":"","sources":["../../src/primitives/rc2.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,WAAW,EAA8C,MAAM,WAAW,CAAC;AAoLpF;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,GACxB,KAAK,UAAU,EACf,eAAe,MAAM,EACrB,IAAI,UAAU,EACd,YAAY,UAAU,KACrB,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAgCvC,CAAC"}
@@ -0,0 +1,192 @@
1
+ /**
2
+ * RC2-CBC pure TypeScript implementation (RFC 2268).
3
+ *
4
+ * Supports 40-bit (effectiveBits=40) and 128-bit (effectiveBits=128) effective
5
+ * key lengths, both in CBC mode with PKCS#7 unpadding.
6
+ *
7
+ * RC2 is a legacy cipher. It is used here exclusively for PKCS#12
8
+ * compatibility (pbeWithSHAAnd40BitRC2-CBC / pbeWithSHAAnd128BitRC2-CBC).
9
+ *
10
+ * Zero runtime dependencies. Works in any JS environment.
11
+ */
12
+ import { Effect } from "effect";
13
+ import { CryptoError, CryptoErrorCodeValue, CryptoOperationValue } from "../config";
14
+ import { removePkcs7Padding } from "./padding";
15
+ // RC2 permutation table (RFC 2268, Section 2)
16
+ const PITABLE = new Uint8Array([
17
+ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
18
+ 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
19
+ 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
20
+ 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
21
+ 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
22
+ 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
23
+ 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
24
+ 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
25
+ 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
26
+ 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
27
+ 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
28
+ 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
29
+ 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
30
+ 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
31
+ 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
32
+ 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad,
33
+ ]);
34
+ /**
35
+ * RC2 key expansion.
36
+ *
37
+ * @param key - Raw key bytes (1..128 bytes)
38
+ * @param pkeySz - Effective key length in bits (e.g. 40 or 128)
39
+ * @returns 64 16-bit words as a plain number[]
40
+ */
41
+ function rc2ExpandKey(key, pkeySz) {
42
+ const L = new Uint8Array(128);
43
+ L.set(key);
44
+ const t = key.length;
45
+ const t8 = Math.ceil(pkeySz / 8);
46
+ const tm = 0xff >> (8 * t8 - pkeySz);
47
+ // Step 2: expand
48
+ for (let i = t; i < 128; i++) {
49
+ L[i] = PITABLE[(L[i - 1] + L[i - t]) & 0xff];
50
+ }
51
+ // Step 3: limit effective bits
52
+ L[128 - t8] = PITABLE[L[128 - t8] & tm];
53
+ // Step 4: reduce
54
+ for (let i = 127 - t8; i >= 0; i--) {
55
+ L[i] = PITABLE[L[i + 1] ^ L[i + t8]];
56
+ }
57
+ // Convert to 64 16-bit words (little-endian)
58
+ const K = new Array(64);
59
+ for (let i = 0; i < 64; i++) {
60
+ K[i] = L[i * 2] | (L[i * 2 + 1] << 8);
61
+ }
62
+ return K;
63
+ }
64
+ /**
65
+ * Decrypt a single 8-byte RC2 block in place.
66
+ * Implements the inverse of the 16-round RC2 encryption described in RFC 2268.
67
+ *
68
+ * Forward mix at key index j (each round processes R0..R3):
69
+ * R0 += K[j] + (R3 & R2) + (~R3 & R1); R0 = R0 <<< 1
70
+ * R1 += K[j+1] + (R0 & R3) + (~R0 & R2); R1 = R1 <<< 2
71
+ * R2 += K[j+2] + (R1 & R0) + (~R1 & R3); R2 = R2 <<< 3
72
+ * R3 += K[j+3] + (R2 & R1) + (~R2 & R0); R3 = R3 <<< 5
73
+ *
74
+ * Inverse mix at key index j (reverse order, unrotate THEN subtract):
75
+ * R3 = R3 >>> 5; R3 -= K[j+3] + (R2 & R1) + (~R2 & R0)
76
+ * R2 = R2 >>> 3; R2 -= K[j+2] + (R1 & R0) + (~R1 & R3)
77
+ * R1 = R1 >>> 2; R1 -= K[j+1] + (R0 & R3) + (~R0 & R2)
78
+ * R0 = R0 >>> 1; R0 -= K[j] + (R3 & R2) + (~R3 & R1)
79
+ */
80
+ function rc2DecryptBlock(block, K) {
81
+ // Load 4 16-bit words (little-endian)
82
+ let r0 = (block[0] | (block[1] << 8)) & 0xffff;
83
+ let r1 = (block[2] | (block[3] << 8)) & 0xffff;
84
+ let r2 = (block[4] | (block[5] << 8)) & 0xffff;
85
+ let r3 = (block[6] | (block[7] << 8)) & 0xffff;
86
+ function invMix(j) {
87
+ // Right rotate R3 by 5, then subtract
88
+ r3 = ((r3 >>> 5) | (r3 << 11)) & 0xffff;
89
+ r3 = (r3 - (K[j + 3] + (r2 & r1) + (~r2 & r0))) & 0xffff;
90
+ // Right rotate R2 by 3, then subtract
91
+ r2 = ((r2 >>> 3) | (r2 << 13)) & 0xffff;
92
+ r2 = (r2 - (K[j + 2] + (r1 & r0) + (~r1 & r3))) & 0xffff;
93
+ // Right rotate R1 by 2, then subtract
94
+ r1 = ((r1 >>> 2) | (r1 << 14)) & 0xffff;
95
+ r1 = (r1 - (K[j + 1] + (r0 & r3) + (~r0 & r2))) & 0xffff;
96
+ // Right rotate R0 by 1, then subtract
97
+ r0 = ((r0 >>> 1) | (r0 << 15)) & 0xffff;
98
+ r0 = (r0 - (K[j] + (r3 & r2) + (~r3 & r1))) & 0xffff;
99
+ }
100
+ function invMash() {
101
+ r3 = (r3 - K[r2 & 63]) & 0xffff;
102
+ r2 = (r2 - K[r1 & 63]) & 0xffff;
103
+ r1 = (r1 - K[r0 & 63]) & 0xffff;
104
+ r0 = (r0 - K[r3 & 63]) & 0xffff;
105
+ }
106
+ // Reverse of forward: inv-mix×5, inv-mash, inv-mix×6, inv-mash, inv-mix×5
107
+ // Forward key index sequence: 0,4,8,12,16 | (mash) | 20,24,28,32,36,40 | (mash) | 44,48,52,56,60
108
+ // Inverse: 60,56,52,48,44 | (invMash) | 40,36,32,28,24,20 | (invMash) | 16,12,8,4,0
109
+ invMix(60);
110
+ invMix(56);
111
+ invMix(52);
112
+ invMix(48);
113
+ invMix(44);
114
+ invMash();
115
+ invMix(40);
116
+ invMix(36);
117
+ invMix(32);
118
+ invMix(28);
119
+ invMix(24);
120
+ invMix(20);
121
+ invMash();
122
+ invMix(16);
123
+ invMix(12);
124
+ invMix(8);
125
+ invMix(4);
126
+ invMix(0);
127
+ // Store back (little-endian)
128
+ block[0] = r0 & 0xff;
129
+ block[1] = (r0 >>> 8) & 0xff;
130
+ block[2] = r1 & 0xff;
131
+ block[3] = (r1 >>> 8) & 0xff;
132
+ block[4] = r2 & 0xff;
133
+ block[5] = (r2 >>> 8) & 0xff;
134
+ block[6] = r3 & 0xff;
135
+ block[7] = (r3 >>> 8) & 0xff;
136
+ }
137
+ /**
138
+ * Pure RC2-CBC decryption. Returns the still-padded plaintext. Never throws.
139
+ *
140
+ * @param key - Raw key bytes (1..128 bytes)
141
+ * @param effectiveBits - Effective key length in bits (40 or 128)
142
+ * @param iv - 8 bytes
143
+ * @param ciphertext - Must be a multiple of 8 bytes
144
+ */
145
+ function rc2CbcDecryptRaw(key, effectiveBits, iv, ciphertext) {
146
+ const K = rc2ExpandKey(key, effectiveBits);
147
+ const plaintext = new Uint8Array(ciphertext.length);
148
+ let prev = new Uint8Array(iv);
149
+ for (let i = 0; i < ciphertext.length; i += 8) {
150
+ const block = new Uint8Array(ciphertext.subarray(i, i + 8));
151
+ const ctBlock = new Uint8Array(block); // save for CBC chain
152
+ rc2DecryptBlock(block, K);
153
+ // CBC: XOR with previous ciphertext block
154
+ for (let j = 0; j < 8; j++) {
155
+ plaintext[i + j] = block[j] ^ prev[j];
156
+ }
157
+ prev = ctBlock;
158
+ }
159
+ return plaintext;
160
+ }
161
+ /**
162
+ * Decrypt data encrypted with RC2-CBC + PKCS#7 unpadding.
163
+ *
164
+ * @param key - Raw key bytes
165
+ * @param effectiveBits - Effective key length in bits (40 or 128)
166
+ * @param iv - 8 bytes
167
+ * @param ciphertext - Must be a multiple of 8 bytes
168
+ */
169
+ export const rc2CbcDecrypt = (key, effectiveBits, iv, ciphertext) => {
170
+ if (iv.length !== 8) {
171
+ return Effect.fail(new CryptoError({
172
+ code: CryptoErrorCodeValue.cipherError,
173
+ reason: "RC2-CBC: IV must be 8 bytes.",
174
+ operation: CryptoOperationValue.cipherRc2,
175
+ }));
176
+ }
177
+ if (ciphertext.length % 8 !== 0) {
178
+ return Effect.fail(new CryptoError({
179
+ code: CryptoErrorCodeValue.cipherError,
180
+ reason: "RC2-CBC: ciphertext must be a multiple of 8 bytes.",
181
+ operation: CryptoOperationValue.cipherRc2,
182
+ }));
183
+ }
184
+ if (key.length < 1 || key.length > 128) {
185
+ return Effect.fail(new CryptoError({
186
+ code: CryptoErrorCodeValue.cipherError,
187
+ reason: "RC2: key length must be 1..128 bytes.",
188
+ operation: CryptoOperationValue.cipherRc2,
189
+ }));
190
+ }
191
+ return removePkcs7Padding(rc2CbcDecryptRaw(key, effectiveBits, iv, ciphertext), 8);
192
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * SHA-1 pure TypeScript implementation (FIPS 180-4).
3
+ *
4
+ * Zero runtime dependencies. Works in any JS environment (browser, Node.js,
5
+ * Deno, Cloudflare Workers, Bun).
6
+ *
7
+ * ⚠️ SHA-1 is cryptographically broken for collision resistance. It is used
8
+ * here exclusively for PKCS#12 legacy MAC/KDF compatibility.
9
+ */
10
+ /**
11
+ * Compute SHA-1 digest of `data`.
12
+ * Returns a 20-byte Uint8Array.
13
+ */
14
+ export declare function sha1(data: Uint8Array): Uint8Array;
15
+ //# sourceMappingURL=sha1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sha1.d.ts","sourceRoot":"","sources":["../../src/primitives/sha1.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAqBH;;;GAGG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAqFjD"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * SHA-1 pure TypeScript implementation (FIPS 180-4).
3
+ *
4
+ * Zero runtime dependencies. Works in any JS environment (browser, Node.js,
5
+ * Deno, Cloudflare Workers, Bun).
6
+ *
7
+ * ⚠️ SHA-1 is cryptographically broken for collision resistance. It is used
8
+ * here exclusively for PKCS#12 legacy MAC/KDF compatibility.
9
+ */
10
+ // SHA-1 initial hash values (first 32 bits of fractional parts of sqrt(2..5))
11
+ const H0 = 0x67452301;
12
+ const H1 = 0xefcdab89;
13
+ const H2 = 0x98badcfe;
14
+ const H3 = 0x10325476;
15
+ const H4 = 0xc3d2e1f0;
16
+ /** Rotate left 32-bit integer */
17
+ function rotl32(x, n) {
18
+ return ((x << n) | (x >>> (32 - n))) >>> 0;
19
+ }
20
+ /** Add two 32-bit unsigned integers (mod 2^32) */
21
+ function add32(...nums) {
22
+ let r = 0;
23
+ for (const n of nums)
24
+ r = (r + n) >>> 0;
25
+ return r;
26
+ }
27
+ /**
28
+ * Compute SHA-1 digest of `data`.
29
+ * Returns a 20-byte Uint8Array.
30
+ */
31
+ export function sha1(data) {
32
+ // ---- Pre-processing: padding ----
33
+ const bitLen = data.length * 8;
34
+ // Message length in bytes after padding: must be ≡ 56 (mod 64)
35
+ const padLen = data.length % 64 < 56 ? 56 - (data.length % 64) : 120 - (data.length % 64);
36
+ const totalLen = data.length + padLen + 8;
37
+ const msg = new Uint8Array(totalLen);
38
+ msg.set(data);
39
+ msg[data.length] = 0x80;
40
+ // Append bit length as big-endian 64-bit integer (only lower 32 bits in practice)
41
+ const view = new DataView(msg.buffer, msg.byteOffset, msg.byteLength);
42
+ view.setUint32(totalLen - 8, Math.floor(bitLen / 0x100000000), true);
43
+ view.setUint32(totalLen - 4, bitLen >>> 0, false);
44
+ // Actually SHA-1 uses big-endian for length
45
+ // Re-do: write the 64-bit length big-endian
46
+ const bitLenHi = Math.floor(data.length / 0x20000000) | 0; // data.length * 8, upper 32 bits
47
+ const bitLenLo = (data.length * 8) >>> 0;
48
+ view.setUint32(totalLen - 8, bitLenHi, false);
49
+ view.setUint32(totalLen - 4, bitLenLo, false);
50
+ // ---- Processing ----
51
+ let h0 = H0, h1 = H1, h2 = H2, h3 = H3, h4 = H4;
52
+ const w = new Uint32Array(80);
53
+ for (let i = 0; i < totalLen; i += 64) {
54
+ // Prepare message schedule
55
+ for (let t = 0; t < 16; t++) {
56
+ w[t] = view.getUint32(i + t * 4, false);
57
+ }
58
+ for (let t = 16; t < 80; t++) {
59
+ w[t] = rotl32(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1);
60
+ }
61
+ let a = h0, b = h1, c = h2, d = h3, e = h4;
62
+ for (let t = 0; t < 80; t++) {
63
+ let f, k;
64
+ if (t < 20) {
65
+ f = (b & c) | ((~b >>> 0) & d);
66
+ k = 0x5a827999;
67
+ }
68
+ else if (t < 40) {
69
+ f = b ^ c ^ d;
70
+ k = 0x6ed9eba1;
71
+ }
72
+ else if (t < 60) {
73
+ f = (b & c) | (b & d) | (c & d);
74
+ k = 0x8f1bbcdc;
75
+ }
76
+ else {
77
+ f = b ^ c ^ d;
78
+ k = 0xca62c1d6;
79
+ }
80
+ const temp = add32(rotl32(a, 5), f, e, k, w[t]);
81
+ e = d;
82
+ d = c;
83
+ c = rotl32(b, 30);
84
+ b = a;
85
+ a = temp;
86
+ }
87
+ h0 = add32(h0, a);
88
+ h1 = add32(h1, b);
89
+ h2 = add32(h2, c);
90
+ h3 = add32(h3, d);
91
+ h4 = add32(h4, e);
92
+ }
93
+ // ---- Produce digest ----
94
+ const digest = new Uint8Array(20);
95
+ const dv = new DataView(digest.buffer);
96
+ dv.setUint32(0, h0, false);
97
+ dv.setUint32(4, h1, false);
98
+ dv.setUint32(8, h2, false);
99
+ dv.setUint32(12, h3, false);
100
+ dv.setUint32(16, h4, false);
101
+ return digest;
102
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * SHA-256 pure TypeScript implementation (FIPS 180-4).
3
+ *
4
+ * Zero runtime dependencies. Works in any JS environment.
5
+ */
6
+ /**
7
+ * Compute SHA-256 digest of `data`.
8
+ * Returns a 32-byte Uint8Array.
9
+ */
10
+ export declare function sha256(data: Uint8Array): Uint8Array;
11
+ /**
12
+ * Compute SHA-256 with a pre-processed initial state.
13
+ *
14
+ * This is used for HMAC key-schedule precomputation: the first 64-byte block
15
+ * (ipad or opad XOR key) is processed once and the resulting state is reused
16
+ * for every HMAC call with the same key.
17
+ *
18
+ * @param initState - 8-element Uint32Array with the pre-processed hash state
19
+ * @param data - The message data (appended after the already-processed block)
20
+ * @param prefixLen - Number of bytes already processed (for length encoding), typically 64
21
+ * @returns 32-byte SHA-256 digest
22
+ */
23
+ export declare function sha256WithState(initState: Uint32Array, data: Uint8Array, prefixLen: number): Uint8Array;
24
+ /**
25
+ * Process a single full 64-byte block from `blockBytes` into a copy of INIT_H.
26
+ * Returns the resulting 8-element hash state.
27
+ * Used to precompute HMAC ipad/opad half-states.
28
+ */
29
+ export declare function sha256ProcessBlock(blockBytes: Uint8Array): Uint32Array;
30
+ //# sourceMappingURL=sha256.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sha256.d.ts","sourceRoot":"","sources":["../../src/primitives/sha256.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAwEH;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CA8BnD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,WAAW,EACtB,IAAI,EAAE,UAAU,EAChB,SAAS,EAAE,MAAM,GAChB,UAAU,CA8BZ;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,WAAW,CAKtE"}