leviathan-crypto 1.3.1 → 2.0.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 (124) hide show
  1. package/CLAUDE.md +129 -76
  2. package/README.md +166 -221
  3. package/SECURITY.md +89 -37
  4. package/dist/chacha20/cipher-suite.d.ts +4 -0
  5. package/dist/chacha20/cipher-suite.js +78 -0
  6. package/dist/chacha20/embedded.d.ts +1 -0
  7. package/dist/chacha20/embedded.js +27 -0
  8. package/dist/chacha20/index.d.ts +20 -7
  9. package/dist/chacha20/index.js +41 -14
  10. package/dist/chacha20/ops.d.ts +1 -1
  11. package/dist/chacha20/ops.js +19 -18
  12. package/dist/chacha20/pool-worker.js +77 -0
  13. package/dist/ct-wasm.d.ts +1 -0
  14. package/dist/ct-wasm.js +3 -0
  15. package/dist/ct.wasm +0 -0
  16. package/dist/docs/aead.md +320 -0
  17. package/dist/docs/architecture.md +419 -285
  18. package/dist/docs/argon2id.md +42 -30
  19. package/dist/docs/chacha20.md +218 -150
  20. package/dist/docs/exports.md +241 -0
  21. package/dist/docs/fortuna.md +65 -74
  22. package/dist/docs/init.md +172 -178
  23. package/dist/docs/loader.md +87 -132
  24. package/dist/docs/serpent.md +134 -565
  25. package/dist/docs/sha2.md +91 -103
  26. package/dist/docs/sha3.md +70 -36
  27. package/dist/docs/types.md +93 -16
  28. package/dist/docs/utils.md +114 -41
  29. package/dist/embedded/chacha20.d.ts +1 -1
  30. package/dist/embedded/chacha20.js +2 -1
  31. package/dist/embedded/kyber.d.ts +1 -0
  32. package/dist/embedded/kyber.js +3 -0
  33. package/dist/embedded/serpent.d.ts +1 -1
  34. package/dist/embedded/serpent.js +2 -1
  35. package/dist/embedded/sha2.d.ts +1 -1
  36. package/dist/embedded/sha2.js +2 -1
  37. package/dist/embedded/sha3.d.ts +1 -1
  38. package/dist/embedded/sha3.js +2 -1
  39. package/dist/errors.d.ts +10 -0
  40. package/dist/{serpent/seal.js → errors.js} +14 -46
  41. package/dist/fortuna.d.ts +2 -8
  42. package/dist/fortuna.js +11 -9
  43. package/dist/index.d.ts +25 -9
  44. package/dist/index.js +36 -7
  45. package/dist/init.d.ts +3 -7
  46. package/dist/init.js +18 -35
  47. package/dist/keccak/embedded.d.ts +1 -0
  48. package/dist/keccak/embedded.js +27 -0
  49. package/dist/keccak/index.d.ts +4 -0
  50. package/dist/keccak/index.js +31 -0
  51. package/dist/kyber/embedded.d.ts +1 -0
  52. package/dist/kyber/embedded.js +27 -0
  53. package/dist/kyber/indcpa.d.ts +49 -0
  54. package/dist/kyber/indcpa.js +352 -0
  55. package/dist/kyber/index.d.ts +38 -0
  56. package/dist/kyber/index.js +150 -0
  57. package/dist/kyber/kem.d.ts +21 -0
  58. package/dist/kyber/kem.js +160 -0
  59. package/dist/kyber/params.d.ts +14 -0
  60. package/dist/kyber/params.js +37 -0
  61. package/dist/kyber/suite.d.ts +13 -0
  62. package/dist/kyber/suite.js +93 -0
  63. package/dist/kyber/types.d.ts +98 -0
  64. package/dist/kyber/types.js +25 -0
  65. package/dist/kyber/validate.d.ts +19 -0
  66. package/dist/kyber/validate.js +68 -0
  67. package/dist/kyber.wasm +0 -0
  68. package/dist/loader.d.ts +19 -4
  69. package/dist/loader.js +91 -25
  70. package/dist/serpent/cipher-suite.d.ts +4 -0
  71. package/dist/serpent/cipher-suite.js +121 -0
  72. package/dist/serpent/embedded.d.ts +1 -0
  73. package/dist/serpent/embedded.js +27 -0
  74. package/dist/serpent/index.d.ts +6 -37
  75. package/dist/serpent/index.js +9 -118
  76. package/dist/serpent/pool-worker.d.ts +1 -0
  77. package/dist/serpent/pool-worker.js +202 -0
  78. package/dist/serpent/serpent-cbc.d.ts +30 -0
  79. package/dist/serpent/serpent-cbc.js +136 -0
  80. package/dist/sha2/embedded.d.ts +1 -0
  81. package/dist/sha2/embedded.js +27 -0
  82. package/dist/sha2/hkdf.js +6 -2
  83. package/dist/sha2/index.d.ts +3 -2
  84. package/dist/sha2/index.js +3 -4
  85. package/dist/sha3/embedded.d.ts +1 -0
  86. package/dist/sha3/embedded.js +27 -0
  87. package/dist/sha3/index.d.ts +3 -2
  88. package/dist/sha3/index.js +3 -4
  89. package/dist/stream/constants.d.ts +6 -0
  90. package/dist/stream/constants.js +30 -0
  91. package/dist/stream/header.d.ts +9 -0
  92. package/dist/stream/header.js +77 -0
  93. package/dist/stream/index.d.ts +7 -0
  94. package/dist/stream/index.js +27 -0
  95. package/dist/stream/open-stream.d.ts +21 -0
  96. package/dist/stream/open-stream.js +146 -0
  97. package/dist/stream/seal-stream-pool.d.ts +38 -0
  98. package/dist/stream/seal-stream-pool.js +391 -0
  99. package/dist/stream/seal-stream.d.ts +20 -0
  100. package/dist/stream/seal-stream.js +142 -0
  101. package/dist/stream/seal.d.ts +9 -0
  102. package/dist/stream/seal.js +75 -0
  103. package/dist/stream/types.d.ts +24 -0
  104. package/dist/stream/types.js +26 -0
  105. package/dist/utils.d.ts +12 -7
  106. package/dist/utils.js +75 -19
  107. package/dist/wasm-source.d.ts +12 -0
  108. package/dist/wasm-source.js +26 -0
  109. package/package.json +13 -5
  110. package/dist/chacha20/pool.d.ts +0 -52
  111. package/dist/chacha20/pool.js +0 -188
  112. package/dist/chacha20/pool.worker.js +0 -37
  113. package/dist/docs/chacha20_pool.md +0 -309
  114. package/dist/docs/wasm.md +0 -194
  115. package/dist/serpent/seal.d.ts +0 -8
  116. package/dist/serpent/stream-pool.d.ts +0 -48
  117. package/dist/serpent/stream-pool.js +0 -285
  118. package/dist/serpent/stream-sealer.d.ts +0 -50
  119. package/dist/serpent/stream-sealer.js +0 -341
  120. package/dist/serpent/stream.d.ts +0 -28
  121. package/dist/serpent/stream.js +0 -205
  122. package/dist/serpent/stream.worker.d.ts +0 -32
  123. package/dist/serpent/stream.worker.js +0 -117
  124. /package/dist/chacha20/{pool.worker.d.ts → pool-worker.d.ts} +0 -0
@@ -1,24 +1,31 @@
1
- # Serpent-256 block cipher TypeScript API
1
+ # Serpent-256 TypeScript API
2
2
 
3
3
  > [!NOTE]
4
- > Authenticated encryption via `SerpentSeal`, plus low-level block, CTR, and CBC
5
- > classes for advanced use.
6
- >
7
4
  > See [Serpent implementation audit](./serpent_audit.md) for algorithm correctness verifications.
8
5
 
6
+ > ### Table of Contents
7
+ > - [Overview](#overview)
8
+ > - [Security Notes](#security-notes)
9
+ > - [Module Init](#module-init)
10
+ > - [API Reference](#api-reference)
11
+ > - [Usage Examples](#usage-examples)
12
+ > - [Error Conditions](#error-conditions)
13
+
14
+ ---
15
+
9
16
  ## Overview
10
17
 
11
- `SerpentSeal` is the primary encryption API for the Serpent module. It provides
12
- authenticated Serpent-256 encryption in a single call -- no manual IV generation,
13
- no separate MAC step, no room for misuse. Internally it uses Encrypt-then-MAC
14
- (SerpentCbc + HMAC-SHA256) and verifies authentication before decryption.
18
+ `SerpentCipher` is the primary API for authenticated Serpent-256 encryption. Pass it
19
+ to `Seal` for one-shot AEAD, or to `SealStream`/`OpenStream` for streaming. There is
20
+ no manual IV generation, no separate MAC step, and no room for misuse. Internally it
21
+ uses Encrypt-then-MAC (Serpent-CBC + HMAC-SHA-256) with HKDF key derivation.
15
22
 
16
23
  For advanced use cases, three lower-level classes are available: `Serpent` (raw
17
24
  16-byte block operations), `SerpentCtr` (counter mode streaming), and `SerpentCbc`
18
25
  (cipher block chaining with PKCS7 padding). These are unauthenticated and require
19
26
  explicit opt-in.
20
27
 
21
- Serpent was an AES finalist. It uses 32 rounds versus AES's 10--14, yielding a
28
+ Serpent was an AES finalist. It uses 32 rounds versus AES's 10 to 14, yielding a
22
29
  larger security margin at comparable speed in WASM.
23
30
 
24
31
  ---
@@ -33,35 +40,31 @@ larger security margin at comparable speed in WASM.
33
40
 
34
41
  This is the most dangerous mistake you can make with this module. An attacker who
35
42
  can modify ciphertext encrypted with `SerpentCbc` or `SerpentCtr` will produce
36
- corrupted plaintext on decryption -- and decryption will succeed without any
37
- indication of tampering. There is no integrity check. The caller receives garbage
38
- and has no way to distinguish it from the original message.
43
+ corrupted plaintext on decryption. Decryption succeeds without any indication of
44
+ tampering. There is no integrity check. Your caller receives garbage and has no way
45
+ to distinguish it from the original message.
39
46
 
40
- `SerpentSeal` eliminates this problem. It computes an HMAC tag over the ciphertext
41
- and verifies it before decryption. If anything has been modified, `decrypt()` throws
42
- instead of returning corrupted data.
47
+ `Seal` with `SerpentCipher` eliminates this problem. It computes an HMAC tag over
48
+ the ciphertext and verifies it before decryption. If anything has been modified,
49
+ `Seal.decrypt()` throws instead of returning corrupted data.
43
50
 
44
- Leviathan also offers a `XChaCha20Poly1305` implementation an alternative that
45
- provides authenticated encryption with a different cipher. See
46
- [chacha20.md](./chacha20.md).
51
+ `Seal` with `XChaCha20Cipher` is an alternative using a different cipher.
52
+ See [chacha20.md](./chacha20.md).
47
53
 
48
54
  ### Never reuse a nonce or IV with the same key
49
55
 
50
- - **CTR mode**: Reusing a nonce with the same key is catastrophic. It produces the
51
- same keystream, which means an attacker can XOR two ciphertexts together and
52
- recover both plaintexts. Always generate a fresh random nonce for each message.
53
- - **CBC mode**: The IV (initialization vector) must be random and unpredictable for
54
- each encryption. A predictable IV enables chosen-plaintext attacks.
56
+ In CTR mode, reusing a nonce with the same key is catastrophic. It produces the
57
+ same keystream, which means an attacker can XOR two ciphertexts together and
58
+ recover both plaintexts. Always generate a fresh random nonce for each message.
59
+ In CBC mode, the IV must be random and unpredictable for each encryption. A predictable IV enables chosen-plaintext attacks.
55
60
 
56
- Use `randomBytes(16)` to generate nonces and IVs. `SerpentSeal` handles IV
57
- generation internally.
61
+ Use `randomBytes(16)` to generate nonces and IVs. `Seal` with `SerpentCipher` handles IV generation internally.
58
62
 
59
63
  ### Always use 256-bit keys
60
64
 
61
65
  Unless you have a specific reason to use a shorter key, pass a 32-byte key to
62
66
  every Serpent operation. Shorter keys provide less security margin and there is no
63
- meaningful performance benefit to using them. `SerpentSeal` requires a 64-byte key
64
- (32 bytes encryption + 32 bytes MAC).
67
+ meaningful performance benefit to using them. `SerpentCipher` requires a 32-byte key; HKDF derives enc/mac/iv keys internally.
65
68
 
66
69
  ### Call dispose() when done
67
70
 
@@ -77,24 +80,25 @@ in memory longer than necessary.
77
80
  Each module subpath exports its own init function for consumers who want
78
81
  tree-shakeable imports.
79
82
 
80
- ### `serpentInit(mode?, opts?)`
83
+ ### `serpentInit(source)`
81
84
 
82
85
  Initializes only the serpent WASM binary. Equivalent to calling the
83
- root `init(['serpent'], mode, opts)` but without pulling the other three
86
+ root `init({ serpent: serpentWasm })` but without pulling the other three
84
87
  modules into the bundle.
85
88
 
86
89
  **Signature:**
87
90
 
88
91
  ```typescript
89
- async function serpentInit(mode?: Mode, opts?: InitOpts): Promise<void>
92
+ async function serpentInit(source: WasmSource): Promise<void>
90
93
  ```
91
94
 
92
95
  **Usage:**
93
96
 
94
97
  ```typescript
95
98
  import { serpentInit, Serpent } from 'leviathan-crypto/serpent'
99
+ import { serpentWasm } from 'leviathan-crypto/serpent/embedded'
96
100
 
97
- await serpentInit()
101
+ await serpentInit(serpentWasm)
98
102
  const cipher = new Serpent()
99
103
  ```
100
104
 
@@ -103,69 +107,66 @@ const cipher = new Serpent()
103
107
  ## API Reference
104
108
 
105
109
  All classes require their WASM modules to be initialized before construction.
106
- `SerpentSeal` requires both `serpent` and `sha2`. All other classes require
107
- `serpent` only.
110
+ `SerpentCipher` (and therefore `Seal`, `SealStream`, `OpenStream`) requires both
111
+ `serpent` and `sha2`. `Serpent`, `SerpentCtr`, and `SerpentCbc` require `serpent` only.
108
112
 
109
- ### SerpentSeal
113
+ ### SerpentCipher
110
114
 
111
- Authenticated Serpent-256 encryption. Handles IV generation, HMAC computation,
112
- and verification internally -- no manual IV or MAC management required.
115
+ `CipherSuite` implementation for Serpent-256 CBC+HMAC-SHA-256. Pass to `Seal`,
116
+ `SealStream`, or `OpenStream`. Never instantiated directly.
113
117
 
114
- ```typescript
115
- class SerpentSeal {
116
- constructor()
117
- encrypt(key: Uint8Array, plaintext: Uint8Array): Uint8Array
118
- decrypt(key: Uint8Array, data: Uint8Array): Uint8Array
119
- dispose(): void
120
- }
121
- ```
122
-
123
- #### `constructor()`
124
-
125
- Creates a new SerpentSeal instance. Throws if `init(['serpent', 'sha2'])` has not
126
- been called.
118
+ Requires `init({ serpent: serpentWasm, sha2: sha2Wasm })`.
127
119
 
128
- ---
120
+ | Property | Value |
121
+ |----------|-------|
122
+ | `formatEnum` | `0x02` |
123
+ | `keySize` | `32` |
124
+ | `tagSize` | `32` (HMAC-SHA-256) |
125
+ | `padded` | `true` (PKCS7) |
126
+ | `wasmModules` | `['serpent', 'sha2']` |
129
127
 
130
- #### `encrypt(key: Uint8Array, plaintext: Uint8Array): Uint8Array`
128
+ #### `SerpentCipher.keygen(): Uint8Array`
131
129
 
132
- Encrypts plaintext and returns a sealed blob containing the ciphertext and
133
- authentication data. The output is opaque -- pass it directly to `decrypt()`.
130
+ Returns `randomBytes(32)`. Convenience method. Not on the `CipherSuite` interface.
134
131
 
135
- - **key** -- exactly 64 bytes (32 bytes encryption key + 32 bytes MAC key).
136
- Throws `RangeError` if the length is not 64.
137
- - **plaintext** -- any length.
132
+ #### Usage with `Seal`
138
133
 
139
- A fresh random IV is generated internally for each call. Two encryptions of the
140
- same plaintext with the same key produce different output.
134
+ ```typescript
135
+ import { init, Seal, SerpentCipher } from 'leviathan-crypto'
136
+ import { serpentWasm } from 'leviathan-crypto/serpent/embedded'
137
+ import { sha2Wasm } from 'leviathan-crypto/sha2/embedded'
141
138
 
142
- ---
139
+ await init({ serpent: serpentWasm, sha2: sha2Wasm })
143
140
 
144
- #### `decrypt(key: Uint8Array, data: Uint8Array): Uint8Array`
141
+ const key = SerpentCipher.keygen()
142
+ const blob = Seal.encrypt(SerpentCipher, key, plaintext)
143
+ const pt = Seal.decrypt(SerpentCipher, key, blob) // throws on tamper
144
+ ```
145
145
 
146
- Verifies the authentication tag and decrypts the sealed blob. MAC verification
147
- happens before decryption -- if the data has been tampered with, `decrypt()` throws
148
- and never returns corrupted plaintext.
146
+ #### Usage with `SealStream` / `OpenStream`
149
147
 
150
- - **key** -- exactly 64 bytes. Must be the same key used for encryption. Throws
151
- `RangeError` if the length is not 64.
152
- - **data** -- the sealed blob from `encrypt()`. Must be at least 64 bytes. Throws
153
- `RangeError` if shorter. Throws `Error` if authentication fails.
148
+ ```typescript
149
+ import { SealStream, OpenStream } from 'leviathan-crypto/stream'
150
+ import { SerpentCipher } from 'leviathan-crypto/serpent'
154
151
 
155
- ---
152
+ const sealer = new SealStream(SerpentCipher, key)
153
+ const preamble = sealer.preamble // 20 bytes, send before first chunk
154
+ const ct0 = sealer.push(chunk0)
155
+ const ctLast = sealer.finalize(lastChunk)
156
156
 
157
- #### `dispose(): void`
157
+ const opener = new OpenStream(SerpentCipher, key, preamble)
158
+ const pt0 = opener.pull(ct0)
159
+ const ptLast = opener.finalize(ctLast)
160
+ ```
158
161
 
159
- Wipes all key material and intermediate state from WASM memory. Delegates to both
160
- internal SerpentCbc and HMAC_SHA256 instances.
162
+ See [aead.md](./aead.md) for the full `Seal`, `SealStream`, and `OpenStream` API.
161
163
 
162
164
  ---
163
165
 
164
166
  ### Serpent
165
167
 
166
168
  Raw Serpent block encryption and decryption. Operates on exactly 16-byte blocks.
167
- This class is a low-level building block, most users should use `SerpentSeal`
168
- instead.
169
+ This class is a low-level building block; use `Seal` with `SerpentCipher` for most purposes.
169
170
 
170
171
  ```typescript
171
172
  class Serpent {
@@ -179,7 +180,7 @@ class Serpent {
179
180
 
180
181
  #### `constructor()`
181
182
 
182
- Creates a new Serpent instance. Throws if `init(['serpent'])` has not been called.
183
+ Creates a new Serpent instance. Throws if `init({ serpent: serpentWasm })` has not been called.
183
184
 
184
185
  ---
185
186
 
@@ -188,7 +189,7 @@ Creates a new Serpent instance. Throws if `init(['serpent'])` has not been calle
188
189
  Loads and expands a key for subsequent block operations. Must be called before
189
190
  `encryptBlock()` or `decryptBlock()`.
190
191
 
191
- - **key** -- 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
192
+ - **key**: 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
192
193
 
193
194
  ---
194
195
 
@@ -196,7 +197,7 @@ Loads and expands a key for subsequent block operations. Must be called before
196
197
 
197
198
  Encrypts a single 16-byte block and returns the 16-byte ciphertext.
198
199
 
199
- - **plaintext** -- exactly 16 bytes. Throws `RangeError` if the length is not 16.
200
+ - **plaintext**: exactly 16 bytes. Throws `RangeError` if the length is not 16.
200
201
 
201
202
  ---
202
203
 
@@ -204,7 +205,7 @@ Encrypts a single 16-byte block and returns the 16-byte ciphertext.
204
205
 
205
206
  Decrypts a single 16-byte block and returns the 16-byte plaintext.
206
207
 
207
- - **ciphertext** -- exactly 16 bytes. Throws `RangeError` if the length is not 16.
208
+ - **ciphertext**: exactly 16 bytes. Throws `RangeError` if the length is not 16.
208
209
 
209
210
  ---
210
211
 
@@ -222,7 +223,7 @@ stream of chunks.
222
223
 
223
224
  > [!WARNING]
224
225
  > CTR mode is unauthenticated. An attacker can modify ciphertext
225
- > without detection. Use `SerpentSeal` for authenticated encryption, or pair
226
+ > without detection. Use `Seal` with `SerpentCipher` for authenticated encryption, or pair
226
227
  > with HMAC-SHA256 (Encrypt-then-MAC).
227
228
 
228
229
  ```typescript
@@ -238,11 +239,11 @@ class SerpentCtr {
238
239
 
239
240
  #### `constructor(opts: { dangerUnauthenticated: true })`
240
241
 
241
- Creates a new SerpentCtr instance. Throws if `init(['serpent'])` has not been
242
+ Creates a new SerpentCtr instance. Throws if `init({ serpent: serpentWasm })` has not been
242
243
  called. Throws if `{ dangerUnauthenticated: true }` is not passed:
243
244
 
244
245
  ```
245
- leviathan-crypto: SerpentCtr is unauthenticated — use SerpentSeal instead.
246
+ leviathan-crypto: SerpentCtr is unauthenticated — use Seal with SerpentCipher instead.
246
247
  To use SerpentCtr directly, pass { dangerUnauthenticated: true }.
247
248
  ```
248
249
 
@@ -253,8 +254,8 @@ To use SerpentCtr directly, pass { dangerUnauthenticated: true }.
253
254
  Initializes the CTR state for encryption. Loads the key, sets the nonce, and
254
255
  resets the internal counter to zero.
255
256
 
256
- - **key** -- 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
257
- - **nonce** -- exactly 16 bytes. Throws `RangeError` if the length is not 16.
257
+ - **key**: 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
258
+ - **nonce**: exactly 16 bytes. Throws `RangeError` if the length is not 16.
258
259
 
259
260
  ---
260
261
 
@@ -264,24 +265,19 @@ Encrypts a chunk of plaintext and returns the same-length ciphertext. Call this
264
265
  one or more times after `beginEncrypt()`. The internal counter advances
265
266
  automatically.
266
267
 
267
- - **chunk** -- any length up to the module's internal chunk buffer size. Throws
268
- `RangeError` if the chunk exceeds the maximum size.
268
+ - **chunk**: any length up to the module's internal chunk buffer size. Throws `RangeError` if the chunk exceeds the maximum size.
269
269
 
270
270
  > [!NOTE]
271
- > Automatically dispatches to the 4-wide SIMD path (`encryptChunk_simd`) when
272
- > the runtime supports WebAssembly SIMD (`hasSIMD()` returns `true`), otherwise
273
- > falls back to the scalar unrolled path. The dispatch is transparent — no API
274
- > change required.
271
+ > Automatically dispatches to the 4-wide SIMD path (`encryptChunk_simd`) when the runtime supports WebAssembly SIMD (`hasSIMD()` returns `true`), otherwise falls back to the scalar unrolled path. The dispatch is transparent with no API change required.
275
272
 
276
273
  ---
277
274
 
278
275
  #### `beginDecrypt(key: Uint8Array, nonce: Uint8Array): void`
279
276
 
280
- Initializes the CTR state for decryption. Functionally identical to
281
- `beginEncrypt()` -- CTR mode uses the same operation in both directions.
277
+ Initializes the CTR state for decryption. Functionally identical to `beginEncrypt()`. CTR mode uses the same operation in both directions.
282
278
 
283
- - **key** -- 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
284
- - **nonce** -- exactly 16 bytes. Throws `RangeError` if the length is not 16.
279
+ - **key**: 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
280
+ - **nonce**: exactly 16 bytes. Throws `RangeError` if the length is not 16.
285
281
 
286
282
  ---
287
283
 
@@ -290,8 +286,7 @@ Initializes the CTR state for decryption. Functionally identical to
290
286
  Decrypts a chunk of ciphertext and returns the same-length plaintext.
291
287
  Functionally identical to `encryptChunk()`.
292
288
 
293
- - **chunk** -- any length up to the module's internal chunk buffer size. Throws
294
- `RangeError` if the chunk exceeds the maximum size.
289
+ - **chunk**: any length up to the module's internal chunk buffer size. Throws `RangeError` if the chunk exceeds the maximum size.
295
290
 
296
291
  ---
297
292
 
@@ -308,7 +303,7 @@ Encrypts and decrypts entire messages in a single call.
308
303
 
309
304
  > [!WARNING]
310
305
  > CBC mode is unauthenticated. Always authenticate the output with
311
- > HMAC-SHA256 (Encrypt-then-MAC) or use `SerpentSeal` instead.
306
+ > HMAC-SHA256 (Encrypt-then-MAC) or use `Seal` with `SerpentCipher` instead.
312
307
 
313
308
  ```typescript
314
309
  class SerpentCbc {
@@ -321,11 +316,11 @@ class SerpentCbc {
321
316
 
322
317
  #### `constructor(opts: { dangerUnauthenticated: true })`
323
318
 
324
- Creates a new SerpentCbc instance. Throws if `init(['serpent'])` has not been
319
+ Creates a new SerpentCbc instance. Throws if `init({ serpent: serpentWasm })` has not been
325
320
  called. Throws if `{ dangerUnauthenticated: true }` is not passed:
326
321
 
327
322
  ```
328
- leviathan-crypto: SerpentCbc is unauthenticated — use SerpentSeal instead.
323
+ leviathan-crypto: SerpentCbc is unauthenticated — use Seal with SerpentCipher instead.
329
324
  To use SerpentCbc directly, pass { dangerUnauthenticated: true }.
330
325
  ```
331
326
 
@@ -337,11 +332,9 @@ Encrypts plaintext with Serpent CBC and PKCS7 padding. The returned ciphertext i
337
332
  always a multiple of 16 bytes and is at least 16 bytes longer than the input (due
338
333
  to padding).
339
334
 
340
- - **key** -- 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
341
- - **iv** -- exactly 16 bytes. Must be random and unique for each (key, message)
342
- pair. Throws `RangeError` if the length is not 16.
343
- - **plaintext** -- any length (including zero). PKCS7 padding is applied
344
- automatically.
335
+ - **key**: 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
336
+ - **iv**: exactly 16 bytes. Must be random and unique per (key, message) pair. Throws `RangeError` if the length is not 16.
337
+ - **plaintext**: any length including zero. PKCS7 padding is applied automatically.
345
338
 
346
339
  Returns the ciphertext as a new `Uint8Array`.
347
340
 
@@ -351,21 +344,14 @@ Returns the ciphertext as a new `Uint8Array`.
351
344
 
352
345
  Decrypts Serpent CBC ciphertext and strips PKCS7 padding.
353
346
 
354
- - **key** -- 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
355
- - **iv** -- exactly 16 bytes. Must be the same IV that was used for encryption.
356
- Throws `RangeError` if the length is not 16.
357
- - **ciphertext** -- must be a non-zero multiple of 16 bytes. Throws `RangeError`
358
- if the length is zero or not a multiple of 16. Also throws `RangeError` if PKCS7
359
- padding is invalid (which typically indicates the wrong key, wrong IV, or
360
- corrupted ciphertext).
347
+ - **key**: 16, 24, or 32 bytes. Throws `RangeError` if the length is invalid.
348
+ - **iv**: exactly 16 bytes. Must match the IV used for encryption. Throws `RangeError` if the length is not 16.
349
+ - **ciphertext**: must be a non-zero multiple of 16 bytes. Throws `RangeError` if the length is zero or not a multiple of 16. Also throws if PKCS7 padding is invalid, which typically indicates the wrong key, wrong IV, or corrupted ciphertext.
361
350
 
362
351
  Returns the decrypted plaintext as a new `Uint8Array`.
363
352
 
364
353
  > [!NOTE]
365
- > Automatically dispatches to the 4-wide SIMD path (`cbcDecryptChunk_simd`) when
366
- > the runtime supports WebAssembly SIMD (`hasSIMD()` returns `true`), otherwise
367
- > falls back to the scalar unrolled path. CBC encryption has no SIMD variant —
368
- > each ciphertext block depends on the previous one.
354
+ > Automatically dispatches to the 4-wide SIMD path (`cbcDecryptChunk_simd`) when the runtime supports WebAssembly SIMD (`hasSIMD()` returns `true`), otherwise falls back to the scalar unrolled path. CBC encryption has no SIMD variant since each ciphertext block depends on the previous one.
369
355
 
370
356
  ---
371
357
 
@@ -375,343 +361,40 @@ Wipes all key material and intermediate state from WASM memory.
375
361
 
376
362
  ---
377
363
 
378
- ### SerpentStream
379
-
380
- Chunked authenticated encryption for large payloads. Each chunk is independently
381
- encrypted with Serpent-CTR and authenticated with HMAC-SHA256 using per-chunk
382
- keys derived via HKDF-SHA256. Position binding and truncation detection are
383
- enforced at the key-derivation layer.
384
-
385
- Use `SerpentStream` when the payload is large or when holding the entire
386
- plaintext in memory is undesirable. For small/medium payloads where a single
387
- `encrypt()`/`decrypt()` call is sufficient, use `SerpentSeal` instead.
388
-
389
- > [!NOTE]
390
- > `SerpentStream` takes a 32-byte key (HKDF handles expansion internally).
391
- > This differs from `SerpentSeal`, which takes 64 bytes.
392
-
393
- ```typescript
394
- class SerpentStream {
395
- constructor()
396
- seal(key: Uint8Array, plaintext: Uint8Array, chunkSize?: number): Uint8Array
397
- open(key: Uint8Array, ciphertext: Uint8Array): Uint8Array
398
- dispose(): void
399
- }
400
- ```
401
-
402
- #### `constructor()`
403
-
404
- Creates a new SerpentStream instance. Throws if `init(['serpent', 'sha2'])` has
405
- not been called.
406
-
407
- ---
408
-
409
- #### `seal(key: Uint8Array, plaintext: Uint8Array, chunkSize?: number): Uint8Array`
410
-
411
- Encrypts plaintext into a chunked authenticated wire format.
412
-
413
- - **key** -- exactly 32 bytes. Throws `RangeError` if not.
414
- - **plaintext** -- any length (including zero).
415
- - **chunkSize** -- optional, default 64KB. Valid range: 1KB to 64KB. Throws
416
- `RangeError` if outside range.
417
-
418
- A fresh random stream nonce is generated internally for each call. Two seals of
419
- the same plaintext with the same key produce different output.
420
-
421
- Wire format: `stream_nonce (16) || chunk_size (4, u32_be) || chunk_count (8, u64_be) || chunk_0 || ... || chunk_N-1`
422
-
423
- Each chunk on the wire: `ciphertext || hmac_tag (32 bytes)`.
424
-
425
- ---
426
-
427
- #### `open(key: Uint8Array, ciphertext: Uint8Array): Uint8Array`
428
-
429
- Verifies authentication and decrypts the chunked wire format. Each chunk's MAC
430
- is verified before decryption (Encrypt-then-MAC). If any chunk fails
431
- authentication, `open()` throws immediately and never returns partial plaintext.
432
-
433
- - **key** -- exactly 32 bytes. Must be the same key used for `seal()`.
434
- - **ciphertext** -- the wire format from `seal()`. Throws `RangeError` if too
435
- short.
436
-
437
- ---
438
-
439
- #### `dispose(): void`
440
-
441
- Wipes all key material and intermediate state from WASM memory. Delegates to
442
- internal SerpentCtr, HMAC_SHA256, and HKDF_SHA256 instances.
443
-
444
- **Security properties:**
445
-
446
- - **Per-chunk EtM** -- HMAC-SHA256 over ciphertext, verified before decrypt.
447
- - **Position binding** -- chunk index encoded in HKDF `info`. Reordering chunks
448
- produces wrong keys; MAC fails.
449
- - **Truncation detection** -- final chunk derives different keys than any
450
- intermediate chunk at the same index.
451
- - **Implicit header integrity** -- HKDF `info` embeds the full header. Tampering
452
- with any header field invalidates every chunk's MAC.
453
- - **Domain separation** -- `"serpent-stream-v1"` prefix prevents key confusion
454
- with SerpentSeal or other constructions.
455
-
456
- > [!IMPORTANT]
457
- > This is a bespoke construction (no external RFC). The compositional security
458
- > argument rests on HKDF (RFC 5869), HMAC-EtM, and Serpent-CTR. See
459
- > [sha2.md](./sha2.md) for HKDF details.
460
-
461
- > [!NOTE]
462
- > `sealChunk` and `openChunk` are exported from the serpent submodule for
463
- > internal use by the pool worker. They are not public API -- callers should use
464
- > `SerpentStream` or `SerpentStreamPool`.
465
-
466
- ---
467
-
468
- ### SerpentStreamPool
469
-
470
- Parallel worker pool for `SerpentStream`. Same wire format, same security
471
- properties, faster on multi-core hardware for large payloads. Each worker owns
472
- its own `serpent.wasm` and `sha2.wasm` instances with isolated linear memory.
473
-
474
- `SerpentStream.seal()` and `SerpentStreamPool.seal()` produce compatible wire
475
- formats -- either can decrypt the other's output.
476
-
477
- ```typescript
478
- class SerpentStreamPool {
479
- static async create(opts?: StreamPoolOpts): Promise<SerpentStreamPool>
480
- seal(key: Uint8Array, plaintext: Uint8Array, chunkSize?: number): Promise<Uint8Array>
481
- open(key: Uint8Array, ciphertext: Uint8Array): Promise<Uint8Array>
482
- dispose(): void
483
- get size(): number
484
- get queueDepth(): number
485
- }
486
- ```
487
-
488
- #### `static async create(opts?: StreamPoolOpts): Promise<SerpentStreamPool>`
489
-
490
- Creates a new pool. Requires `init(['serpent', 'sha2'])` to have been called.
491
- Compiles both WASM modules once and distributes them to all workers.
492
-
493
- - **opts.workers** -- number of workers to spawn. Default:
494
- `navigator.hardwareConcurrency ?? 4`.
495
-
496
- Uses a static factory pattern because worker initialization is async (WASM
497
- compilation and instantiation happen per worker).
498
-
499
- ---
500
-
501
- #### `seal(key, plaintext, chunkSize?)`
502
-
503
- Same parameters as `SerpentStream.seal()`, but returns a `Promise`. Key
504
- derivation happens on the main thread; chunk encryption is parallelised across
505
- workers.
506
-
507
- ---
508
-
509
- #### `open(key, ciphertext)`
510
-
511
- Same parameters as `SerpentStream.open()`, but returns a `Promise`. If any chunk
512
- fails authentication, the promise rejects immediately -- no partial plaintext is
513
- returned.
514
-
515
- ---
516
-
517
- #### `dispose()`
518
-
519
- Terminates all workers. Rejects all pending and queued jobs. Must be called to
520
- release worker resources when the pool is no longer needed.
521
-
522
- ---
523
-
524
- ### SerpentStreamSealer / SerpentStreamOpener
525
-
526
- Incremental streaming AEAD — seal and open one chunk at a time without holding
527
- the full message in memory. Unlike `SerpentStream` (which is one-shot),
528
- `SerpentStreamSealer` produces chunks as data arrives and `SerpentStreamOpener`
529
- authenticates and decrypts them individually.
530
-
531
- **Wire format:**
532
- ```
533
- header: nonce (16) || chunkSize_u32be (4) = 20 bytes
534
- chunk: IV (16) || CBC_ciphertext (PKCS7-padded) || HMAC-SHA256 (32)
535
- ```
536
-
537
- Per-chunk keys are derived via HKDF-SHA256 from the stream key and a `chunkInfo`
538
- blob binding the stream nonce, chunk size, chunk index, and `isLast` flag. Each
539
- chunk is independently authenticated and position-bound — reordering, truncation,
540
- and cross-stream splicing are all detected.
541
-
542
- > [!NOTE]
543
- > `SerpentStreamSealer` requires a 64-byte key (same as `SerpentSeal`). HKDF
544
- > derives a fresh `encKey` + `macKey` pair for every chunk.
545
-
546
- > [!IMPORTANT]
547
- > The sealer produces a 20-byte header that **must** be transmitted to the opener
548
- > before any chunks. The opener is initialized with this header.
549
-
550
- ```typescript
551
- class SerpentStreamSealer {
552
- constructor(key: Uint8Array, chunkSize?: number, opts?: { framed?: boolean })
553
- header(): Uint8Array // call once before seal() — returns 20 bytes
554
- seal(plaintext: Uint8Array): Uint8Array // exactly chunkSize bytes
555
- final(plaintext: Uint8Array): Uint8Array // <= chunkSize bytes; wipes on return
556
- dispose(): void // abort mid-stream; wipes without final chunk
557
- }
558
-
559
- class SerpentStreamOpener {
560
- constructor(key: Uint8Array, header: Uint8Array, opts?: { framed?: boolean })
561
- open(chunk: Uint8Array): Uint8Array // throws on auth failure or post-final
562
- feed(bytes: Uint8Array): Uint8Array[] // framed mode only — accumulates and parses frames
563
- dispose(): void
564
- }
565
- ```
566
-
567
- #### Sealer state machine
568
-
569
- | State | Valid calls |
570
- |---|---|
571
- | `fresh` | `header()`, `dispose()` |
572
- | `sealing` | `seal()`, `final()`, `dispose()` |
573
- | `dead` | `dispose()` (no-op) |
574
-
575
- `header()` transitions `fresh → sealing`. `final()` seals the last chunk, wipes
576
- all key material, and transitions to `dead`. `dispose()` wipes and transitions to
577
- `dead` from any state — use it to abort a stream before `final()` is called.
578
-
579
- Calling `header()` twice, `seal()` before `header()`, or any method after `final()`
580
- all throw immediately.
581
-
582
- ---
583
-
584
- #### Opener state machine
585
-
586
- The opener is ready as soon as it is constructed. It calls `open()` for each
587
- chunk in order. Once a chunk with `isLast` set passes authentication, the opener
588
- wipes its key material and transitions to `dead`. Subsequent `open()` calls throw.
589
-
590
- `dispose()` wipes and marks the instance dead from any state.
591
-
592
- ---
593
-
594
- #### `constructor(key, chunkSize?, opts?)`
595
-
596
- - **key** — 64-byte key. Throws `RangeError` if wrong length.
597
- - **chunkSize** — bytes per chunk. Must be 1024–65536. Default: 65536. Throws
598
- `RangeError` if out of range.
599
-
600
- ##### Options (`opts`)
601
-
602
- | Option | Type | Default | Description |
603
- |--------|------|---------|-------------|
604
- | `framed` | `boolean` | `false` | Prepend `u32be(sealedLen)` to each `seal()`/`final()` output. Use for flat byte streams (files, pipes, TCP). Omit when the transport already frames messages (WebSocket, IPC). |
605
-
606
- ---
607
-
608
- #### `header()`
609
-
610
- Returns the 20-byte stream header (`nonce || u32be(chunkSize)`). Must be called
611
- once before the first `seal()`. Throws if called a second time or after `final()`.
612
-
613
- ---
614
-
615
- #### `seal(plaintext)`
616
-
617
- Seals one chunk. **Plaintext must be exactly `chunkSize` bytes.** Returns
618
- `IV (16) || ciphertext || HMAC (32)`. Throws `RangeError` if wrong size. Throws
619
- if called before `header()` or after `final()`.
620
-
621
- ---
622
-
623
- #### `final(plaintext)`
624
-
625
- Seals the last chunk. Plaintext may be 0–`chunkSize` bytes (partial chunk is
626
- valid). After producing output, wipes all key material and marks the sealer dead.
627
- Throws `RangeError` if plaintext exceeds `chunkSize`.
628
-
629
- ---
630
-
631
- #### `dispose()` (sealer)
632
-
633
- Aborts the stream. Wipes key material without producing a final chunk. The opener
634
- will see an incomplete stream and throw when it detects a missing final chunk.
635
- Safe to call after `final()` — no-op if already dead.
636
-
637
- ---
638
-
639
- #### `constructor(key, header, opts?)` (opener)
640
-
641
- - **key** — 64-byte key. Throws `RangeError` if wrong length.
642
- - **header** — 20-byte stream header from `sealer.header()`. Throws `RangeError`
643
- if wrong length.
644
-
645
- ##### Options (`opts`)
646
-
647
- | Option | Type | Default | Description |
648
- |--------|------|---------|-------------|
649
- | `framed` | `boolean` | `false` | Enable byte-accumulation mode. Parses `u32be` length prefixes and dispatches complete frames to `open()` internally. Required to use `feed()`. |
650
-
651
- ---
652
-
653
- #### `open(chunk)`
654
-
655
- Authenticates and decrypts one chunk. Throws `Error` on authentication failure.
656
- Throws `Error` if called after the final chunk has already been opened. Returns
657
- plaintext bytes (PKCS7 padding stripped).
658
-
659
- ---
660
-
661
- #### `feed(bytes: Uint8Array): Uint8Array[]`
662
-
663
- Only callable when constructed with `{ framed: true }`. Accumulates incoming bytes,
664
- parses `u32be` length prefixes, dispatches complete frames to `open()` internally.
665
- Returns an array of decrypted chunks — zero, one, or more per call depending on how
666
- many complete frames were buffered. Throws if called on an unframed opener.
667
-
668
- ---
669
-
670
- #### `dispose()` (opener)
671
-
672
- Wipes key material. Safe to call at any point — use to abort opening a stream
673
- early.
674
-
675
- ---
676
-
677
364
  ## Usage Examples
678
365
 
679
- ### Example 1: SerpentSeal (authenticated encryption)
366
+ ### Example 1: Seal with SerpentCipher (authenticated encryption)
680
367
 
681
368
  ```typescript
682
- import { init, SerpentSeal, randomBytes } from 'leviathan-crypto';
683
-
684
- await init(['serpent', 'sha2']);
685
-
686
- // 64-byte key: 32 bytes encryption + 32 bytes MAC
687
- const key = randomBytes(64);
369
+ import { init, Seal, SerpentCipher } from 'leviathan-crypto'
370
+ import { serpentWasm } from 'leviathan-crypto/serpent/embedded'
371
+ import { sha2Wasm } from 'leviathan-crypto/sha2/embedded'
688
372
 
689
- const seal = new SerpentSeal();
373
+ await init({ serpent: serpentWasm, sha2: sha2Wasm })
690
374
 
691
- const plaintext = new TextEncoder().encode('Authenticated secret message.');
692
- const ciphertext = seal.encrypt(key, plaintext);
693
- const decrypted = seal.decrypt(key, ciphertext);
375
+ const key = SerpentCipher.keygen()
376
+ const plaintext = new TextEncoder().encode('Authenticated secret message.')
377
+ const blob = Seal.encrypt(SerpentCipher, key, plaintext)
378
+ const decrypted = Seal.decrypt(SerpentCipher, key, blob)
694
379
 
695
- console.log(new TextDecoder().decode(decrypted));
380
+ console.log(new TextDecoder().decode(decrypted))
696
381
  // "Authenticated secret message."
697
-
698
- seal.dispose();
699
382
  ```
700
383
 
701
384
  ### Example 2: CTR mode (advanced)
702
385
 
703
- Advanced use. For authenticated encryption, use `SerpentSeal`.
704
-
705
- Use `SerpentCtr` to encrypt data of any length. CTR mode produces ciphertext
706
- that is the same length as the plaintext -- no padding overhead.
386
+ For authenticated encryption, use `Seal` with `SerpentCipher`. Use `SerpentCtr` to
387
+ encrypt data of any length. CTR mode produces ciphertext the same length as the
388
+ plaintext with no padding overhead.
707
389
 
708
390
  ```typescript
709
391
  import { init, SerpentCtr, randomBytes } from 'leviathan-crypto';
392
+ import { serpentWasm } from 'leviathan-crypto/serpent/embedded';
710
393
 
711
- await init(['serpent']);
394
+ await init({ serpent: serpentWasm });
712
395
 
713
396
  const key = randomBytes(32); // 256-bit key
714
- const nonce = randomBytes(16); // 16-byte nonce -- NEVER reuse with the same key
397
+ const nonce = randomBytes(16); // 16-byte nonce, NEVER reuse with the same key
715
398
 
716
399
  const ctr = new SerpentCtr({ dangerUnauthenticated: true });
717
400
 
@@ -734,21 +417,21 @@ ctr.dispose();
734
417
 
735
418
  > [!IMPORTANT]
736
419
  > CTR mode is unauthenticated. An attacker can tamper with the
737
- > ciphertext without detection. Use `SerpentSeal` for authenticated encryption.
420
+ > ciphertext without detection. Use `Seal` with `SerpentCipher` for authenticated encryption.
738
421
 
739
422
  ### Example 3: CBC mode (advanced)
740
423
 
741
- Advanced use. For authenticated encryption, use `SerpentSeal`.
742
-
743
- Use `SerpentCbc` for message-level encryption with automatic PKCS7 padding.
424
+ For authenticated encryption, use `Seal` with `SerpentCipher`. Use `SerpentCbc` for
425
+ message-level encryption with automatic PKCS7 padding.
744
426
 
745
427
  ```typescript
746
428
  import { init, SerpentCbc, randomBytes } from 'leviathan-crypto';
429
+ import { serpentWasm } from 'leviathan-crypto/serpent/embedded';
747
430
 
748
- await init(['serpent']);
431
+ await init({ serpent: serpentWasm });
749
432
 
750
433
  const key = randomBytes(32); // 256-bit key
751
- const iv = randomBytes(16); // Random IV -- must be unique per message
434
+ const iv = randomBytes(16); // Random IV, must be unique per message
752
435
 
753
436
  const cbc = new SerpentCbc({ dangerUnauthenticated: true });
754
437
 
@@ -765,109 +448,18 @@ cbc.dispose();
765
448
  ```
766
449
 
767
450
  > [!IMPORTANT]
768
- > CBC mode is unauthenticated. Use `SerpentSeal` for authenticated encryption.
769
-
770
- ### Example 4: SerpentStream (chunked authenticated encryption)
771
-
772
- Use `SerpentStream` for large payloads where holding the entire plaintext in
773
- memory is undesirable.
774
-
775
- ```typescript
776
- import { init, SerpentStream, randomBytes } from 'leviathan-crypto';
777
-
778
- await init(['serpent', 'sha2']);
779
-
780
- const key = randomBytes(32); // 32-byte key (HKDF handles expansion)
781
-
782
- const stream = new SerpentStream();
783
-
784
- const plaintext = new Uint8Array(1024 * 1024); // 1 MB
785
- crypto.getRandomValues(plaintext);
786
-
787
- const ciphertext = stream.seal(key, plaintext); // default 64KB chunks
788
- const decrypted = stream.open(key, ciphertext);
789
-
790
- // decrypted is byte-identical to plaintext
791
-
792
- stream.dispose();
793
- ```
794
-
795
- ### Example 5: SerpentStreamPool (parallel chunked encryption)
796
-
797
- Use `SerpentStreamPool` for maximum throughput on multi-core hardware.
798
-
799
- ```typescript
800
- import { init, SerpentStreamPool, randomBytes } from 'leviathan-crypto';
801
-
802
- await init(['serpent', 'sha2']);
803
-
804
- const pool = await SerpentStreamPool.create({ workers: 4 });
451
+ > CBC mode is unauthenticated. Use `Seal` with `SerpentCipher` for authenticated encryption.
805
452
 
806
- const key = randomBytes(32);
807
- const plaintext = new Uint8Array(10 * 1024 * 1024); // 10 MB
453
+ ### Example 4: Raw block operations (low-level)
808
454
 
809
- const ciphertext = await pool.seal(key, plaintext);
810
- const decrypted = await pool.open(key, ciphertext);
811
-
812
- // decrypted is byte-identical to plaintext
813
-
814
- pool.dispose(); // terminates workers
815
- ```
816
-
817
- ### Example 6: SerpentStreamSealer / SerpentStreamOpener (incremental streaming)
818
-
819
- Use `SerpentStreamSealer` when data arrives in chunks and you cannot buffer the
820
- entire plaintext before encrypting — network streams, file processors, live feeds.
821
-
822
- ```typescript
823
- import { init, SerpentStreamSealer, SerpentStreamOpener, randomBytes } from 'leviathan-crypto';
824
-
825
- await init(['serpent', 'sha2']);
826
-
827
- const key = randomBytes(64); // 64-byte key
828
- const chunkSize = 65536; // 64 KB chunks
829
-
830
- // ── Seal side ────────────────────────────────────────────────────────────────
831
-
832
- const sealer = new SerpentStreamSealer(key, chunkSize);
833
- const header = sealer.header(); // transmit this to the opener first
834
-
835
- // seal() as data arrives — each chunk must be exactly chunkSize bytes
836
- const chunk0 = sealer.seal(plaintext0);
837
- const chunk1 = sealer.seal(plaintext1);
838
-
839
- // final() for the last chunk — may be shorter than chunkSize
840
- const lastChunk = sealer.final(lastPlaintext);
841
- // sealer is now dead — key material wiped
842
-
843
- // ── Open side ────────────────────────────────────────────────────────────────
844
-
845
- const opener = new SerpentStreamOpener(key, header);
846
-
847
- const pt0 = opener.open(chunk0);
848
- const pt1 = opener.open(chunk1);
849
- const ptN = opener.open(lastChunk); // opener detects isLast, wipes on return
850
- // opener is now dead
851
-
852
- // Truncation and reordering are detected — open() throws on auth failure
853
- ```
854
-
855
- To abort a stream mid-way (e.g. on connection drop):
856
-
857
- ```typescript
858
- sealer.dispose(); // wipes key material without producing a final chunk
859
- // opener will throw when it receives no more chunks
860
- ```
861
-
862
- ### Example 7: Raw block operations (low-level)
863
-
864
- Use the `Serpent` class for single 16-byte block operations. This is the lowest
865
- level API, most users should use `SerpentSeal` instead.
455
+ Use the `Serpent` class for single 16-byte block operations. This is the lowest-level
456
+ API; use `Seal` with `SerpentCipher` for most purposes.
866
457
 
867
458
  ```typescript
868
459
  import { init, Serpent } from 'leviathan-crypto';
460
+ import { serpentWasm } from 'leviathan-crypto/serpent/embedded';
869
461
 
870
- await init(['serpent']);
462
+ await init({ serpent: serpentWasm });
871
463
 
872
464
  const cipher = new Serpent();
873
465
 
@@ -897,13 +489,9 @@ cipher.dispose();
897
489
 
898
490
  | Condition | Error type | Message |
899
491
  |-----------|-----------|---------|
900
- | `SerpentSeal` constructed before `init(['serpent', 'sha2'])` | `Error` | `leviathan-crypto: call init(['serpent', 'sha2']) before using SerpentSeal` |
901
- | `SerpentSeal` key is not 64 bytes | `RangeError` | `SerpentSeal key must be 64 bytes (got N)` |
902
- | `SerpentSeal` data too short for decrypt | `RangeError` | `SerpentSeal ciphertext too short` |
903
- | `SerpentSeal` authentication failed | `Error` | `SerpentSeal: authentication failed` |
904
- | `init(['serpent'])` not called before constructing `Serpent` | `Error` | `leviathan-crypto: call init(['serpent']) before using this class` |
905
- | `SerpentCbc` constructed without `{ dangerUnauthenticated: true }` | `Error` | `leviathan-crypto: SerpentCbc is unauthenticated — use SerpentSeal instead. To use SerpentCbc directly, pass { dangerUnauthenticated: true }.` |
906
- | `SerpentCtr` constructed without `{ dangerUnauthenticated: true }` | `Error` | `leviathan-crypto: SerpentCtr is unauthenticated — use SerpentSeal instead. To use SerpentCtr directly, pass { dangerUnauthenticated: true }.` |
492
+ | `init({ serpent: ... })` not called before constructing `Serpent` | `Error` | `leviathan-crypto: call init({ serpent: ... }) before using this class` |
493
+ | `SerpentCbc` constructed without `{ dangerUnauthenticated: true }` | `Error` | `leviathan-crypto: SerpentCbc is unauthenticated use Seal with SerpentCipher instead. To use SerpentCbc directly, pass { dangerUnauthenticated: true }.` |
494
+ | `SerpentCtr` constructed without `{ dangerUnauthenticated: true }` | `Error` | `leviathan-crypto: SerpentCtr is unauthenticated — use Seal with SerpentCipher instead. To use SerpentCtr directly, pass { dangerUnauthenticated: true }.` |
907
495
  | Key is not 16, 24, or 32 bytes (`Serpent.loadKey`) | `RangeError` | `key must be 16, 24, or 32 bytes (got N)` |
908
496
  | Key is not 16, 24, or 32 bytes (`SerpentCbc`) | `RangeError` | `Serpent key must be 16, 24, or 32 bytes (got N)` |
909
497
  | Key is not 16, 24, or 32 bytes (`SerpentCtr`) | `RangeError` | `key must be 16, 24, or 32 bytes` |
@@ -913,38 +501,19 @@ cipher.dispose();
913
501
  | IV is not 16 bytes (`SerpentCbc`) | `RangeError` | `CBC IV must be 16 bytes (got N)` |
914
502
  | Ciphertext length is zero or not a multiple of 16 (`SerpentCbc.decrypt`) | `RangeError` | `ciphertext length must be a non-zero multiple of 16` |
915
503
  | Invalid PKCS7 padding on decrypt (`SerpentCbc.decrypt`) | `RangeError` | `invalid PKCS7 padding` |
916
- | `SerpentStream` constructed before `init(['serpent', 'sha2'])` | `Error` | `leviathan-crypto: call init(['serpent', 'sha2']) before using SerpentStream` |
917
- | `SerpentStream` key is not 32 bytes | `RangeError` | `SerpentStream key must be 32 bytes (got N)` |
918
- | `SerpentStream` chunkSize out of range | `RangeError` | `SerpentStream chunkSize must be 1024..65536 (got N)` |
919
- | `SerpentStream` ciphertext too short | `RangeError` | `SerpentStream: ciphertext too short` |
920
- | `SerpentStream` authentication failed | `Error` | `SerpentStream: authentication failed` |
921
- | `SerpentStreamPool.create()` before `init(['serpent', 'sha2'])` | `Error` | `leviathan-crypto: call init(['serpent', 'sha2']) before using SerpentStreamPool` |
922
- | `SerpentStreamPool` methods after `dispose()` | `Error` | `leviathan-crypto: pool is disposed` |
923
- | `SerpentStreamSealer` constructed before `init(['serpent', 'sha2'])` | `Error` | `leviathan-crypto: call init(['serpent']) before using SerpentStreamSealer` |
924
- | `SerpentStreamSealer` key is not 64 bytes | `RangeError` | `SerpentStreamSealer key must be 64 bytes (got N)` |
925
- | `SerpentStreamSealer` chunkSize out of range | `RangeError` | `SerpentStreamSealer chunkSize must be 1024..65536 (got N)` |
926
- | `SerpentStreamSealer.header()` called twice | `Error` | `SerpentStreamSealer: header() already called` |
927
- | `SerpentStreamSealer.seal()` before `header()` | `Error` | `SerpentStreamSealer: call header() first` |
928
- | `SerpentStreamSealer.seal()` or `final()` after `final()` or `dispose()` | `Error` | `SerpentStreamSealer: stream is closed` |
929
- | `SerpentStreamSealer.seal()` wrong plaintext size | `RangeError` | `SerpentStreamSealer: seal() requires exactly N bytes (got M)` |
930
- | `SerpentStreamSealer.final()` plaintext exceeds chunkSize | `RangeError` | `SerpentStreamSealer: final() plaintext exceeds chunkSize (got N)` |
931
- | `SerpentStreamOpener` constructed before `init(['serpent', 'sha2'])` | `Error` | `leviathan-crypto: call init(['serpent']) before using SerpentStreamOpener` |
932
- | `SerpentStreamOpener` key is not 64 bytes | `RangeError` | `SerpentStreamOpener key must be 64 bytes (got N)` |
933
- | `SerpentStreamOpener` header is not 20 bytes | `RangeError` | `SerpentStreamOpener header must be 20 bytes (got N)` |
934
- | `SerpentStreamOpener.open()` authentication failed | `Error` | `SerpentStreamOpener: authentication failed` |
935
- | `SerpentStreamOpener.open()` after stream closed | `Error` | `SerpentStreamOpener: stream is closed` |
936
504
 
937
505
  ---
938
506
 
939
507
  > ## Cross-References
940
508
  >
941
509
  > - [index](./README.md) — Project Documentation index
510
+ > - [lexicon](./lexicon.md) — Glossary of cryptographic terms
942
511
  > - [architecture](./architecture.md) — architecture overview, module relationships, buffer layouts, and build pipeline
943
512
  > - [asm_serpent](./asm_serpent.md) — WASM implementation details and buffer layout
944
513
  > - [serpent_reference](./serpent_reference.md) — algorithm specification, S-boxes, linear transform, and known attacks
945
514
  > - [serpent_audit](./serpent_audit.md) — security audit findings (correctness, side-channel analysis)
946
- > - [chacha20](./chacha20.md) — XChaCha20Poly1305 authenticated encryption (alternative AEAD)
947
- > - [sha2](./sha2.md) — HMAC-SHA256 and HKDF used internally by SerpentSeal and SerpentStream
515
+ > - [authenticated encryption](./aead.md) — `Seal`, `SealStream`, `OpenStream`: use `SerpentCipher` as the suite argument
516
+ > - [chacha20](./chacha20.md) — `XChaCha20Cipher`: alternative `CipherSuite` for `Seal` and streaming
517
+ > - [sha2](./sha2.md) — HMAC-SHA256 and HKDF used internally by `SerpentCipher`
948
518
  > - [types](./types.md) — `Blockcipher`, `Streamcipher`, and `AEAD` interfaces implemented by Serpent classes
949
519
  > - [utils](./utils.md) — `constantTimeEqual`, `wipe`, `randomBytes` used by Serpent wrappers
950
-