bitspark-archon-core 0.7.0__tar.gz

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.
@@ -0,0 +1,202 @@
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.
@@ -0,0 +1,4 @@
1
+ archon
2
+ Copyright 2026 Bitspark and the archon contributors
3
+
4
+ This product includes software developed at Bitspark (https://github.com/Bitspark).
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: bitspark-archon-core
3
+ Version: 0.7.0
4
+ Summary: archon core: Ed25519 primitives, the canonical key spelling, and the SPKI/PKCS-8 key codec. The identity floor beneath the law.
5
+ Author: Bitspark
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Bitspark/archon
8
+ Project-URL: Documentation, https://github.com/Bitspark/archon/tree/main/docs
9
+ Project-URL: Repository, https://github.com/Bitspark/archon
10
+ Project-URL: Issues, https://github.com/Bitspark/archon/issues
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Security :: Cryptography
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE
21
+ Requires-Dist: pycryptodome>=3.20
22
+ Dynamic: license-file
23
+
24
+ # archon core — Python
25
+
26
+ The identity floor in Python: Ed25519 key bytes, one canonical text spelling, the SPKI and
27
+ PKCS-8 codecs, and domain-separated signing.
28
+
29
+ ```console
30
+ pip install bitspark-archon-core
31
+ ```
32
+
33
+ The distribution is `bitspark-archon-core`; the import is `archon_core`. The prefix is a
34
+ registry name only — PyPI, like crates.io, has a single flat namespace.
35
+
36
+ ```python
37
+ from archon_core import (
38
+ public_key_from_seed, encode_key, sign_in_domain, verify_in_domain,
39
+ )
40
+
41
+ seed = bytes(range(32))
42
+ pub = public_key_from_seed(seed)
43
+
44
+ encode_key(pub)
45
+ # 'ed25519:03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8'
46
+
47
+ sig = sign_in_domain(seed, "example.v1", b"hello")
48
+ verify_in_domain(pub, "example.v1", b"hello", sig) # True
49
+ verify_in_domain(pub, "other.v1", b"hello", sig) # False — domains do not cross
50
+ ```
51
+
52
+ ## What it is
53
+
54
+ Two questions and no others: *are these bytes that key*, and *is this signature that key's*.
55
+ Authority and custody belong to their own layers — see the
56
+ [repository README](https://github.com/Bitspark/archon).
57
+
58
+ | | |
59
+ |---|---|
60
+ | `crypto` | `public_key_from_seed`, `sign`/`verify`, `sign_in_domain`/`verify_in_domain` |
61
+ | `hexbytes` | `to_hex`, and fixed-size decoders that accept exactly N bytes or fail |
62
+ | `keytext` | `encode_key`/`decode_key` — `ed25519:<64 hex>` |
63
+ | `keycodec` | RFC 5280 SPKI and RFC 5958 PKCS-8 v1 PEM, as a byte codec |
64
+
65
+ ## Agreement is the claim
66
+
67
+ This core is held to the same hand-authored oracle as the Go, Rust and TypeScript cores —
68
+ 60 cases in [`vectors/identity.json`](https://github.com/Bitspark/archon/blob/main/vectors/identity.json),
69
+ recomputed rather than echoed. If it disagrees with the others about whether something is a
70
+ valid key, signature or key text, that disagreement is the defect.
71
+
72
+ Two places where Python needed care to agree, both recorded in the source:
73
+
74
+ - **`sign_in_domain` is Ed25519ph with the domain as the RFC 8032 §5.1 context.**
75
+ `cryptography` cannot express it — it offers only pure `sign(data)`. This package binds
76
+ **PyCryptodome**, which can.
77
+ - **Small-order public keys are rejected.** PyCryptodome's verifier accepts them; Go's
78
+ `crypto/ed25519` and `ed25519-dalek` do not. archon's profile is to reject, so `verify`
79
+ checks `[8]A` against the identity using the library's own point arithmetic. Without it,
80
+ two oracle cases pass in Python and fail everywhere else.
81
+
82
+ ## Verification
83
+
84
+ Signing raises rather than silently signing raw: an empty domain, or one over 255 bytes, is
85
+ an error. Verification is total — every shape failure returns `False`, so a caller cannot
86
+ mistake *malformed* for *valid*.
87
+
88
+ ## License
89
+
90
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,67 @@
1
+ # archon core — Python
2
+
3
+ The identity floor in Python: Ed25519 key bytes, one canonical text spelling, the SPKI and
4
+ PKCS-8 codecs, and domain-separated signing.
5
+
6
+ ```console
7
+ pip install bitspark-archon-core
8
+ ```
9
+
10
+ The distribution is `bitspark-archon-core`; the import is `archon_core`. The prefix is a
11
+ registry name only — PyPI, like crates.io, has a single flat namespace.
12
+
13
+ ```python
14
+ from archon_core import (
15
+ public_key_from_seed, encode_key, sign_in_domain, verify_in_domain,
16
+ )
17
+
18
+ seed = bytes(range(32))
19
+ pub = public_key_from_seed(seed)
20
+
21
+ encode_key(pub)
22
+ # 'ed25519:03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8'
23
+
24
+ sig = sign_in_domain(seed, "example.v1", b"hello")
25
+ verify_in_domain(pub, "example.v1", b"hello", sig) # True
26
+ verify_in_domain(pub, "other.v1", b"hello", sig) # False — domains do not cross
27
+ ```
28
+
29
+ ## What it is
30
+
31
+ Two questions and no others: *are these bytes that key*, and *is this signature that key's*.
32
+ Authority and custody belong to their own layers — see the
33
+ [repository README](https://github.com/Bitspark/archon).
34
+
35
+ | | |
36
+ |---|---|
37
+ | `crypto` | `public_key_from_seed`, `sign`/`verify`, `sign_in_domain`/`verify_in_domain` |
38
+ | `hexbytes` | `to_hex`, and fixed-size decoders that accept exactly N bytes or fail |
39
+ | `keytext` | `encode_key`/`decode_key` — `ed25519:<64 hex>` |
40
+ | `keycodec` | RFC 5280 SPKI and RFC 5958 PKCS-8 v1 PEM, as a byte codec |
41
+
42
+ ## Agreement is the claim
43
+
44
+ This core is held to the same hand-authored oracle as the Go, Rust and TypeScript cores —
45
+ 60 cases in [`vectors/identity.json`](https://github.com/Bitspark/archon/blob/main/vectors/identity.json),
46
+ recomputed rather than echoed. If it disagrees with the others about whether something is a
47
+ valid key, signature or key text, that disagreement is the defect.
48
+
49
+ Two places where Python needed care to agree, both recorded in the source:
50
+
51
+ - **`sign_in_domain` is Ed25519ph with the domain as the RFC 8032 §5.1 context.**
52
+ `cryptography` cannot express it — it offers only pure `sign(data)`. This package binds
53
+ **PyCryptodome**, which can.
54
+ - **Small-order public keys are rejected.** PyCryptodome's verifier accepts them; Go's
55
+ `crypto/ed25519` and `ed25519-dalek` do not. archon's profile is to reject, so `verify`
56
+ checks `[8]A` against the identity using the library's own point arithmetic. Without it,
57
+ two oracle cases pass in Python and fail everywhere else.
58
+
59
+ ## Verification
60
+
61
+ Signing raises rather than silently signing raw: an empty domain, or one over 255 bytes, is
62
+ an error. Verification is total — every shape failure returns `False`, so a caller cannot
63
+ mistake *malformed* for *valid*.
64
+
65
+ ## License
66
+
67
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bitspark-archon-core"
7
+ version = "0.7.0"
8
+ description = "archon core: Ed25519 primitives, the canonical key spelling, and the SPKI/PKCS-8 key codec. The identity floor beneath the law."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{ name = "Bitspark" }]
14
+
15
+ # One runtime dependency, and the choice is load-bearing. `cryptography` exposes only
16
+ # `sign(data)` — pure Ed25519 — while archon's domain separation is Ed25519ph with the domain
17
+ # as the RFC 8032 context. PyCryptodome's `eddsa.new(key, 'rfc8032', context=…)` is the one
18
+ # mainstream Python route to that primitive.
19
+ dependencies = ["pycryptodome>=3.20"]
20
+
21
+ classifiers = [
22
+ "Development Status :: 3 - Alpha",
23
+ "Intended Audience :: Developers",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Topic :: Security :: Cryptography",
27
+ "Typing :: Typed",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/Bitspark/archon"
32
+ Documentation = "https://github.com/Bitspark/archon/tree/main/docs"
33
+ Repository = "https://github.com/Bitspark/archon"
34
+ Issues = "https://github.com/Bitspark/archon/issues"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.setuptools.package-data]
40
+ archon_core = ["py.typed"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["test"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,54 @@
1
+ """archon core — the identity floor in Python.
2
+
3
+ Ed25519 key bytes, one canonical text spelling, the SPKI/PKCS-8 codecs, and
4
+ domain-separated signing. It answers two questions — are these bytes that key, and is this
5
+ signature that key's — and nothing about authority or custody.
6
+
7
+ This core is held to the same hand-authored oracle as the Go, Rust and TypeScript cores;
8
+ if it disagrees with them about whether something is valid, that disagreement is the defect.
9
+ """
10
+
11
+ from .crypto import (
12
+ MAX_DOMAIN_SIZE,
13
+ PUBLIC_KEY_SIZE,
14
+ SEED_SIZE,
15
+ SIGNATURE_SIZE,
16
+ public_key_from_seed,
17
+ sign,
18
+ sign_in_domain,
19
+ verify,
20
+ verify_in_domain,
21
+ )
22
+ from .hexbytes import pubkey_from_hex, seed_from_hex, signature_from_hex, to_hex
23
+ from .keycodec import (
24
+ pkcs8_pem_to_seed,
25
+ pubkey_to_spki_pem,
26
+ seed_to_pkcs8_pem,
27
+ spki_pem_to_pubkey,
28
+ )
29
+ from .keytext import decode_key, encode_key
30
+
31
+ __version__ = "0.7.0"
32
+
33
+ __all__ = [
34
+ "MAX_DOMAIN_SIZE",
35
+ "PUBLIC_KEY_SIZE",
36
+ "SEED_SIZE",
37
+ "SIGNATURE_SIZE",
38
+ "public_key_from_seed",
39
+ "sign",
40
+ "verify",
41
+ "sign_in_domain",
42
+ "verify_in_domain",
43
+ "to_hex",
44
+ "seed_from_hex",
45
+ "pubkey_from_hex",
46
+ "signature_from_hex",
47
+ "encode_key",
48
+ "decode_key",
49
+ "pubkey_to_spki_pem",
50
+ "seed_to_pkcs8_pem",
51
+ "spki_pem_to_pubkey",
52
+ "pkcs8_pem_to_seed",
53
+ "__version__",
54
+ ]
@@ -0,0 +1,132 @@
1
+ """Conformance CLI (python) — a dev/CI artifact, not part of the library surface.
2
+
3
+ Implements the `conformance v1` protocol: `conformance <family>` reads the whole
4
+ vectors/identity.json on stdin, selects its family's cases, RECOMPUTES each result from the
5
+ case INPUTS (ignoring the expected value the oracle carries), and writes one NDJSON line per
6
+ case to stdout in input order. The harness drives this and the other cores as black boxes and
7
+ asserts each line against the oracle.
8
+
9
+ pubkey_from_seed : in {name, seed} out {"name","pubkey":"<64-hex>"}
10
+ key_encode : in {name, pubkey} out {"name","text":"<key text>"}
11
+ keycodec : in {name, kind, key?|pem?} out {"name","result":{"ok":…}|{"error":true}}
12
+ signature_verify : in {name, pubkey, message, sig} out {"name","valid":<bool>}
13
+ hex_decode : in {name, kind, hex} out {"name","result":{"ok":"<hex>"}|{"error":true}}
14
+ domain_sign : in {name, seed, domain, message} out {"name","result":{"ok":"<128-hex>"}|{"error":true}}
15
+ domain_verify : in {name, pubkey, domain, message, sig} out {"name","valid":<bool>}
16
+
17
+ Recomputing rather than echoing is the whole point: a CLI that read `result` from the case
18
+ would agree with the oracle by construction and prove nothing.
19
+ """
20
+
21
+ import json
22
+ import sys
23
+
24
+ from . import crypto, hexbytes, keycodec, keytext
25
+
26
+
27
+ def _result_of(value, err):
28
+ """The oracle's two-shape result: {"ok": …} or {"error": true}."""
29
+ return {"error": True} if err is not None else {"ok": value}
30
+
31
+
32
+ def _try(fn):
33
+ try:
34
+ return fn(), None
35
+ except Exception as exc: # noqa: BLE001 - every failure is one refusal to the oracle
36
+ return None, exc
37
+
38
+
39
+ def _unhex(text: str) -> bytes:
40
+ # Case inputs that are *already* known-good hex; a bad one is a broken vector file,
41
+ # not a case the family is testing.
42
+ return bytes.fromhex(text)
43
+
44
+
45
+ def main(argv=None) -> int:
46
+ argv = sys.argv[1:] if argv is None else argv
47
+ if len(argv) != 1:
48
+ print("usage: conformance <family>", file=sys.stderr)
49
+ return 2
50
+ family = argv[0]
51
+
52
+ doc = json.load(sys.stdin)
53
+ cases = doc.get(family)
54
+ if cases is None:
55
+ print(f"conformance: no such family: {family}", file=sys.stderr)
56
+ return 1
57
+
58
+ out_lines = []
59
+ for case in cases:
60
+ # The oracle carries a leading note object in some families; it has no name.
61
+ if "name" not in case:
62
+ continue
63
+ out = {"name": case["name"]}
64
+
65
+ if family == "pubkey_from_seed":
66
+ pub = crypto.public_key_from_seed(_unhex(case["seed"]))
67
+ out["pubkey"] = hexbytes.to_hex(pub)
68
+
69
+ elif family == "key_encode":
70
+ out["text"] = keytext.encode_key(_unhex(case["pubkey"]))
71
+
72
+ elif family == "keycodec":
73
+ kind = case["kind"]
74
+ if kind == "encode_pkcs8":
75
+ v, e = _try(lambda: keycodec.seed_to_pkcs8_pem(_unhex(case["key"])).decode("ascii"))
76
+ elif kind == "encode_spki":
77
+ v, e = _try(lambda: keycodec.pubkey_to_spki_pem(_unhex(case["key"])).decode("ascii"))
78
+ elif kind == "decode_pkcs8":
79
+ v, e = _try(lambda: hexbytes.to_hex(keycodec.pkcs8_pem_to_seed(case["pem"].encode("utf-8"))))
80
+ elif kind == "decode_spki":
81
+ v, e = _try(lambda: hexbytes.to_hex(keycodec.spki_pem_to_pubkey(case["pem"].encode("utf-8"))))
82
+ else:
83
+ raise SystemExit(f"unknown keycodec kind: {kind}")
84
+ out["result"] = _result_of(v, e)
85
+
86
+ elif family == "signature_verify":
87
+ out["valid"] = crypto.verify(
88
+ _unhex(case["pubkey"]), _unhex(case["message"]), _unhex(case["sig"])
89
+ )
90
+
91
+ elif family == "hex_decode":
92
+ kind = case["kind"]
93
+ fn = {
94
+ "seed": hexbytes.seed_from_hex,
95
+ "pubkey": hexbytes.pubkey_from_hex,
96
+ "signature": hexbytes.signature_from_hex,
97
+ }.get(kind)
98
+ if fn is None:
99
+ raise SystemExit(f"unknown hex_decode kind: {kind}")
100
+ v, e = _try(lambda: hexbytes.to_hex(fn(case["hex"])))
101
+ out["result"] = _result_of(v, e)
102
+
103
+ elif family == "domain_sign":
104
+ v, e = _try(
105
+ lambda: hexbytes.to_hex(
106
+ crypto.sign_in_domain(
107
+ _unhex(case["seed"]), case["domain"], _unhex(case["message"])
108
+ )
109
+ )
110
+ )
111
+ out["result"] = _result_of(v, e)
112
+
113
+ elif family == "domain_verify":
114
+ out["valid"] = crypto.verify_in_domain(
115
+ _unhex(case["pubkey"]),
116
+ case["domain"],
117
+ _unhex(case["message"]),
118
+ _unhex(case["sig"]),
119
+ )
120
+
121
+ else:
122
+ print(f"conformance: unhandled family: {family}", file=sys.stderr)
123
+ return 1
124
+
125
+ out_lines.append(json.dumps(out, separators=(",", ":"), sort_keys=True))
126
+
127
+ sys.stdout.write("\n".join(out_lines) + ("\n" if out_lines else ""))
128
+ return 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ raise SystemExit(main())
@@ -0,0 +1,178 @@
1
+ """Ed25519 signing and verification — the floor's only cryptography.
2
+
3
+ Like the other cores, this binds an existing Ed25519 implementation and writes none of its
4
+ own curve arithmetic. The binding here is PyCryptodome, chosen for one reason the mainstream
5
+ alternative cannot meet: `sign_in_domain` is Ed25519ph with the domain as the RFC 8032 §5.1
6
+ context string, and `cryptography`'s Ed25519 exposes only `sign(data)` — pure Ed25519, no
7
+ prehash, no context. PyCryptodome's `eddsa.new(key, 'rfc8032', context=...)` reaches it.
8
+
9
+ - `sign` / `verify` — raw Ed25519 over the message bytes.
10
+ - `sign_in_domain` / `verify_in_domain` — DOMAIN-SEPARATED: Ed25519ph with the domain as the
11
+ context. A signature made in one domain verifies in no other and never as a raw signature.
12
+
13
+ Verification is fail-closed: every shape failure collapses to False rather than raising, so a
14
+ caller cannot mistake "malformed" for "valid".
15
+ """
16
+
17
+ from Crypto.Hash import SHA512
18
+ from Crypto.PublicKey import ECC
19
+ from Crypto.Signature import eddsa
20
+
21
+ PUBLIC_KEY_SIZE = 32
22
+ SIGNATURE_SIZE = 64
23
+ SEED_SIZE = 32
24
+ #: The longest domain (RFC 8032 context) a signature can be made in, in bytes.
25
+ MAX_DOMAIN_SIZE = 255
26
+
27
+ __all__ = [
28
+ "PUBLIC_KEY_SIZE",
29
+ "SIGNATURE_SIZE",
30
+ "SEED_SIZE",
31
+ "MAX_DOMAIN_SIZE",
32
+ "public_key_from_seed",
33
+ "sign",
34
+ "verify",
35
+ "sign_in_domain",
36
+ "verify_in_domain",
37
+ ]
38
+
39
+
40
+ def _private(seed: bytes):
41
+ if len(seed) != SEED_SIZE:
42
+ raise ValueError(f"crypto: seed must be {SEED_SIZE} bytes, got {len(seed)}")
43
+ return ECC.construct(curve="Ed25519", seed=bytes(seed))
44
+
45
+
46
+ def _public(pubkey: bytes):
47
+ # Importing an encoded SPKI is the only route PyCryptodome offers from 32 raw bytes.
48
+ return ECC.import_key(_SPKI_PREFIX + bytes(pubkey))
49
+
50
+
51
+ # The order of the prime-order subgroup, L = 2^252 + 27742317777372353535851937790883648493.
52
+ _L = 0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED
53
+
54
+
55
+ def _is_prime_order_point(encoded: bytes) -> bool:
56
+ """ADR 0008: `encoded` is a canonical encoding of a point of order exactly L.
57
+
58
+ False for a point not on the curve, a non-canonical spelling (y >= p, or x = 0 with the
59
+ sign bit set: the point re-encodes to different bytes), the identity, any small-order
60
+ point and any mixed-order point. This is archon's acceptance policy, not the library's:
61
+ RFC 8032 permits more than one verification equation, and implementations genuinely
62
+ differ — PyCryptodome's is cofactored, so on its own it accepts a mixed-order key for
63
+ every message and a small-order R, where Go and ed25519-dalek (uncofactored) accept the
64
+ former for one message in eight and refuse the latter. Restricting both points to the
65
+ prime-order subgroup is where the two equations agree; checking it here, explicitly, is
66
+ what makes the accepted set archon's rather than the library's.
67
+
68
+ It is a check, not curve arithmetic we wrote: `[L]A` uses the library's own point
69
+ multiplication, and a point is in the prime-order subgroup exactly when `[L]A` is the
70
+ identity. That is stronger than a small-order check (`[8]A`), which passes a mixed-order
71
+ point, and stronger than a blocklist, which misses non-canonical spellings.
72
+ """
73
+ try:
74
+ key = ECC.import_key(_SPKI_PREFIX + bytes(encoded))
75
+ if key.public_key().export_key(format="raw") != bytes(encoded):
76
+ return False
77
+ point = key.pointQ
78
+ if _is_identity(point):
79
+ return False
80
+ return _is_identity(point * _L)
81
+ except Exception: # noqa: BLE001 - an unusable point is not a valid key either
82
+ return False
83
+
84
+
85
+ def _is_identity(point) -> bool:
86
+ """The identity is (0, 1) — both coordinates, deliberately.
87
+
88
+ PyCryptodome's `EccPoint.is_point_at_infinity()` on an Edwards curve tests `x == 0`
89
+ alone, which the order-2 point (0, -1) satisfies too. Its arithmetic is right: for a
90
+ key with an order-2 torsion component, `[L]A` really is (0, -1) — but that method calls
91
+ it the identity, and the subgroup check would pass a mixed-order key. Found by the
92
+ differential run (`conformance/profile-cases.mjs differential`) on its first pass, in
93
+ the one class the fixed vectors happened not to draw.
94
+ """
95
+ return point.is_point_at_infinity() and int(point.y) == 1
96
+
97
+
98
+ def _in_profile(pubkey: bytes, signature: bytes) -> bool:
99
+ """The profile's shape conditions: sizes, and A and R prime-order points. S's range
100
+ (0 <= S < L) is PyCryptodome's own check, so it is not repeated here."""
101
+ return (
102
+ len(pubkey) == PUBLIC_KEY_SIZE
103
+ and len(signature) == SIGNATURE_SIZE
104
+ and _is_prime_order_point(pubkey)
105
+ and _is_prime_order_point(signature[:PUBLIC_KEY_SIZE])
106
+ )
107
+
108
+
109
+ # The SPKI template keycodec also uses. Importing an encoded public key is the only route
110
+ # PyCryptodome offers from 32 raw bytes, so the prefix lives here too rather than crossing a
111
+ # module boundary for four constants.
112
+ _SPKI_PREFIX = bytes(
113
+ [0x30, 0x2A, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x03, 0x21, 0x00]
114
+ )
115
+
116
+
117
+ def public_key_from_seed(seed: bytes) -> bytes:
118
+ """The 32-byte public key for `seed`. Raises when the seed is not 32 bytes."""
119
+ return _private(seed).public_key().export_key(format="raw")
120
+
121
+
122
+ def sign(seed: bytes, message: bytes) -> bytes:
123
+ """A raw Ed25519 signature over `message`."""
124
+ return eddsa.new(_private(seed), "rfc8032").sign(bytes(message))
125
+
126
+
127
+ def verify(pubkey: bytes, message: bytes, signature: bytes) -> bool:
128
+ """True when `signature` is `pubkey`'s over `message`, within the verification
129
+ profile (ADR 0008). False on any shape failure, including a key or an R outside the
130
+ profile."""
131
+ if not _in_profile(pubkey, signature):
132
+ return False
133
+ try:
134
+ eddsa.new(_public(pubkey), "rfc8032").verify(bytes(message), bytes(signature))
135
+ return True
136
+ except (ValueError, TypeError):
137
+ return False
138
+
139
+
140
+ def _check_domain(domain: str) -> None:
141
+ # A domain is 1..=255 bytes of UTF-8. `str.encode` raises (a ValueError) on a lone
142
+ # surrogate rather than substituting, which is the behaviour the profile requires.
143
+ n = len(domain.encode("utf-8"))
144
+ if n == 0:
145
+ raise ValueError("crypto: domain is empty")
146
+ if n > MAX_DOMAIN_SIZE:
147
+ raise ValueError(f"crypto: domain is {n} bytes, max {MAX_DOMAIN_SIZE}")
148
+
149
+
150
+ def sign_in_domain(seed: bytes, domain: str, message: bytes) -> bytes:
151
+ """Signs `message` in `domain` — Ed25519ph with the domain as the RFC 8032 context.
152
+
153
+ Raises, never silently signs raw, when the domain is empty or longer than 255 bytes.
154
+ """
155
+ _check_domain(domain)
156
+ digest = SHA512.new(bytes(message))
157
+ signer = eddsa.new(_private(seed), "rfc8032", context=domain.encode("utf-8"))
158
+ return signer.sign(digest)
159
+
160
+
161
+ def verify_in_domain(
162
+ pubkey: bytes, domain: str, message: bytes, signature: bytes
163
+ ) -> bool:
164
+ """True when `signature` is `pubkey`'s over `message` IN `domain`, within the
165
+ verification profile (ADR 0008). False otherwise."""
166
+ try:
167
+ _check_domain(domain)
168
+ except ValueError:
169
+ return False
170
+ if not _in_profile(pubkey, signature):
171
+ return False
172
+ try:
173
+ digest = SHA512.new(bytes(message))
174
+ verifier = eddsa.new(_public(pubkey), "rfc8032", context=domain.encode("utf-8"))
175
+ verifier.verify(digest, bytes(signature))
176
+ return True
177
+ except (ValueError, TypeError):
178
+ return False
@@ -0,0 +1,47 @@
1
+ """Typed, fail-closed hex spellings.
2
+
3
+ Not a hex helper — every language has one — but the FIXED SIZE. Each decoder accepts exactly
4
+ its type's byte count or fails; the length is checked on the TEXT before any byte is decoded,
5
+ so a wrong-length input never reaches the decoder. Either case in, lowercase out. No `0x`, no
6
+ whitespace, no odd-length bodies.
7
+ """
8
+
9
+ from .crypto import PUBLIC_KEY_SIZE, SEED_SIZE, SIGNATURE_SIZE
10
+
11
+ __all__ = ["to_hex", "seed_from_hex", "pubkey_from_hex", "signature_from_hex"]
12
+
13
+ _HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
14
+
15
+
16
+ def to_hex(data: bytes) -> str:
17
+ """Lowercase hex, no prefix."""
18
+ return bytes(data).hex()
19
+
20
+
21
+ def _fixed(text: str, n: int, what: str) -> bytes:
22
+ if len(text) != n * 2:
23
+ raise ValueError(
24
+ f"hexbytes: {what} hex is {len(text)} characters, expected {n * 2}"
25
+ )
26
+ # Python's bytes.fromhex accepts whitespace; archon's grammar does not. Check the
27
+ # alphabet explicitly rather than relying on the decoder's laxer rules — the other
28
+ # cores reject a space here, and agreement is the point.
29
+ for ch in text:
30
+ if ch not in _HEX_DIGITS:
31
+ raise ValueError(f"hexbytes: {what}: non-hex character {ch!r}")
32
+ return bytes.fromhex(text)
33
+
34
+
35
+ def seed_from_hex(text: str) -> bytes:
36
+ """Exactly 32 bytes, or raises."""
37
+ return _fixed(text, SEED_SIZE, "seed")
38
+
39
+
40
+ def pubkey_from_hex(text: str) -> bytes:
41
+ """Exactly 32 bytes, or raises."""
42
+ return _fixed(text, PUBLIC_KEY_SIZE, "public key")
43
+
44
+
45
+ def signature_from_hex(text: str) -> bytes:
46
+ """Exactly 64 bytes, or raises."""
47
+ return _fixed(text, SIGNATURE_SIZE, "signature")
@@ -0,0 +1,86 @@
1
+ """The SPKI and PKCS-8 PEM codecs — a BYTE codec, not key custody.
2
+
3
+ For an Ed25519 key the DER is fixed-length and fixed-shape, so this is a template match, not
4
+ an ASN.1 parser: a 12-byte SPKI prefix or a 16-byte PKCS-8 v1 prefix, then exactly 32 key
5
+ bytes. Anything else is refused. That is deliberate — a general parser would accept encodings
6
+ the other cores would not, and agreement is the claim.
7
+
8
+ RFC 5280 (SPKI) and RFC 5958 (PKCS-8 v1). PKCS-8 v2, which carries the public key alongside
9
+ the private one, is NOT accepted: it is a second spelling of the same key.
10
+ """
11
+
12
+ import base64
13
+
14
+ from .crypto import PUBLIC_KEY_SIZE
15
+
16
+ _KEY_LEN = PUBLIC_KEY_SIZE # 32; the seed is the same length
17
+
18
+ _SPKI_PREFIX = bytes(
19
+ [0x30, 0x2A, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x03, 0x21, 0x00]
20
+ )
21
+ _PKCS8_PREFIX = bytes(
22
+ [
23
+ 0x30, 0x2E, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,
24
+ 0x03, 0x2B, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
25
+ ]
26
+ )
27
+
28
+ _PEM_PUBLIC = "PUBLIC KEY"
29
+ _PEM_PRIVATE = "PRIVATE KEY"
30
+
31
+ __all__ = [
32
+ "pubkey_to_spki_pem",
33
+ "seed_to_pkcs8_pem",
34
+ "spki_pem_to_pubkey",
35
+ "pkcs8_pem_to_seed",
36
+ ]
37
+
38
+
39
+ def _encode(key: bytes, prefix: bytes, pem_type: str) -> bytes:
40
+ if len(key) != _KEY_LEN:
41
+ raise ValueError(f"keycodec: key must be {_KEY_LEN} bytes, got {len(key)}")
42
+ body = base64.b64encode(prefix + bytes(key)).decode("ascii")
43
+ return (
44
+ f"-----BEGIN {pem_type}-----\n{body}\n-----END {pem_type}-----\n"
45
+ ).encode("ascii")
46
+
47
+
48
+ def _decode(pem_bytes: bytes, prefix: bytes, pem_type: str) -> bytes:
49
+ text = bytes(pem_bytes).decode("ascii", errors="strict").replace("\r\n", "\n")
50
+ text = text.rstrip("\n")
51
+ begin = f"-----BEGIN {pem_type}-----"
52
+ end = f"-----END {pem_type}-----"
53
+ lines = text.split("\n")
54
+ if len(lines) < 3 or lines[0] != begin or lines[-1] != end:
55
+ raise ValueError(f"keycodec: not a {pem_type!r} PEM block")
56
+ try:
57
+ # validate=True: base64 that carries stray characters is refused rather than
58
+ # silently skipped, which is what a lax decoder would do.
59
+ der = base64.b64decode("".join(lines[1:-1]), validate=True)
60
+ except Exception as exc: # noqa: BLE001 - surfaced as one codec error
61
+ raise ValueError(f"keycodec: invalid base64 in PEM body: {exc}") from exc
62
+ if len(der) != len(prefix) + _KEY_LEN or der[: len(prefix)] != prefix:
63
+ raise ValueError(
64
+ f"keycodec: DER does not match the {pem_type} ed25519-key-codec-v1 template"
65
+ )
66
+ return der[len(prefix) :]
67
+
68
+
69
+ def pubkey_to_spki_pem(pubkey: bytes) -> bytes:
70
+ """A public key as an RFC 5280 SPKI PEM block."""
71
+ return _encode(pubkey, _SPKI_PREFIX, _PEM_PUBLIC)
72
+
73
+
74
+ def seed_to_pkcs8_pem(seed: bytes) -> bytes:
75
+ """A seed as an RFC 5958 PKCS-8 v1 PEM block."""
76
+ return _encode(seed, _PKCS8_PREFIX, _PEM_PRIVATE)
77
+
78
+
79
+ def spki_pem_to_pubkey(pem_bytes: bytes) -> bytes:
80
+ """The 32 public-key bytes from an SPKI PEM block, or raises."""
81
+ return _decode(pem_bytes, _SPKI_PREFIX, _PEM_PUBLIC)
82
+
83
+
84
+ def pkcs8_pem_to_seed(pem_bytes: bytes) -> bytes:
85
+ """The 32 seed bytes from a PKCS-8 v1 PEM block, or raises."""
86
+ return _decode(pem_bytes, _PKCS8_PREFIX, _PEM_PRIVATE)
@@ -0,0 +1,37 @@
1
+ """The canonical key spelling: `ed25519:<64 lowercase hex>`.
2
+
3
+ One spelling, in every language. The prefix is required; the body is exactly 64 hex digits
4
+ decoding to a 32-byte public key. Length and alphabet are part of the grammar, not decoration
5
+ — a body of the wrong length is refused even when it is valid hex.
6
+ """
7
+
8
+ from .crypto import PUBLIC_KEY_SIZE
9
+
10
+ _PREFIX = "ed25519:"
11
+
12
+ __all__ = ["encode_key", "decode_key"]
13
+
14
+ _HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
15
+
16
+
17
+ def encode_key(pubkey: bytes) -> str:
18
+ """`ed25519:` followed by the key as lowercase hex."""
19
+ return _PREFIX + bytes(pubkey).hex()
20
+
21
+
22
+ def decode_key(text: str) -> bytes:
23
+ """The 32 key bytes, or raises — missing prefix, odd length, non-hex, wrong size."""
24
+ if not text.startswith(_PREFIX):
25
+ raise ValueError(f"keytext: missing {_PREFIX!r} prefix")
26
+ body = text[len(_PREFIX) :]
27
+ if len(body) % 2 != 0:
28
+ raise ValueError("keytext: key body has an odd number of hex digits")
29
+ for ch in body:
30
+ if ch not in _HEX_DIGITS:
31
+ raise ValueError(f"keytext: non-hex character in key body: {ch!r}")
32
+ out = bytes.fromhex(body)
33
+ if len(out) != PUBLIC_KEY_SIZE:
34
+ raise ValueError(
35
+ f"keytext: decoded key is {len(out)} bytes, expected {PUBLIC_KEY_SIZE}"
36
+ )
37
+ return out
File without changes
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: bitspark-archon-core
3
+ Version: 0.7.0
4
+ Summary: archon core: Ed25519 primitives, the canonical key spelling, and the SPKI/PKCS-8 key codec. The identity floor beneath the law.
5
+ Author: Bitspark
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Bitspark/archon
8
+ Project-URL: Documentation, https://github.com/Bitspark/archon/tree/main/docs
9
+ Project-URL: Repository, https://github.com/Bitspark/archon
10
+ Project-URL: Issues, https://github.com/Bitspark/archon/issues
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Security :: Cryptography
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE
21
+ Requires-Dist: pycryptodome>=3.20
22
+ Dynamic: license-file
23
+
24
+ # archon core — Python
25
+
26
+ The identity floor in Python: Ed25519 key bytes, one canonical text spelling, the SPKI and
27
+ PKCS-8 codecs, and domain-separated signing.
28
+
29
+ ```console
30
+ pip install bitspark-archon-core
31
+ ```
32
+
33
+ The distribution is `bitspark-archon-core`; the import is `archon_core`. The prefix is a
34
+ registry name only — PyPI, like crates.io, has a single flat namespace.
35
+
36
+ ```python
37
+ from archon_core import (
38
+ public_key_from_seed, encode_key, sign_in_domain, verify_in_domain,
39
+ )
40
+
41
+ seed = bytes(range(32))
42
+ pub = public_key_from_seed(seed)
43
+
44
+ encode_key(pub)
45
+ # 'ed25519:03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8'
46
+
47
+ sig = sign_in_domain(seed, "example.v1", b"hello")
48
+ verify_in_domain(pub, "example.v1", b"hello", sig) # True
49
+ verify_in_domain(pub, "other.v1", b"hello", sig) # False — domains do not cross
50
+ ```
51
+
52
+ ## What it is
53
+
54
+ Two questions and no others: *are these bytes that key*, and *is this signature that key's*.
55
+ Authority and custody belong to their own layers — see the
56
+ [repository README](https://github.com/Bitspark/archon).
57
+
58
+ | | |
59
+ |---|---|
60
+ | `crypto` | `public_key_from_seed`, `sign`/`verify`, `sign_in_domain`/`verify_in_domain` |
61
+ | `hexbytes` | `to_hex`, and fixed-size decoders that accept exactly N bytes or fail |
62
+ | `keytext` | `encode_key`/`decode_key` — `ed25519:<64 hex>` |
63
+ | `keycodec` | RFC 5280 SPKI and RFC 5958 PKCS-8 v1 PEM, as a byte codec |
64
+
65
+ ## Agreement is the claim
66
+
67
+ This core is held to the same hand-authored oracle as the Go, Rust and TypeScript cores —
68
+ 60 cases in [`vectors/identity.json`](https://github.com/Bitspark/archon/blob/main/vectors/identity.json),
69
+ recomputed rather than echoed. If it disagrees with the others about whether something is a
70
+ valid key, signature or key text, that disagreement is the defect.
71
+
72
+ Two places where Python needed care to agree, both recorded in the source:
73
+
74
+ - **`sign_in_domain` is Ed25519ph with the domain as the RFC 8032 §5.1 context.**
75
+ `cryptography` cannot express it — it offers only pure `sign(data)`. This package binds
76
+ **PyCryptodome**, which can.
77
+ - **Small-order public keys are rejected.** PyCryptodome's verifier accepts them; Go's
78
+ `crypto/ed25519` and `ed25519-dalek` do not. archon's profile is to reject, so `verify`
79
+ checks `[8]A` against the identity using the library's own point arithmetic. Without it,
80
+ two oracle cases pass in Python and fail everywhere else.
81
+
82
+ ## Verification
83
+
84
+ Signing raises rather than silently signing raw: an empty domain, or one over 255 bytes, is
85
+ an error. Verification is total — every shape failure returns `False`, so a caller cannot
86
+ mistake *malformed* for *valid*.
87
+
88
+ ## License
89
+
90
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ src/archon_core/__init__.py
6
+ src/archon_core/_conformance.py
7
+ src/archon_core/crypto.py
8
+ src/archon_core/hexbytes.py
9
+ src/archon_core/keycodec.py
10
+ src/archon_core/keytext.py
11
+ src/archon_core/py.typed
12
+ src/bitspark_archon_core.egg-info/PKG-INFO
13
+ src/bitspark_archon_core.egg-info/SOURCES.txt
14
+ src/bitspark_archon_core.egg-info/dependency_links.txt
15
+ src/bitspark_archon_core.egg-info/requires.txt
16
+ src/bitspark_archon_core.egg-info/top_level.txt
17
+ test/test_core.py
@@ -0,0 +1,180 @@
1
+ """Unit tests for the Python core.
2
+
3
+ The oracle in `vectors/identity.json` is the cross-language authority and is driven by
4
+ `conformance/check.mjs`; these tests cover the same ground from inside Python, plus the
5
+ argument-shape failures the oracle has no way to express (a raised exception, a wrong-sized
6
+ seed) because its protocol only carries `ok` / `error`.
7
+ """
8
+
9
+ import pytest
10
+
11
+ from archon_core import (
12
+ MAX_DOMAIN_SIZE,
13
+ decode_key,
14
+ encode_key,
15
+ pkcs8_pem_to_seed,
16
+ pubkey_from_hex,
17
+ pubkey_to_spki_pem,
18
+ public_key_from_seed,
19
+ seed_from_hex,
20
+ seed_to_pkcs8_pem,
21
+ sign,
22
+ sign_in_domain,
23
+ signature_from_hex,
24
+ spki_pem_to_pubkey,
25
+ to_hex,
26
+ verify,
27
+ verify_in_domain,
28
+ )
29
+
30
+ SEED = bytes(range(32))
31
+ MSG = b"hello"
32
+ DOMAIN = "example.v1"
33
+
34
+
35
+ # --- crypto ---------------------------------------------------------------------------
36
+
37
+ def test_public_key_is_32_bytes_and_stable():
38
+ pub = public_key_from_seed(SEED)
39
+ assert len(pub) == 32
40
+ assert pub == public_key_from_seed(SEED)
41
+
42
+
43
+ def test_seed_must_be_32_bytes():
44
+ with pytest.raises(ValueError):
45
+ public_key_from_seed(SEED[:31])
46
+
47
+
48
+ def test_sign_verify_roundtrip():
49
+ assert verify(public_key_from_seed(SEED), MSG, sign(SEED, MSG))
50
+
51
+
52
+ def test_verify_is_total_not_raising():
53
+ pub = public_key_from_seed(SEED)
54
+ sig = sign(SEED, MSG)
55
+ assert verify(pub, b"goodbye", sig) is False
56
+ assert verify(pub[:31], MSG, sig) is False # short key
57
+ assert verify(pub, MSG, sig[:63]) is False # short signature
58
+ assert verify(pub, MSG, bytes(64)) is False # all-zero signature
59
+
60
+
61
+ def test_domain_separation_is_cryptographic():
62
+ pub = public_key_from_seed(SEED)
63
+ sig = sign_in_domain(SEED, DOMAIN, MSG)
64
+ assert verify_in_domain(pub, DOMAIN, MSG, sig)
65
+ assert verify_in_domain(pub, "other.v1", MSG, sig) is False # another domain
66
+ assert verify(pub, MSG, sig) is False # never as raw
67
+ assert verify_in_domain(pub, DOMAIN, MSG, sign(SEED, MSG)) is False # raw never in a domain
68
+
69
+
70
+ def test_domain_bounds():
71
+ with pytest.raises(ValueError):
72
+ sign_in_domain(SEED, "", MSG) # "sign in no domain"
73
+ with pytest.raises(ValueError):
74
+ sign_in_domain(SEED, "d" * (MAX_DOMAIN_SIZE + 1), MSG)
75
+ longest = "d" * MAX_DOMAIN_SIZE
76
+ assert verify_in_domain(
77
+ public_key_from_seed(SEED), longest, MSG, sign_in_domain(SEED, longest, MSG)
78
+ )
79
+
80
+
81
+ def test_verify_in_domain_is_false_not_raising_on_bad_domain():
82
+ pub = public_key_from_seed(SEED)
83
+ sig = sign_in_domain(SEED, DOMAIN, MSG)
84
+ assert verify_in_domain(pub, "", MSG, sig) is False
85
+ assert verify_in_domain(pub, "d" * (MAX_DOMAIN_SIZE + 1), MSG, sig) is False
86
+
87
+
88
+ @pytest.mark.parametrize(
89
+ "pubkey_hex",
90
+ [
91
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
92
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
93
+ ],
94
+ )
95
+ def test_small_order_public_keys_are_rejected(pubkey_hex):
96
+ """archon's profile rejects them; PyCryptodome's verifier alone would not.
97
+
98
+ These are the two oracle cases that disagreed before the explicit check existed.
99
+ """
100
+ pub = bytes.fromhex(pubkey_hex)
101
+ sig = pub + bytes(32) # the R=A, S=0 shape the oracle uses
102
+ assert verify(pub, MSG, sig) is False
103
+ assert verify_in_domain(pub, DOMAIN, MSG, sig) is False
104
+
105
+
106
+ # --- hexbytes -------------------------------------------------------------------------
107
+
108
+ def test_hex_is_lowercase_and_fixed_size():
109
+ assert to_hex(b"\x00\xff") == "00ff"
110
+ assert seed_from_hex("AA" * 32) == bytes([0xAA]) * 32 # either case in
111
+ for bad in ["aa" * 31, "aa" * 33, "", "zz" * 32]:
112
+ with pytest.raises(ValueError):
113
+ seed_from_hex(bad)
114
+
115
+
116
+ def test_hex_rejects_whitespace_that_python_would_otherwise_accept():
117
+ """`bytes.fromhex` tolerates spaces; archon's grammar does not, and the other cores
118
+ reject them. Agreement is the point."""
119
+ with pytest.raises(ValueError):
120
+ seed_from_hex("aa " * 16 + "aa" * 16)
121
+
122
+
123
+ def test_hex_decoders_are_typed_by_length():
124
+ assert len(pubkey_from_hex("11" * 32)) == 32
125
+ assert len(signature_from_hex("11" * 64)) == 64
126
+ with pytest.raises(ValueError):
127
+ pubkey_from_hex("11" * 64) # a signature is not a public key
128
+
129
+
130
+ # --- keytext --------------------------------------------------------------------------
131
+
132
+ def test_key_text_roundtrip():
133
+ pub = public_key_from_seed(SEED)
134
+ text = encode_key(pub)
135
+ assert text.startswith("ed25519:")
136
+ assert text == text.lower()
137
+ assert decode_key(text) == pub
138
+
139
+
140
+ @pytest.mark.parametrize(
141
+ "bad",
142
+ [
143
+ "d75a98", # no prefix
144
+ "ed25519:abc", # odd number of digits
145
+ "ed25519:" + "zz" * 32, # non-hex
146
+ "ed25519:" + "aa" * 31, # decodes to the wrong size
147
+ "ED25519:" + "aa" * 32, # the prefix is exact
148
+ ],
149
+ )
150
+ def test_key_text_refusals(bad):
151
+ with pytest.raises(ValueError):
152
+ decode_key(bad)
153
+
154
+
155
+ # --- keycodec -------------------------------------------------------------------------
156
+
157
+ def test_pem_roundtrips():
158
+ pub = public_key_from_seed(SEED)
159
+ assert spki_pem_to_pubkey(pubkey_to_spki_pem(pub)) == pub
160
+ assert pkcs8_pem_to_seed(seed_to_pkcs8_pem(SEED)) == SEED
161
+
162
+
163
+ def test_pem_shape():
164
+ pem = pubkey_to_spki_pem(public_key_from_seed(SEED)).decode("ascii")
165
+ assert pem.startswith("-----BEGIN PUBLIC KEY-----\n")
166
+ assert pem.endswith("-----END PUBLIC KEY-----\n")
167
+
168
+
169
+ def test_pem_accepts_crlf():
170
+ pem = seed_to_pkcs8_pem(SEED).decode("ascii")
171
+ assert pkcs8_pem_to_seed(pem.replace("\n", "\r\n").encode("ascii")) == SEED
172
+
173
+
174
+ def test_pem_refuses_the_wrong_block_and_bad_template():
175
+ with pytest.raises(ValueError):
176
+ spki_pem_to_pubkey(seed_to_pkcs8_pem(SEED)) # private PEM to the public decoder
177
+ with pytest.raises(ValueError):
178
+ pubkey_to_spki_pem(b"\x00" * 31) # key must be 32 bytes
179
+ with pytest.raises(ValueError):
180
+ spki_pem_to_pubkey(b"-----BEGIN PUBLIC KEY-----\nbm90IERFUg==\n-----END PUBLIC KEY-----\n")