kxco-post-quantum 1.2.0 → 1.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 - unreleased
4
+
5
+ Adds FIPS 204 / FIPS 205 context string support. Purely additive: the
6
+ cryptographic surface for every existing call site is byte-for-byte unchanged,
7
+ and all 39 pinned vectors still match.
8
+
9
+ ### Added
10
+ - **Optional `context` on `mlDsa.sign` / `mlDsa.verify`** via a trailing options
11
+ object, `{ context }`. At most 255 bytes per FIPS 204 section 5.2; strings are
12
+ encoded as UTF-8. A signature made under a context does not verify without it
13
+ or under a different one. Closes a real incompleteness relative to FIPS 204:
14
+ the library previously could not verify a counterparty's signature that used a
15
+ context.
16
+ - **The same option on `slhDsa.sign` / `slhDsa.verify`**, on the same terms.
17
+ Added alongside ML-DSA rather than after it, because one signature module
18
+ accepting an options object while its sibling silently ignored one would be a
19
+ footgun.
20
+ - `MAX_CONTEXT_BYTES` (255) exported from both modules.
21
+ - `test/context.test.js`, 26 tests, including cross-verification against
22
+ third-party ML-DSA-65 signatures produced by OpenSSL through Python
23
+ `cryptography`, covering five context shapes: short, single-byte, the 255-byte
24
+ maximum, binary, and multi-byte UTF-8.
25
+
26
+ ### Notes
27
+ - **No behaviour change without the new argument.** Omitting `opts` takes the
28
+ identical code path as before. An empty context is collapsed to no context,
29
+ which is what FIPS 204 specifies and what was verified empirically.
30
+ - **Misuse throws rather than returning `false`.** A context over 255 bytes, a
31
+ wrongly typed context, or a bare value passed where an options object belongs
32
+ raises `RangeError` / `TypeError`. These are caller bugs, not failed
33
+ verifications, and swallowing them would hide a signature that silently
34
+ carried no domain separation. No existing call site passes the argument, so
35
+ nothing can regress.
36
+ - Works identically on `@noble/post-quantum` 0.6.1 and 0.7.0, verified on both,
37
+ so this release is independent of the 0.7.0 upgrade.
38
+
39
+ ## 1.2.1 — 2026-07-22
40
+
41
+ Metadata alignment. No code changes; cryptographic surface is byte-for-byte
42
+ identical to `1.2.0` (all 39 pinned vectors match).
43
+
44
+ ### Changed
45
+ - **License now `Apache-2.0`** in package metadata, matching the repository
46
+ LICENSE. `1.2.0` was published declaring `MIT` from a pre-relicense branch;
47
+ this release corrects the published license to the canonical `Apache-2.0`.
48
+ - `author` set to **Shayne Heffernan and John Heffernan**.
49
+ - README security note corrected: `@noble/post-quantum` was **not** in scope
50
+ of Cure53's 2023 `@noble` audit (which covered `ciphers`/`curves`/`hashes`)
51
+ and is maintainer self-audited — the prior "audited by Cure53 (2024)"
52
+ wording was inaccurate. See `AUDIT.md`.
53
+
3
54
  ## 1.2.0 — 2026-07-22
4
55
 
5
56
  Adds SLH-DSA (FIPS 205) and modernises the underlying primitive engine to
package/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Knightsbridge Group — KXCO
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,140 +1,178 @@
1
- # kxco-post-quantum
2
-
3
- Post-quantum cryptography primitives for the KXCO stack.
4
-
5
- [![npm](https://img.shields.io/npm/v/kxco-post-quantum)](https://www.npmjs.com/package/kxco-post-quantum)
6
- [![CI](https://github.com/JackKXCO/kxco-post-quantum/actions/workflows/ci.yml/badge.svg)](https://github.com/JackKXCO/kxco-post-quantum/actions/workflows/ci.yml)
7
- [![license](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
8
-
9
- ML-DSA-65 (FIPS 204) and SLH-DSA-SHA2-192s (FIPS 205) signatures, ML-KEM-768 (FIPS 203) key encapsulation, and key fingerprinting utilities. Wraps [`@noble/post-quantum`](https://github.com/paulmillr/noble-post-quantum) — the NIST reference implementation. All other `kxco-pq-*` packages depend on this one.
10
-
11
- ---
12
-
13
- ## Install
14
-
15
- ```bash
16
- npm install kxco-post-quantum
17
- ```
18
-
19
- Requires Node.js 20.19+. ESM-only.
20
-
21
- ---
22
-
23
- ## Quick start
24
-
25
- ```js
26
- import { mlDsa, mlKem, slhDsa, fingerprint, kidEquals } from 'kxco-post-quantum'
27
-
28
- // ML-DSA-65 — sign and verify
29
- const { publicKey, secretKey } = mlDsa.keypairFromMaster(masterSecret, 'signing-v1')
30
- const sig = mlDsa.sign(secretKey, 'hello')
31
- const ok = mlDsa.verify(publicKey, 'hello', sig) // true
32
-
33
- // SLH-DSA-SHA2-192s — hash-based signatures (same API shape as mlDsa)
34
- const slh = slhDsa.keypairFromMaster(masterSecret, 'signing-v1')
35
- const slhSig = slhDsa.sign(slh.secretKey, 'hello')
36
- const slhOk = slhDsa.verify(slh.publicKey, 'hello', slhSig) // true
37
-
38
- // Key fingerprint
39
- const kid = fingerprint(publicKey) // e.g. '4a7c9e2f1b3d5680'
40
- kidEquals(kid, kid) // true (constant-time)
41
-
42
- // ML-KEM-768 — key encapsulation
43
- const kemKeys = mlKem.keypairFromMaster(masterSecret, 'encryption-v1')
44
- const { ciphertext, sharedSecret } = mlKem.encapsulate(kemKeys.publicKey)
45
- const recovered = mlKem.decapsulate(ciphertext, kemKeys.secretKey)
46
- // sharedSecret and recovered are the same 32 bytes
47
- ```
48
-
49
- `masterSecret` is a `Buffer` or `Uint8Array` with at least 16 bytes of entropy (typically 32–64 bytes from an env var or KMS).
50
-
51
- ---
52
-
53
- ## API
54
-
55
- ### `mlDsa` — ML-DSA-65 (NIST FIPS 204)
56
-
57
- | Export | Signature | Description |
58
- |---|---|---|
59
- | `keypairFromMaster` | `(master, info?) → { publicKey, secretKey }` | Deterministic keypair via HKDF-SHA-512. `info` defaults to `'ml-dsa-65-v1'`. |
60
- | `sign` | `(secretKey, message) → string` | Signs a message. Returns a hex-encoded signature (6618 chars). |
61
- | `verify` | `(publicKey, message, sigHex) → boolean` | Verifies a hex-encoded signature. Returns `false` on any failure. |
62
- | `ml_dsa65` | raw primitive | The underlying `@noble/post-quantum` primitive, re-exported. |
63
-
64
- `publicKey` is 1952 bytes. `secretKey` is 4032 bytes. `message` accepts `Buffer`, `Uint8Array`, or `string`.
65
-
66
- ### `slhDsa` — SLH-DSA-SHA2-192s (NIST FIPS 205)
67
-
68
- Hash-based, stateless signatures. Security Category 3 (matching ML-DSA-65), but security rests only on the SHA-2 hash function — no lattice or number-theoretic assumptions. Use this as a conservative hedge alongside `mlDsa`. Tradeoff: signatures are ~5× larger (16224 vs 3309 bytes) and signing is slower.
69
-
70
- | Export | Signature | Description |
71
- |---|---|---|
72
- | `keypairFromMaster` | `(master, info?) → { publicKey, secretKey }` | Deterministic keypair via HKDF-SHA-512. `info` defaults to `'slh-dsa-sha2-192s-v1'`. |
73
- | `sign` | `(secretKey, message) → string` | Signs a message. Returns a hex-encoded signature (32448 chars). |
74
- | `verify` | `(publicKey, message, sigHex) → boolean` | Verifies a hex-encoded signature. Returns `false` on any failure. |
75
- | `slh_dsa_sha2_192s` | raw primitive | The underlying `@noble/post-quantum` primitive, re-exported. |
76
-
77
- `publicKey` is 48 bytes. `secretKey` is 96 bytes. `message` accepts `Buffer`, `Uint8Array`, or `string`.
78
-
79
- ### `mlKem` — ML-KEM-768 (NIST FIPS 203)
80
-
81
- | Export | Signature | Description |
82
- |---|---|---|
83
- | `keypairFromMaster` | `(master, info?) → { publicKey, secretKey }` | Deterministic keypair via HKDF-SHA-512. `info` defaults to `'ml-kem-768-v1'`. |
84
- | `encapsulate` | `(publicKey) → { ciphertext, sharedSecret }` | Generates a shared secret and ciphertext to send to the key holder. |
85
- | `decapsulate` | `(ciphertext, secretKey) → Buffer` | Recovers the shared secret from a ciphertext. Returns 32 bytes. |
86
- | `ml_kem768` | raw primitive | The underlying `@noble/post-quantum` primitive, re-exported. |
87
-
88
- `publicKey` is 1184 bytes. `ciphertext` is 1088 bytes. `sharedSecret` is 32 bytes.
89
-
90
- ### `fingerprint(publicKey)` → `string`
91
-
92
- First 16 hex characters of SHA-256 of the public key. Stable for the lifetime of the key. Accepts raw bytes or a hex string.
93
-
94
- ### `kidEquals(a, b)` → `boolean`
95
-
96
- Constant-time comparison of two kid strings. Use this when comparing user-supplied input — not `===`.
97
-
98
- ### `deriveSeed(master, info, length)` → `Buffer`
99
-
100
- HKDF-SHA-512 derivation. `master` must be at least 16 bytes. `info` is a required domain-separation string. Returns `length` bytes.
101
-
102
- ### `webhook` — hybrid HMAC + ML-DSA-65 delivery signing
103
-
104
- Low-level helpers for the KXCO hybrid webhook pattern: `envelope`, `hmacHex`, `verifyHmac`, `pqSign`, `verifyPq`, `signDelivery`, `verifyDelivery`. HMAC-SHA-256 gives symmetric verification with no library dependency; ML-DSA-65 adds non-repudiation over the same `${timestamp}.${body}` envelope. The full identity/credential surface lives in `kxco-pq-sdk`.
105
-
106
- ---
107
-
108
- ## What this does NOT do
109
-
110
- - No identity credentials or verifiable claims (those are in `kxco-pq-sdk`)
111
- - No relay, transport, or network layer
112
- - No key storage or KMS integration
113
- - No FIPS 140-3 module validation (the algorithms are FIPS-standardised; the module is not validated)
114
-
115
- ---
116
-
117
- ## Part of the KXCO stack
118
-
119
- `kxco-post-quantum` is the primitive layer. Everything else builds on it:
120
-
121
- - **`kxco-pq-sdk`** — identity credentials, webhook signing, verifiable claims
122
- - Other `kxco-pq-*` packages — domain-specific integrations
123
-
124
- Install this package directly when you need ML-DSA or ML-KEM without the rest of the identity stack.
125
-
126
- ---
127
-
128
- ## Security
129
-
130
- Cryptographic operations delegate entirely to [`@noble/post-quantum`](https://github.com/paulmillr/noble-post-quantum) and [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), audited by Cure53 (2024). This package does not reimplement any NIST primitive.
131
-
132
- To report a vulnerability: [open a private security advisory](https://github.com/JackKXCO/kxco-post-quantum/security/advisories/new) or email **security@kxco.ai**.
133
-
134
- ## License
135
-
136
- MIT. See [LICENSE](./LICENSE).
137
-
138
- ## Maintainers
139
-
140
- Shayne Heffernan and John Heffernan — [KXCO by Knightsbridge](https://kxco.ai)
1
+ # kxco-post-quantum
2
+
3
+ Post-quantum cryptography primitives for the KXCO stack.
4
+
5
+ [![npm](https://img.shields.io/npm/v/kxco-post-quantum)](https://www.npmjs.com/package/kxco-post-quantum)
6
+ [![CI](https://github.com/KnightsbridgeAIQ/kxco-post-quantum/actions/workflows/ci.yml/badge.svg)](https://github.com/KnightsbridgeAIQ/kxco-post-quantum/actions/workflows/ci.yml)
7
+ [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](./LICENSE)
8
+
9
+ ML-DSA-65 (FIPS 204) and SLH-DSA-SHA2-192s (FIPS 205) signatures, ML-KEM-768 (FIPS 203) key encapsulation, and key fingerprinting utilities. Wraps [`@noble/post-quantum`](https://github.com/paulmillr/noble-post-quantum) — the NIST reference implementation. All other `kxco-pq-*` packages depend on this one.
10
+
11
+ ---
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install kxco-post-quantum
17
+ ```
18
+
19
+ Requires Node.js 20.19+. ESM-only.
20
+
21
+ ---
22
+
23
+ ## Quick start
24
+
25
+ ```js
26
+ import { mlDsa, mlKem, slhDsa, fingerprint, kidEquals } from 'kxco-post-quantum'
27
+
28
+ // ML-DSA-65 — sign and verify
29
+ const { publicKey, secretKey } = mlDsa.keypairFromMaster(masterSecret, 'signing-v1')
30
+ const sig = mlDsa.sign(secretKey, 'hello')
31
+ const ok = mlDsa.verify(publicKey, 'hello', sig) // true
32
+
33
+ // SLH-DSA-SHA2-192s — hash-based signatures (same API shape as mlDsa)
34
+ const slh = slhDsa.keypairFromMaster(masterSecret, 'signing-v1')
35
+ const slhSig = slhDsa.sign(slh.secretKey, 'hello')
36
+ const slhOk = slhDsa.verify(slh.publicKey, 'hello', slhSig) // true
37
+
38
+ // Key fingerprint
39
+ const kid = fingerprint(publicKey) // e.g. '4a7c9e2f1b3d5680'
40
+ kidEquals(kid, kid) // true (constant-time)
41
+
42
+ // ML-KEM-768 — key encapsulation
43
+ const kemKeys = mlKem.keypairFromMaster(masterSecret, 'encryption-v1')
44
+ const { ciphertext, sharedSecret } = mlKem.encapsulate(kemKeys.publicKey)
45
+ const recovered = mlKem.decapsulate(ciphertext, kemKeys.secretKey)
46
+ // sharedSecret and recovered are the same 32 bytes
47
+ ```
48
+
49
+ `masterSecret` is a `Buffer` or `Uint8Array` with at least 16 bytes of entropy (typically 32–64 bytes from an env var or KMS).
50
+
51
+ ### Context strings (FIPS 204 / FIPS 205)
52
+
53
+ `sign` and `verify` take an optional context string, at most 255 bytes. A
54
+ signature made under a context does not verify without it, or under a different
55
+ one.
56
+
57
+ ```js
58
+ const sig = mlDsa.sign(secretKey, 'hello', { context: 'kxco-nexus-v1' })
59
+
60
+ mlDsa.verify(publicKey, 'hello', sig, { context: 'kxco-nexus-v1' }) // true
61
+ mlDsa.verify(publicKey, 'hello', sig) // false
62
+ mlDsa.verify(publicKey, 'hello', sig, { context: 'other-v1' }) // false
63
+ ```
64
+
65
+ The parameter is optional and defaults to no context, so every existing call
66
+ site is unaffected. An empty context is identical to omitting it. `slhDsa` takes
67
+ the same option.
68
+
69
+ **Context separates at the signature level; `keypairFromMaster(master, info)`
70
+ separates at the key level.** They are complementary. Use a context when one key
71
+ legitimately signs for several purposes and you need a signature from one
72
+ purpose to be unusable in another. Use a distinct derived key when the purposes
73
+ should not share a key at all.
74
+
75
+ Strings are encoded as UTF-8, so the 255-byte limit is bytes and not
76
+ characters. Over-length or wrongly typed input throws (`RangeError` /
77
+ `TypeError`) rather than returning `false`, because that is a caller bug and not
78
+ a failed verification:
79
+
80
+ ```js
81
+ mlDsa.sign(secretKey, 'hello', 'kxco-nexus-v1') // throws TypeError
82
+ // (needs { context: ... })
83
+ ```
84
+
85
+ That last case is worth guarding: without the throw it would silently sign with
86
+ *no* context and produce a valid-looking signature carrying none of the intended
87
+ separation.
88
+
89
+ ---
90
+
91
+ ## API
92
+
93
+ ### `mlDsa` — ML-DSA-65 (NIST FIPS 204)
94
+
95
+ | Export | Signature | Description |
96
+ |---|---|---|
97
+ | `keypairFromMaster` | `(master, info?) → { publicKey, secretKey }` | Deterministic keypair via HKDF-SHA-512. `info` defaults to `'ml-dsa-65-v1'`. |
98
+ | `sign` | `(secretKey, message) → string` | Signs a message. Returns a hex-encoded signature (6618 chars). |
99
+ | `verify` | `(publicKey, message, sigHex) → boolean` | Verifies a hex-encoded signature. Returns `false` on any failure. |
100
+ | `ml_dsa65` | raw primitive | The underlying `@noble/post-quantum` primitive, re-exported. |
101
+
102
+ `publicKey` is 1952 bytes. `secretKey` is 4032 bytes. `message` accepts `Buffer`, `Uint8Array`, or `string`.
103
+
104
+ ### `slhDsa` — SLH-DSA-SHA2-192s (NIST FIPS 205)
105
+
106
+ Hash-based, stateless signatures. Security Category 3 (matching ML-DSA-65), but security rests only on the SHA-2 hash function — no lattice or number-theoretic assumptions. Use this as a conservative hedge alongside `mlDsa`. Tradeoff: signatures are ~5× larger (16224 vs 3309 bytes) and signing is slower.
107
+
108
+ | Export | Signature | Description |
109
+ |---|---|---|
110
+ | `keypairFromMaster` | `(master, info?) → { publicKey, secretKey }` | Deterministic keypair via HKDF-SHA-512. `info` defaults to `'slh-dsa-sha2-192s-v1'`. |
111
+ | `sign` | `(secretKey, message) → string` | Signs a message. Returns a hex-encoded signature (32448 chars). |
112
+ | `verify` | `(publicKey, message, sigHex) → boolean` | Verifies a hex-encoded signature. Returns `false` on any failure. |
113
+ | `slh_dsa_sha2_192s` | raw primitive | The underlying `@noble/post-quantum` primitive, re-exported. |
114
+
115
+ `publicKey` is 48 bytes. `secretKey` is 96 bytes. `message` accepts `Buffer`, `Uint8Array`, or `string`.
116
+
117
+ ### `mlKem` — ML-KEM-768 (NIST FIPS 203)
118
+
119
+ | Export | Signature | Description |
120
+ |---|---|---|
121
+ | `keypairFromMaster` | `(master, info?) → { publicKey, secretKey }` | Deterministic keypair via HKDF-SHA-512. `info` defaults to `'ml-kem-768-v1'`. |
122
+ | `encapsulate` | `(publicKey) → { ciphertext, sharedSecret }` | Generates a shared secret and ciphertext to send to the key holder. |
123
+ | `decapsulate` | `(ciphertext, secretKey) → Buffer` | Recovers the shared secret from a ciphertext. Returns 32 bytes. |
124
+ | `ml_kem768` | raw primitive | The underlying `@noble/post-quantum` primitive, re-exported. |
125
+
126
+ `publicKey` is 1184 bytes. `ciphertext` is 1088 bytes. `sharedSecret` is 32 bytes.
127
+
128
+ ### `fingerprint(publicKey)` → `string`
129
+
130
+ First 16 hex characters of SHA-256 of the public key. Stable for the lifetime of the key. Accepts raw bytes or a hex string.
131
+
132
+ ### `kidEquals(a, b)` → `boolean`
133
+
134
+ Constant-time comparison of two kid strings. Use this when comparing user-supplied input — not `===`.
135
+
136
+ ### `deriveSeed(master, info, length)` → `Buffer`
137
+
138
+ HKDF-SHA-512 derivation. `master` must be at least 16 bytes. `info` is a required domain-separation string. Returns `length` bytes.
139
+
140
+ ### `webhook` — hybrid HMAC + ML-DSA-65 delivery signing
141
+
142
+ Low-level helpers for the KXCO hybrid webhook pattern: `envelope`, `hmacHex`, `verifyHmac`, `pqSign`, `verifyPq`, `signDelivery`, `verifyDelivery`. HMAC-SHA-256 gives symmetric verification with no library dependency; ML-DSA-65 adds non-repudiation over the same `${timestamp}.${body}` envelope. The full identity/credential surface lives in `kxco-pq-sdk`.
143
+
144
+ ---
145
+
146
+ ## What this does NOT do
147
+
148
+ - No identity credentials or verifiable claims (those are in `kxco-pq-sdk`)
149
+ - No relay, transport, or network layer
150
+ - No key storage or KMS integration
151
+ - No FIPS 140-3 module validation (the algorithms are FIPS-standardised; the module is not validated)
152
+
153
+ ---
154
+
155
+ ## Part of the KXCO stack
156
+
157
+ `kxco-post-quantum` is the primitive layer. Everything else builds on it:
158
+
159
+ - **`kxco-pq-sdk`** — identity credentials, webhook signing, verifiable claims
160
+ - Other `kxco-pq-*` packages — domain-specific integrations
161
+
162
+ Install this package directly when you need ML-DSA or ML-KEM without the rest of the identity stack.
163
+
164
+ ---
165
+
166
+ ## Security
167
+
168
+ Cryptographic operations delegate entirely to [`@noble/post-quantum`](https://github.com/paulmillr/noble-post-quantum) and [`@noble/hashes`](https://github.com/paulmillr/noble-hashes) — this package does not reimplement any NIST primitive. `@noble/hashes` falls under Cure53's 2023 audit of the `@noble` ecosystem (`ciphers`, `curves`, `hashes`); `@noble/post-quantum` was **not** in that audit's scope and has been self-audited by its maintainer. See [AUDIT.md](./AUDIT.md) for the full posture.
169
+
170
+ To report a vulnerability: [open a private security advisory](https://github.com/KnightsbridgeAIQ/kxco-post-quantum/security/advisories/new) or email **john@knightsbridgelaw.com**. Acknowledgement within 2 business days, triage decision within 5. Full policy, including safe harbour for good-faith research: <https://kxco.ai/security>.
171
+
172
+ ## License
173
+
174
+ Apache-2.0. See [LICENSE](./LICENSE).
175
+
176
+ ## Maintainers
177
+
178
+ Shayne Heffernan and John Heffernan — [KXCO by Knightsbridge](https://kxco.ai)
package/SECURITY.md CHANGED
@@ -1,9 +1,22 @@
1
1
  # Security Policy
2
2
 
3
3
  ## Reporting a vulnerability
4
- Email **security@kxco.ai**. Do not open public issues for security reports.
5
- PGP key available on request. We respond within 48 hours and credit reporters
6
- in `CHANGELOG.md` unless they request otherwise.
4
+ Email **john@knightsbridgelaw.com**. Do not open public issues for security reports.
5
+ PGP key available on request. We credit reporters in `CHANGELOG.md` unless they
6
+ request otherwise.
7
+
8
+ Acknowledgement within **2 business days**. Triage decision within **5 business days**.
9
+
10
+ Full policy: <https://kxco.ai/security>
11
+
12
+ ## Safe harbour
13
+ If you make a good-faith effort to comply with this policy, we will treat your
14
+ research as authorised, and we will not pursue or support legal action against
15
+ you. Good faith means: do not access, modify, exfiltrate, or destroy data that
16
+ is not yours; use test accounts where possible; do not degrade service for
17
+ others; and stop and report as soon as you have established that a
18
+ vulnerability exists. This cannot bind third parties, and it does not cover
19
+ extortion, data sale, or public disclosure ahead of the window below.
7
20
 
8
21
  ## Scope
9
22
  In scope:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kxco-post-quantum",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "ML-DSA-65, ML-KEM-768 and SLH-DSA-SHA2-192s primitives with key fingerprinting. The base layer for all kxco-pq-* packages.",
5
5
  "keywords": [
6
6
  "post-quantum",
@@ -23,12 +23,11 @@
23
23
  "deterministic-keys",
24
24
  "fingerprint",
25
25
  "replay-protection",
26
- "constant-time",
27
26
  "hybrid-signing",
28
27
  "non-repudiation"
29
28
  ],
30
- "license": "MIT",
31
- "author": "KXCO by Knightsbridge <hello@kxco.ai>",
29
+ "license": "Apache-2.0",
30
+ "author": "Shayne Heffernan and John Heffernan",
32
31
  "contributors": [
33
32
  {
34
33
  "name": "Shayne Heffernan"
@@ -41,10 +40,10 @@
41
40
  "funding": "https://kxco.ai",
42
41
  "repository": {
43
42
  "type": "git",
44
- "url": "https://github.com/JackKXCO/kxco-post-quantum.git"
43
+ "url": "https://github.com/KnightsbridgeAIQ/kxco-post-quantum.git"
45
44
  },
46
45
  "bugs": {
47
- "url": "https://github.com/JackKXCO/kxco-post-quantum/issues"
46
+ "url": "https://github.com/KnightsbridgeAIQ/kxco-post-quantum/issues"
48
47
  },
49
48
  "type": "module",
50
49
  "sideEffects": false,
@@ -91,11 +90,11 @@
91
90
  "node": ">=20.19"
92
91
  },
93
92
  "dependencies": {
94
- "@noble/hashes": "^2.2.0",
95
- "@noble/post-quantum": "^0.6.1"
93
+ "@noble/hashes": "2.3.0",
94
+ "@noble/post-quantum": "0.7.0"
96
95
  },
97
96
  "scripts": {
98
- "test": "node --test test/basic.test.js && node --test test/browser-smoke.test.js && node test/run-vectors.js",
97
+ "test": "node --test test/basic.test.js && node --test test/context.test.js && node --test test/browser-smoke.test.js && node test/run-vectors.js",
99
98
  "test:vectors": "node test/run-vectors.js",
100
99
  "generate:vectors": "node test/generate-vectors.js > test/vectors.json",
101
100
  "bench": "node bench/bench.js"
@@ -0,0 +1,69 @@
1
+ // Internal: FIPS 204 / FIPS 205 signature context strings.
2
+ //
3
+ // Not part of the public exports map. Shared by ml-dsa.js and slh-dsa.js
4
+ // because a validator for security-relevant input should exist once, even
5
+ // though the small byte/hex helpers in those modules are duplicated.
6
+ //
7
+ // FIPS 204 section 5.2 (and FIPS 205 equivalently) allow an optional context
8
+ // string of at most 255 bytes, mixed into the message representative. It gives
9
+ // domain separation: a signature made under one context does not verify under
10
+ // another, or under no context at all.
11
+ //
12
+ // KXCO derives keys per domain via deriveSeed(master, info), which separates at
13
+ // the KEY level. Context separates at the SIGNATURE level, so one key can sign
14
+ // for several domains without a signature being replayable across them. The two
15
+ // are complementary, not alternatives.
16
+
17
+ const enc = new TextEncoder()
18
+
19
+ /** FIPS 204 section 5.2: |ctx| <= 255. */
20
+ export const MAX_CONTEXT_BYTES = 255
21
+
22
+ /**
23
+ * Normalise the options bag into a context byte string, or undefined.
24
+ *
25
+ * Returns undefined for "no context", which makes the caller take the exact
26
+ * code path it took before this parameter existed. An empty context is
27
+ * cryptographically identical to no context, so it also returns undefined
28
+ * rather than passing a zero-length array down.
29
+ *
30
+ * THROWS on caller misuse (wrong type, over-length). This is deliberate and it
31
+ * differs from verify()'s usual fail-closed behaviour: a malformed context is a
32
+ * programming error, not a bad signature, and silently returning false would
33
+ * hide the bug behind an outcome that looks like a normal verification failure.
34
+ * No existing call site passes this argument, so nothing can regress.
35
+ *
36
+ * @param {{ context?: Uint8Array|Buffer|string }} [opts]
37
+ * @returns {Uint8Array|undefined}
38
+ */
39
+ export function normalizeContext(opts) {
40
+ if (opts === undefined || opts === null) return undefined
41
+
42
+ if (typeof opts !== 'object' || Array.isArray(opts) || opts instanceof Uint8Array) {
43
+ throw new TypeError(
44
+ 'expected an options object such as { context }, not a bare value',
45
+ )
46
+ }
47
+
48
+ const { context } = opts
49
+ if (context === undefined || context === null) return undefined
50
+
51
+ let bytes
52
+ if (context instanceof Uint8Array) {
53
+ bytes = context
54
+ } else if (typeof context === 'string') {
55
+ bytes = enc.encode(context)
56
+ } else {
57
+ throw new TypeError('context must be a Uint8Array or a string')
58
+ }
59
+
60
+ if (bytes.length > MAX_CONTEXT_BYTES) {
61
+ throw new RangeError(
62
+ `context must be at most ${MAX_CONTEXT_BYTES} bytes (FIPS 204 section 5.2), got ${bytes.length}`,
63
+ )
64
+ }
65
+
66
+ // Empty context is identical to no context under FIPS 204, so collapse it
67
+ // and keep the legacy call path byte-for-byte.
68
+ return bytes.length === 0 ? undefined : bytes
69
+ }
package/src/index.js CHANGED
@@ -1,17 +1,17 @@
1
- // @kxco/post-quantum
2
- //
3
- // Production-tested post-quantum cryptography patterns: deterministic key
4
- // derivation, hybrid HMAC + ML-DSA webhook signing, kid fingerprinting.
5
- // Built on @noble/post-quantum. Used in production at KXCO across
6
- // KnightsVault, KXCO Bank, KnightsBot, The Exchequer, and Armature L1.
7
- //
8
- // This package does NOT reimplement the NIST primitives. It wraps the
9
- // audited @noble/post-quantum reference implementation with the integration
10
- // patterns we have proven in production.
11
-
12
- export * as mlDsa from './ml-dsa.js'
13
- export * as mlKem from './ml-kem.js'
14
- export * as slhDsa from './slh-dsa.js'
15
- export * from './derive.js'
16
- export * from './kid.js'
17
- export * as webhook from './webhook.js'
1
+ // @kxco/post-quantum
2
+ //
3
+ // Production-tested post-quantum cryptography patterns: deterministic key
4
+ // derivation, hybrid HMAC + ML-DSA webhook signing, kid fingerprinting.
5
+ // Built on @noble/post-quantum. Used in production at KXCO across
6
+ // KnightsVault, KXCO Bank, KnightsBot, The Exchequer, and Armature L1.
7
+ //
8
+ // This package does NOT reimplement the NIST primitives. It wraps the
9
+ // audited @noble/post-quantum reference implementation with the integration
10
+ // patterns we have proven in production.
11
+
12
+ export * as mlDsa from './ml-dsa.js'
13
+ export * as mlKem from './ml-kem.js'
14
+ export * as slhDsa from './slh-dsa.js'
15
+ export * from './derive.js'
16
+ export * from './kid.js'
17
+ export * as webhook from './webhook.js'
package/src/ml-dsa.d.ts CHANGED
@@ -18,23 +18,56 @@ export function keypairFromMaster(
18
18
  info?: string,
19
19
  ): MlDsaKeypair
20
20
 
21
+ /** Maximum context length in bytes (FIPS 204 section 5.2). */
22
+ export const MAX_CONTEXT_BYTES: 255
23
+
24
+ export interface SignatureOptions {
25
+ /**
26
+ * Optional FIPS 204 section 5.2 context string, at most 255 bytes.
27
+ * Strings are encoded as UTF-8.
28
+ *
29
+ * Gives domain separation at the signature level: a signature made under a
30
+ * context does not verify without it, or under a different one. An empty
31
+ * context is identical to omitting it.
32
+ *
33
+ * Complements `keypairFromMaster(master, info)`, which separates domains at
34
+ * the key level.
35
+ */
36
+ context?: Buffer | Uint8Array | string
37
+ }
38
+
21
39
  /**
22
40
  * Sign a message under an ML-DSA-65 secret key. Returns the signature
23
41
  * as a hex string (3309 bytes = 6618 hex characters).
42
+ *
43
+ * @throws {TypeError} if `opts` is not an options object, or `context` is
44
+ * neither a string nor a Uint8Array
45
+ * @throws {RangeError} if `context` exceeds 255 bytes
24
46
  */
25
47
  export function sign(
26
48
  secretKey: Buffer | Uint8Array,
27
- message: Buffer | string,
49
+ message: Buffer | Uint8Array | string,
50
+ opts?: SignatureOptions,
28
51
  ): string
29
52
 
30
53
  /**
31
54
  * Verify a hex-encoded ML-DSA-65 signature against a public key + message.
32
- * Returns `false` on any error (invalid hex, wrong length, mismatch).
55
+ *
56
+ * Returns `false` on any cryptographic failure (invalid hex, wrong length,
57
+ * mismatch, or a missing/incorrect context).
58
+ *
59
+ * Throws only on caller misuse of `opts`, which is a programming error rather
60
+ * than a failed verification and is not swallowed.
61
+ *
62
+ * @throws {TypeError} if `opts` is not an options object, or `context` is
63
+ * neither a string nor a Uint8Array
64
+ * @throws {RangeError} if `context` exceeds 255 bytes
33
65
  */
34
66
  export function verify(
35
67
  publicKey: Buffer | Uint8Array,
36
- message: Buffer | string,
68
+ message: Buffer | Uint8Array | string,
37
69
  sigHex: string,
70
+ opts?: SignatureOptions,
38
71
  ): boolean
39
72
 
40
73
  /**
package/src/ml-dsa.js CHANGED
@@ -8,6 +8,9 @@
8
8
 
9
9
  import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js'
10
10
  import { deriveSeed } from './derive.js'
11
+ import { normalizeContext, MAX_CONTEXT_BYTES } from './_context.js'
12
+
13
+ export { MAX_CONTEXT_BYTES }
11
14
 
12
15
  const HAS_BUFFER = typeof Buffer !== 'undefined'
13
16
  const enc = new TextEncoder()
@@ -50,26 +53,47 @@ export function keypairFromMaster(master, info = 'ml-dsa-65-v1') {
50
53
  /**
51
54
  * Sign a message. Returns the signature as a hex string.
52
55
  *
56
+ * An optional FIPS 204 section 5.2 context string gives domain separation: a
57
+ * signature made under a context does not verify without it. Omit it and the
58
+ * behaviour is exactly as before this parameter existed.
59
+ *
53
60
  * @param {Buffer|Uint8Array} secretKey
54
61
  * @param {Buffer|Uint8Array|string} message
62
+ * @param {{ context?: Uint8Array|Buffer|string }} [opts] at most 255 context bytes
55
63
  * @returns {string} hex-encoded signature (6618 chars)
56
64
  */
57
- export function sign(secretKey, message) {
58
- const sig = ml_dsa65.sign(toBytes(message), secretKey)
65
+ export function sign(secretKey, message, opts) {
66
+ const context = normalizeContext(opts)
67
+ const sig = context === undefined
68
+ ? ml_dsa65.sign(toBytes(message), secretKey)
69
+ : ml_dsa65.sign(toBytes(message), secretKey, { context })
59
70
  return bytesToHex(sig)
60
71
  }
61
72
 
62
73
  /**
63
74
  * Verify a hex-encoded signature.
64
75
  *
76
+ * Pass the same context the signer used. A signature made under a context
77
+ * returns false here if the context is omitted or differs, which is the point
78
+ * of it.
79
+ *
80
+ * Returns false for any cryptographic failure. Throws only on caller misuse of
81
+ * `opts` (wrong type, or a context over 255 bytes), because that is a bug
82
+ * rather than a failed verification and should not be silently swallowed.
83
+ *
65
84
  * @param {Buffer|Uint8Array} publicKey
66
85
  * @param {Buffer|Uint8Array|string} message
67
86
  * @param {string} sigHex
87
+ * @param {{ context?: Uint8Array|Buffer|string }} [opts]
68
88
  * @returns {boolean}
69
89
  */
70
- export function verify(publicKey, message, sigHex) {
90
+ export function verify(publicKey, message, sigHex, opts) {
91
+ // Outside the try: misuse must surface, not be swallowed as "invalid".
92
+ const context = normalizeContext(opts)
71
93
  try {
72
- return ml_dsa65.verify(hexToBytes(sigHex), toBytes(message), publicKey)
94
+ return context === undefined
95
+ ? ml_dsa65.verify(hexToBytes(sigHex), toBytes(message), publicKey)
96
+ : ml_dsa65.verify(hexToBytes(sigHex), toBytes(message), publicKey, { context })
73
97
  } catch {
74
98
  return false
75
99
  }
package/src/slh-dsa.d.ts CHANGED
@@ -1,46 +1,72 @@
1
- /// <reference types="node" />
2
-
3
- export interface SlhDsaKeypair {
4
- /** 48-byte public key */
5
- publicKey: Buffer
6
- /** 96-byte secret key */
7
- secretKey: Buffer
8
- }
9
-
10
- /**
11
- * Generate an SLH-DSA-SHA2-192s (NIST FIPS 205) keypair deterministically
12
- * from a master + domain-separation info string.
13
- *
14
- * Same inputs always produce the same keypair — no state, no DB row.
15
- * Security Category 3, matching ML-DSA-65.
16
- */
17
- export function keypairFromMaster(
18
- master: Buffer | Uint8Array,
19
- info?: string,
20
- ): SlhDsaKeypair
21
-
22
- /**
23
- * Sign a message under an SLH-DSA-SHA2-192s secret key. Returns the signature
24
- * as a hex string (16224 bytes = 32448 hex characters).
25
- */
26
- export function sign(
27
- secretKey: Buffer | Uint8Array,
28
- message: Buffer | string,
29
- ): string
30
-
31
- /**
32
- * Verify a hex-encoded SLH-DSA-SHA2-192s signature against a public key +
33
- * message. Returns `false` on any error (invalid hex, wrong length, mismatch).
34
- */
35
- export function verify(
36
- publicKey: Buffer | Uint8Array,
37
- message: Buffer | string,
38
- sigHex: string,
39
- ): boolean
40
-
41
- /**
42
- * Raw `@noble/post-quantum` SLH-DSA-SHA2-192s primitive, re-exported for
43
- * callers who want the lower-level API. The wrapper functions above are
44
- * recommended for production use.
45
- */
46
- export const slh_dsa_sha2_192s: typeof import('@noble/post-quantum/slh-dsa.js').slh_dsa_sha2_192s
1
+ /// <reference types="node" />
2
+
3
+ export interface SlhDsaKeypair {
4
+ /** 48-byte public key */
5
+ publicKey: Buffer
6
+ /** 96-byte secret key */
7
+ secretKey: Buffer
8
+ }
9
+
10
+ /**
11
+ * Generate an SLH-DSA-SHA2-192s (NIST FIPS 205) keypair deterministically
12
+ * from a master + domain-separation info string.
13
+ *
14
+ * Same inputs always produce the same keypair — no state, no DB row.
15
+ * Security Category 3, matching ML-DSA-65.
16
+ */
17
+ export function keypairFromMaster(
18
+ master: Buffer | Uint8Array,
19
+ info?: string,
20
+ ): SlhDsaKeypair
21
+
22
+ /** Maximum context length in bytes (FIPS 205, matching FIPS 204). */
23
+ export const MAX_CONTEXT_BYTES: 255
24
+
25
+ export interface SignatureOptions {
26
+ /**
27
+ * Optional context string, at most 255 bytes. Strings are encoded as UTF-8.
28
+ * A signature made under a context does not verify without it. An empty
29
+ * context is identical to omitting it.
30
+ */
31
+ context?: Buffer | Uint8Array | string
32
+ }
33
+
34
+ /**
35
+ * Sign a message under an SLH-DSA-SHA2-192s secret key. Returns the signature
36
+ * as a hex string (16224 bytes = 32448 hex characters).
37
+ *
38
+ * @throws {TypeError} if `opts` is not an options object, or `context` is
39
+ * neither a string nor a Uint8Array
40
+ * @throws {RangeError} if `context` exceeds 255 bytes
41
+ */
42
+ export function sign(
43
+ secretKey: Buffer | Uint8Array,
44
+ message: Buffer | Uint8Array | string,
45
+ opts?: SignatureOptions,
46
+ ): string
47
+
48
+ /**
49
+ * Verify a hex-encoded SLH-DSA-SHA2-192s signature against a public key +
50
+ * message.
51
+ *
52
+ * Returns `false` on any cryptographic failure (invalid hex, wrong length,
53
+ * mismatch, or a missing/incorrect context). Throws only on caller misuse of
54
+ * `opts`.
55
+ *
56
+ * @throws {TypeError} if `opts` is not an options object, or `context` is
57
+ * neither a string nor a Uint8Array
58
+ * @throws {RangeError} if `context` exceeds 255 bytes
59
+ */
60
+ export function verify(
61
+ publicKey: Buffer | Uint8Array,
62
+ message: Buffer | Uint8Array | string,
63
+ sigHex: string,
64
+ opts?: SignatureOptions,
65
+ ): boolean
66
+
67
+ /**
68
+ * Raw `@noble/post-quantum` SLH-DSA-SHA2-192s primitive, re-exported for
69
+ * callers who want the lower-level API. The wrapper functions above are
70
+ * recommended for production use.
71
+ */
72
+ export const slh_dsa_sha2_192s: typeof import('@noble/post-quantum/slh-dsa.js').slh_dsa_sha2_192s
package/src/slh-dsa.js CHANGED
@@ -1,88 +1,106 @@
1
- // SLH-DSA-SHA2-192s helpers (NIST FIPS 205, SPHINCS+).
2
- //
3
- // Stateless hash-based signatures. Security Category 3 (≈ AES-192), matching
4
- // ML-DSA-65's security level. Public key 48 bytes, secret key 96 bytes,
5
- // signature 16224 bytes. Security rests only on the SHA-2 hash function — no
6
- // lattice or number-theoretic assumptions — which makes it the conservative
7
- // hedge alongside ML-DSA-65.
8
- //
9
- // Tradeoff: signatures are ~5x larger than ML-DSA-65 (16224 vs 3309 bytes) and
10
- // signing is slower. Use ML-DSA-65 as the default; reach for SLH-DSA when you
11
- // want a signature whose security does not depend on lattice hardness.
12
- //
13
- // Isomorphic: works in Node and modern browsers. Returns Buffer on Node
14
- // (consistent with ml-dsa.js), Uint8Array in browsers.
15
-
16
- import { slh_dsa_sha2_192s } from '@noble/post-quantum/slh-dsa.js'
17
- import { deriveSeed } from './derive.js'
18
-
19
- const HAS_BUFFER = typeof Buffer !== 'undefined'
20
- const enc = new TextEncoder()
21
-
22
- function toBytes(input) {
23
- if (input instanceof Uint8Array) return input
24
- if (typeof input === 'string') return enc.encode(input)
25
- throw new Error('expected Uint8Array or string')
26
- }
27
- function hexToBytes(hex) {
28
- if (typeof hex !== 'string' || hex.length % 2) throw new Error('invalid hex')
29
- const b = new Uint8Array(hex.length / 2)
30
- for (let i = 0; i < b.length; i++) b[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)
31
- return b
32
- }
33
- function bytesToHex(bytes) {
34
- let s = ''
35
- for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, '0')
36
- return s
37
- }
38
- function wrap(bytes) {
39
- return HAS_BUFFER ? Buffer.from(bytes) : bytes
40
- }
41
-
42
- // Seed length for SLH-DSA-SHA2-192s keygen (FIPS 205: SK.seed || SK.prf || PK.seed).
43
- const SEED_BYTES = slh_dsa_sha2_192s.lengths.seed
44
-
45
- /**
46
- * Generate an SLH-DSA-SHA2-192s keypair from a master + domain-separation info.
47
- *
48
- * @returns {{ publicKey: Buffer|Uint8Array, secretKey: Buffer|Uint8Array }}
49
- */
50
- export function keypairFromMaster(master, info = 'slh-dsa-sha2-192s-v1') {
51
- const seed = deriveSeed(master, info, SEED_BYTES)
52
- const seedU8 = seed instanceof Uint8Array ? seed : new Uint8Array(seed)
53
- const k = slh_dsa_sha2_192s.keygen(seedU8)
54
- return {
55
- publicKey: wrap(k.publicKey),
56
- secretKey: wrap(k.secretKey),
57
- }
58
- }
59
-
60
- /**
61
- * Sign a message. Returns the signature as a hex string.
62
- *
63
- * @param {Buffer|Uint8Array} secretKey
64
- * @param {Buffer|Uint8Array|string} message
65
- * @returns {string} hex-encoded signature (32448 chars)
66
- */
67
- export function sign(secretKey, message) {
68
- const sig = slh_dsa_sha2_192s.sign(toBytes(message), secretKey)
69
- return bytesToHex(sig)
70
- }
71
-
72
- /**
73
- * Verify a hex-encoded signature.
74
- *
75
- * @param {Buffer|Uint8Array} publicKey
76
- * @param {Buffer|Uint8Array|string} message
77
- * @param {string} sigHex
78
- * @returns {boolean}
79
- */
80
- export function verify(publicKey, message, sigHex) {
81
- try {
82
- return slh_dsa_sha2_192s.verify(hexToBytes(sigHex), toBytes(message), publicKey)
83
- } catch {
84
- return false
85
- }
86
- }
87
-
88
- export { slh_dsa_sha2_192s }
1
+ // SLH-DSA-SHA2-192s helpers (NIST FIPS 205, SPHINCS+).
2
+ //
3
+ // Stateless hash-based signatures. Security Category 3 (≈ AES-192), matching
4
+ // ML-DSA-65's security level. Public key 48 bytes, secret key 96 bytes,
5
+ // signature 16224 bytes. Security rests only on the SHA-2 hash function — no
6
+ // lattice or number-theoretic assumptions — which makes it the conservative
7
+ // hedge alongside ML-DSA-65.
8
+ //
9
+ // Tradeoff: signatures are ~5x larger than ML-DSA-65 (16224 vs 3309 bytes) and
10
+ // signing is slower. Use ML-DSA-65 as the default; reach for SLH-DSA when you
11
+ // want a signature whose security does not depend on lattice hardness.
12
+ //
13
+ // Isomorphic: works in Node and modern browsers. Returns Buffer on Node
14
+ // (consistent with ml-dsa.js), Uint8Array in browsers.
15
+
16
+ import { slh_dsa_sha2_192s } from '@noble/post-quantum/slh-dsa.js'
17
+ import { deriveSeed } from './derive.js'
18
+ import { normalizeContext, MAX_CONTEXT_BYTES } from './_context.js'
19
+
20
+ export { MAX_CONTEXT_BYTES }
21
+
22
+ const HAS_BUFFER = typeof Buffer !== 'undefined'
23
+ const enc = new TextEncoder()
24
+
25
+ function toBytes(input) {
26
+ if (input instanceof Uint8Array) return input
27
+ if (typeof input === 'string') return enc.encode(input)
28
+ throw new Error('expected Uint8Array or string')
29
+ }
30
+ function hexToBytes(hex) {
31
+ if (typeof hex !== 'string' || hex.length % 2) throw new Error('invalid hex')
32
+ const b = new Uint8Array(hex.length / 2)
33
+ for (let i = 0; i < b.length; i++) b[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)
34
+ return b
35
+ }
36
+ function bytesToHex(bytes) {
37
+ let s = ''
38
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, '0')
39
+ return s
40
+ }
41
+ function wrap(bytes) {
42
+ return HAS_BUFFER ? Buffer.from(bytes) : bytes
43
+ }
44
+
45
+ // Seed length for SLH-DSA-SHA2-192s keygen (FIPS 205: SK.seed || SK.prf || PK.seed).
46
+ const SEED_BYTES = slh_dsa_sha2_192s.lengths.seed
47
+
48
+ /**
49
+ * Generate an SLH-DSA-SHA2-192s keypair from a master + domain-separation info.
50
+ *
51
+ * @returns {{ publicKey: Buffer|Uint8Array, secretKey: Buffer|Uint8Array }}
52
+ */
53
+ export function keypairFromMaster(master, info = 'slh-dsa-sha2-192s-v1') {
54
+ const seed = deriveSeed(master, info, SEED_BYTES)
55
+ const seedU8 = seed instanceof Uint8Array ? seed : new Uint8Array(seed)
56
+ const k = slh_dsa_sha2_192s.keygen(seedU8)
57
+ return {
58
+ publicKey: wrap(k.publicKey),
59
+ secretKey: wrap(k.secretKey),
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Sign a message. Returns the signature as a hex string.
65
+ *
66
+ * Accepts the same optional context string as ml-dsa.js (FIPS 205 allows it on
67
+ * the same terms as FIPS 204, at most 255 bytes). Omit it and the behaviour is
68
+ * exactly as before this parameter existed.
69
+ *
70
+ * @param {Buffer|Uint8Array} secretKey
71
+ * @param {Buffer|Uint8Array|string} message
72
+ * @param {{ context?: Uint8Array|Buffer|string }} [opts] at most 255 context bytes
73
+ * @returns {string} hex-encoded signature (32448 chars)
74
+ */
75
+ export function sign(secretKey, message, opts) {
76
+ const context = normalizeContext(opts)
77
+ const sig = context === undefined
78
+ ? slh_dsa_sha2_192s.sign(toBytes(message), secretKey)
79
+ : slh_dsa_sha2_192s.sign(toBytes(message), secretKey, { context })
80
+ return bytesToHex(sig)
81
+ }
82
+
83
+ /**
84
+ * Verify a hex-encoded signature.
85
+ *
86
+ * Pass the same context the signer used. Returns false for any cryptographic
87
+ * failure; throws only on caller misuse of `opts`.
88
+ *
89
+ * @param {Buffer|Uint8Array} publicKey
90
+ * @param {Buffer|Uint8Array|string} message
91
+ * @param {string} sigHex
92
+ * @param {{ context?: Uint8Array|Buffer|string }} [opts]
93
+ * @returns {boolean}
94
+ */
95
+ export function verify(publicKey, message, sigHex, opts) {
96
+ const context = normalizeContext(opts)
97
+ try {
98
+ return context === undefined
99
+ ? slh_dsa_sha2_192s.verify(hexToBytes(sigHex), toBytes(message), publicKey)
100
+ : slh_dsa_sha2_192s.verify(hexToBytes(sigHex), toBytes(message), publicKey, { context })
101
+ } catch {
102
+ return false
103
+ }
104
+ }
105
+
106
+ export { slh_dsa_sha2_192s }