pqblocks-files 0.1.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.
Files changed (34) hide show
  1. pqblocks_files-0.1.0/LICENSE +201 -0
  2. pqblocks_files-0.1.0/NOTICE +7 -0
  3. pqblocks_files-0.1.0/PKG-INFO +140 -0
  4. pqblocks_files-0.1.0/README.md +107 -0
  5. pqblocks_files-0.1.0/pyproject.toml +46 -0
  6. pqblocks_files-0.1.0/setup.cfg +4 -0
  7. pqblocks_files-0.1.0/src/pqblocks_files/__init__.py +0 -0
  8. pqblocks_files-0.1.0/src/pqblocks_files/ae.py +92 -0
  9. pqblocks_files-0.1.0/src/pqblocks_files/chunker.py +125 -0
  10. pqblocks_files-0.1.0/src/pqblocks_files/cli.py +240 -0
  11. pqblocks_files-0.1.0/src/pqblocks_files/encrypt.py +337 -0
  12. pqblocks_files-0.1.0/src/pqblocks_files/header.py +350 -0
  13. pqblocks_files-0.1.0/src/pqblocks_files/kem.py +302 -0
  14. pqblocks_files-0.1.0/src/pqblocks_files/keys.py +240 -0
  15. pqblocks_files-0.1.0/src/pqblocks_files/pqtypes.py +48 -0
  16. pqblocks_files-0.1.0/src/pqblocks_files.egg-info/PKG-INFO +140 -0
  17. pqblocks_files-0.1.0/src/pqblocks_files.egg-info/SOURCES.txt +32 -0
  18. pqblocks_files-0.1.0/src/pqblocks_files.egg-info/dependency_links.txt +1 -0
  19. pqblocks_files-0.1.0/src/pqblocks_files.egg-info/entry_points.txt +2 -0
  20. pqblocks_files-0.1.0/src/pqblocks_files.egg-info/requires.txt +6 -0
  21. pqblocks_files-0.1.0/src/pqblocks_files.egg-info/top_level.txt +1 -0
  22. pqblocks_files-0.1.0/tests/test_aead.py +353 -0
  23. pqblocks_files-0.1.0/tests/test_chunker.py +176 -0
  24. pqblocks_files-0.1.0/tests/test_cli.py +377 -0
  25. pqblocks_files-0.1.0/tests/test_cli_direct.py +171 -0
  26. pqblocks_files-0.1.0/tests/test_coverage_extra.py +219 -0
  27. pqblocks_files-0.1.0/tests/test_encrypt.py +426 -0
  28. pqblocks_files-0.1.0/tests/test_fuzz_parsers.py +160 -0
  29. pqblocks_files-0.1.0/tests/test_header.py +303 -0
  30. pqblocks_files-0.1.0/tests/test_kat_acvp.py +107 -0
  31. pqblocks_files-0.1.0/tests/test_kat_wycheproof.py +115 -0
  32. pqblocks_files-0.1.0/tests/test_kem.py +186 -0
  33. pqblocks_files-0.1.0/tests/test_keys.py +129 -0
  34. pqblocks_files-0.1.0/tests/test_security_fixes.py +699 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ Use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The PQBlocks Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ pqblocks-files
2
+ Copyright 2026 The PQBlocks Authors
3
+
4
+ This product is part of PQBlocks (https://github.com/PQBlocks).
5
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
6
+
7
+
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: pqblocks-files
3
+ Version: 0.1.0
4
+ Summary: Hybrid post-quantum file encryption: ML-KEM-768 plus X25519 key encapsulation with chunked ChaCha20-Poly1305 in the pfsh v1 format.
5
+ Author: The PQBlocks Authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/PQBlocks/hybrid-file-encryption
8
+ Project-URL: Documentation, https://github.com/PQBlocks/hybrid-file-encryption#readme
9
+ Project-URL: Source, https://github.com/PQBlocks/hybrid-file-encryption
10
+ Project-URL: Changelog, https://github.com/PQBlocks/hybrid-file-encryption/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/PQBlocks/hybrid-file-encryption/issues
12
+ Project-URL: Security, https://github.com/PQBlocks/hybrid-file-encryption/security/policy
13
+ Keywords: post-quantum,ml-kem,x25519,hybrid,file-encryption,chacha20-poly1305,kem
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Security :: Cryptography
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ License-File: NOTICE
27
+ Requires-Dist: bech32<2,>=1.2
28
+ Requires-Dist: cryptography<51,>=42
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest; extra == "test"
31
+ Requires-Dist: hypothesis; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # pqblocks-files
35
+
36
+ Hybrid post-quantum file encryption for Python and the command line: ML-KEM-768 plus X25519 key encapsulation, with the payload sealed in 64 KiB ChaCha20-Poly1305 chunks (the `pfsh` v1 file format).
37
+ Use it to encrypt files or byte strings to one or more recipients' public keys so that a future quantum computer, or a break of either primitive alone, does not expose them.
38
+ Implements NIST FIPS 203 (ML-KEM-768, via liboqs), RFC 7748 (X25519), RFC 8439 (ChaCha20-Poly1305) and RFC 5869 (HKDF). **Not FIPS or CMVP validated. Pre-1.0: not independently audited.**
39
+
40
+ ```bash
41
+ pip install pqblocks-files # needs a system liboqs 0.15.x or 0.16.x, see Requirements
42
+ ```
43
+
44
+ ```python
45
+ from pqblocks_files.encrypt import encrypt, decrypt
46
+ from pqblocks_files.keys import keygen
47
+
48
+ keypair = keygen() # ML-KEM-768 + X25519
49
+ blob = encrypt(b"quarterly numbers", [keypair.public]) # fresh random file key every call
50
+ assert decrypt(blob, keypair) == b"quarterly numbers" # refuses classical-only files by default
51
+ ```
52
+
53
+ ## Requirements
54
+
55
+ - Python 3.11 or newer; `cryptography` and `bech32` (installed by pip).
56
+ - **A shared liboqs** (`liboqs.so`, version 0.15.x or 0.16.x) found by the system loader, or pointed to with `OQS_LIB_PATH=/path/to/liboqs.so.9`. Any other liboqs version is refused at import with a `RuntimeError`. pip does not install liboqs. This was verified against liboqs 0.16.0; the CI workflow builds 0.15.0.
57
+
58
+ ## Why PQBlocks
59
+
60
+ - **Hybrid by default:** every file key is wrapped under ML-KEM-768 *and* X25519. Classical-only files are a loud, explicit opt-in on both write (`classical_only=True`) and read (`require_pq=False`).
61
+ - **No foot-guns in the API:** no nonce, file-key or algorithm parameters. The file key is always fresh from the OS CSPRNG.
62
+ - **Private keys are passphrase-protected properly:** scrypt (n=2^17, r=8, p=1), a random 16-byte salt per file, versioned format, created `0600` with `O_EXCL`. The CLI has no default passphrase.
63
+ - **Tested against hostile input:** 279 tests including Wycheproof and ACVP ML-KEM-768 vectors, and property-based fuzzing of the parsers. See [TESTING.md](TESTING.md).
64
+ - **Honest limits:** see Limitations and [SECURITY_NOTES.md](SECURITY_NOTES.md). The open medium-severity items are listed there.
65
+ - **Licence:** Apache-2.0.
66
+
67
+ ## Usage
68
+
69
+ ### Library
70
+
71
+ ```python
72
+ from pqblocks_files.keys import keygen, save_public_key, save_private_key, load_public_key, load_private_key
73
+ from pqblocks_files.encrypt import encrypt, decrypt, decrypt_with_mode
74
+ from pqblocks_files.pqtypes import KeyPair
75
+
76
+ kp = keygen()
77
+ save_public_key(kp, "alice.pub") # Bech32 text, mode 0444
78
+ save_private_key(kp, "alice.key", b"a long passphrase") # scrypt + ChaCha20-Poly1305, mode 0600, never overwrites
79
+
80
+ alice = KeyPair(public=load_public_key("alice.pub"), private=load_private_key("alice.key", b"a long passphrase"))
81
+ blob = encrypt(open("report.pdf", "rb").read(), [alice.public])
82
+ result = decrypt_with_mode(blob, alice) # result.plaintext, result.mode == "hybrid"
83
+ ```
84
+
85
+ `encrypt` takes a list of recipients; any one of their private keys opens the file.
86
+
87
+ ### Command line
88
+
89
+ ```bash
90
+ pqblocks-files keygen --output alice.pub --output-sec alice.key # prompts for a passphrase (twice)
91
+ pqblocks-files encrypt --recipient alice.pub --output report.pfsh report.pdf
92
+ pqblocks-files decrypt --key alice.key --output report.pdf report.pfsh # prompts for the passphrase
93
+ ```
94
+
95
+ For scripts use `--passphrase-file FILE` (one trailing newline is stripped; an empty passphrase is refused). The passphrase is never accepted as an argument, never has a default, and is never printed.
96
+
97
+ Exit codes: 0 success; 1 bad input or malformed file; 2 key not found in header or key file could not be unlocked; 3 ML-KEM key-check abort; 4 classical-only file refused (re-run with `--allow-classical`).
98
+
99
+ ### Downgrade policy
100
+
101
+ `decrypt()` has `require_pq=True` by default. A file that your key can open only through a classical-only (X25519) stanza raises `ClassicalOnlyRejected` instead of being read. Pass `require_pq=False` (CLI: `--allow-classical`) to accept it; `decrypt_with_mode()` tells you which mode opened the file.
102
+
103
+ ## API reference
104
+
105
+ `encrypt(plaintext: bytes, recipients: list[Recipient], classical_only: bool = False) -> bytes`
106
+ Complete `pfsh` v1 file. `classical_only=True` writes X25519-only stanzas (no post-quantum protection). Raises `ValueError` for no recipients or an all-zero ML-KEM key (a classical-only key used without `classical_only=True`), `TypeError` for wrong argument types.
107
+
108
+ `decrypt(pfsh_bytes: bytes, keypair: KeyPair, require_pq: bool = True) -> bytes`
109
+ Plaintext, or an exception; never partial output. Exceptions: `HeaderMACMismatch` (no stanza opens under this key, or the header is malformed), `ClassicalOnlyRejected`, `TruncatedFile`, `TagVerificationFailed`, `NonMonotonicCounter`, `MLKEMKeyCheckFailed`, `ValueError`.
110
+
111
+ `decrypt_with_mode(pfsh_bytes, keypair, require_pq=True) -> DecryptResult`
112
+ `DecryptResult(plaintext, mode)`, `mode` is `"hybrid"` or `"classical"` (`MODE_HYBRID`, `MODE_CLASSICAL` in `pqblocks_files.encrypt`). `plaintext` is hidden from `repr`.
113
+
114
+ `keygen(classical_only: bool = False) -> KeyPair`; `KeyPair(public: Recipient, private: bytes)` (private is hidden from `repr`); `Recipient(hybrid_pk: bytes, label: str = "")`.
115
+
116
+ `save_public_key(keypair, path)`, `load_public_key(path) -> Recipient`, `save_private_key(keypair, path, passphrase: bytes)`, `load_private_key(path, passphrase: bytes) -> bytes`. Loaders raise `ValueError` on any malformed, truncated, tampered or unknown-version file, and on an empty passphrase.
117
+
118
+ `parse_header` and the framing helpers in `pqblocks_files.encrypt` are internal and may change. Helpers that take a caller-chosen file key or ephemeral key (`_chunk`, `_encode_header`, the `_eph_x25519_sk` parameters in `kem`) are private on purpose: reusing a key would reuse a keystream.
119
+
120
+ ## Limitations
121
+
122
+ - **Whole file in memory:** `encrypt` and `decrypt` take and return `bytes`; there is no streaming API.
123
+ - **Decrypt is slower than encrypt:** at 10 MB the library-level median was 0.18 s to decrypt against 0.02 s to encrypt (see [BENCHMARKS.md](BENCHMARKS.md)). The cause was not profiled.
124
+ - **No sender authentication or signatures:** anyone who has your public key can create a file for you. Use a signature scheme on top if you need provenance.
125
+ - **No zeroization** of keys or plaintext (Python `bytes` are immutable); see [SECURITY_NOTES.md](SECURITY_NOTES.md).
126
+ - **Pre-1.0 format and API:** the key-file format is versioned (v1) but may change before 1.0. Key files from earlier unreleased builds are refused.
127
+ - **Key distribution is out of scope:** nothing authenticates a public key file to a person.
128
+ - **Open medium-severity design items** (combiner does not bind the X25519 ciphertext and public keys; shared HKDF label in classical mode; 128-bit file key) are listed in [SECURITY_NOTES.md](SECURITY_NOTES.md).
129
+
130
+ ## Security notes
131
+
132
+ See [SECURITY_NOTES.md](SECURITY_NOTES.md) and [SECURITY.md](SECURITY.md). Not independently audited; not FIPS 140-3 or CMVP validated.
133
+
134
+ ## Verification
135
+
136
+ [TESTING.md](TESTING.md) · [BENCHMARKS.md](BENCHMARKS.md) · [EVIDENCE.md](EVIDENCE.md) · [VERIFICATION_REPORT.md](VERIFICATION_REPORT.md) · [USE_CASES.md](USE_CASES.md) · [AGENTS.md](AGENTS.md)
137
+
138
+ ## Part of PQBlocks
139
+
140
+ [PQBlocks](https://github.com/PQBlocks) builds open, tested building blocks for the post-quantum transition. This package is its hybrid file-encryption tool.
@@ -0,0 +1,107 @@
1
+ # pqblocks-files
2
+
3
+ Hybrid post-quantum file encryption for Python and the command line: ML-KEM-768 plus X25519 key encapsulation, with the payload sealed in 64 KiB ChaCha20-Poly1305 chunks (the `pfsh` v1 file format).
4
+ Use it to encrypt files or byte strings to one or more recipients' public keys so that a future quantum computer, or a break of either primitive alone, does not expose them.
5
+ Implements NIST FIPS 203 (ML-KEM-768, via liboqs), RFC 7748 (X25519), RFC 8439 (ChaCha20-Poly1305) and RFC 5869 (HKDF). **Not FIPS or CMVP validated. Pre-1.0: not independently audited.**
6
+
7
+ ```bash
8
+ pip install pqblocks-files # needs a system liboqs 0.15.x or 0.16.x, see Requirements
9
+ ```
10
+
11
+ ```python
12
+ from pqblocks_files.encrypt import encrypt, decrypt
13
+ from pqblocks_files.keys import keygen
14
+
15
+ keypair = keygen() # ML-KEM-768 + X25519
16
+ blob = encrypt(b"quarterly numbers", [keypair.public]) # fresh random file key every call
17
+ assert decrypt(blob, keypair) == b"quarterly numbers" # refuses classical-only files by default
18
+ ```
19
+
20
+ ## Requirements
21
+
22
+ - Python 3.11 or newer; `cryptography` and `bech32` (installed by pip).
23
+ - **A shared liboqs** (`liboqs.so`, version 0.15.x or 0.16.x) found by the system loader, or pointed to with `OQS_LIB_PATH=/path/to/liboqs.so.9`. Any other liboqs version is refused at import with a `RuntimeError`. pip does not install liboqs. This was verified against liboqs 0.16.0; the CI workflow builds 0.15.0.
24
+
25
+ ## Why PQBlocks
26
+
27
+ - **Hybrid by default:** every file key is wrapped under ML-KEM-768 *and* X25519. Classical-only files are a loud, explicit opt-in on both write (`classical_only=True`) and read (`require_pq=False`).
28
+ - **No foot-guns in the API:** no nonce, file-key or algorithm parameters. The file key is always fresh from the OS CSPRNG.
29
+ - **Private keys are passphrase-protected properly:** scrypt (n=2^17, r=8, p=1), a random 16-byte salt per file, versioned format, created `0600` with `O_EXCL`. The CLI has no default passphrase.
30
+ - **Tested against hostile input:** 279 tests including Wycheproof and ACVP ML-KEM-768 vectors, and property-based fuzzing of the parsers. See [TESTING.md](TESTING.md).
31
+ - **Honest limits:** see Limitations and [SECURITY_NOTES.md](SECURITY_NOTES.md). The open medium-severity items are listed there.
32
+ - **Licence:** Apache-2.0.
33
+
34
+ ## Usage
35
+
36
+ ### Library
37
+
38
+ ```python
39
+ from pqblocks_files.keys import keygen, save_public_key, save_private_key, load_public_key, load_private_key
40
+ from pqblocks_files.encrypt import encrypt, decrypt, decrypt_with_mode
41
+ from pqblocks_files.pqtypes import KeyPair
42
+
43
+ kp = keygen()
44
+ save_public_key(kp, "alice.pub") # Bech32 text, mode 0444
45
+ save_private_key(kp, "alice.key", b"a long passphrase") # scrypt + ChaCha20-Poly1305, mode 0600, never overwrites
46
+
47
+ alice = KeyPair(public=load_public_key("alice.pub"), private=load_private_key("alice.key", b"a long passphrase"))
48
+ blob = encrypt(open("report.pdf", "rb").read(), [alice.public])
49
+ result = decrypt_with_mode(blob, alice) # result.plaintext, result.mode == "hybrid"
50
+ ```
51
+
52
+ `encrypt` takes a list of recipients; any one of their private keys opens the file.
53
+
54
+ ### Command line
55
+
56
+ ```bash
57
+ pqblocks-files keygen --output alice.pub --output-sec alice.key # prompts for a passphrase (twice)
58
+ pqblocks-files encrypt --recipient alice.pub --output report.pfsh report.pdf
59
+ pqblocks-files decrypt --key alice.key --output report.pdf report.pfsh # prompts for the passphrase
60
+ ```
61
+
62
+ For scripts use `--passphrase-file FILE` (one trailing newline is stripped; an empty passphrase is refused). The passphrase is never accepted as an argument, never has a default, and is never printed.
63
+
64
+ Exit codes: 0 success; 1 bad input or malformed file; 2 key not found in header or key file could not be unlocked; 3 ML-KEM key-check abort; 4 classical-only file refused (re-run with `--allow-classical`).
65
+
66
+ ### Downgrade policy
67
+
68
+ `decrypt()` has `require_pq=True` by default. A file that your key can open only through a classical-only (X25519) stanza raises `ClassicalOnlyRejected` instead of being read. Pass `require_pq=False` (CLI: `--allow-classical`) to accept it; `decrypt_with_mode()` tells you which mode opened the file.
69
+
70
+ ## API reference
71
+
72
+ `encrypt(plaintext: bytes, recipients: list[Recipient], classical_only: bool = False) -> bytes`
73
+ Complete `pfsh` v1 file. `classical_only=True` writes X25519-only stanzas (no post-quantum protection). Raises `ValueError` for no recipients or an all-zero ML-KEM key (a classical-only key used without `classical_only=True`), `TypeError` for wrong argument types.
74
+
75
+ `decrypt(pfsh_bytes: bytes, keypair: KeyPair, require_pq: bool = True) -> bytes`
76
+ Plaintext, or an exception; never partial output. Exceptions: `HeaderMACMismatch` (no stanza opens under this key, or the header is malformed), `ClassicalOnlyRejected`, `TruncatedFile`, `TagVerificationFailed`, `NonMonotonicCounter`, `MLKEMKeyCheckFailed`, `ValueError`.
77
+
78
+ `decrypt_with_mode(pfsh_bytes, keypair, require_pq=True) -> DecryptResult`
79
+ `DecryptResult(plaintext, mode)`, `mode` is `"hybrid"` or `"classical"` (`MODE_HYBRID`, `MODE_CLASSICAL` in `pqblocks_files.encrypt`). `plaintext` is hidden from `repr`.
80
+
81
+ `keygen(classical_only: bool = False) -> KeyPair`; `KeyPair(public: Recipient, private: bytes)` (private is hidden from `repr`); `Recipient(hybrid_pk: bytes, label: str = "")`.
82
+
83
+ `save_public_key(keypair, path)`, `load_public_key(path) -> Recipient`, `save_private_key(keypair, path, passphrase: bytes)`, `load_private_key(path, passphrase: bytes) -> bytes`. Loaders raise `ValueError` on any malformed, truncated, tampered or unknown-version file, and on an empty passphrase.
84
+
85
+ `parse_header` and the framing helpers in `pqblocks_files.encrypt` are internal and may change. Helpers that take a caller-chosen file key or ephemeral key (`_chunk`, `_encode_header`, the `_eph_x25519_sk` parameters in `kem`) are private on purpose: reusing a key would reuse a keystream.
86
+
87
+ ## Limitations
88
+
89
+ - **Whole file in memory:** `encrypt` and `decrypt` take and return `bytes`; there is no streaming API.
90
+ - **Decrypt is slower than encrypt:** at 10 MB the library-level median was 0.18 s to decrypt against 0.02 s to encrypt (see [BENCHMARKS.md](BENCHMARKS.md)). The cause was not profiled.
91
+ - **No sender authentication or signatures:** anyone who has your public key can create a file for you. Use a signature scheme on top if you need provenance.
92
+ - **No zeroization** of keys or plaintext (Python `bytes` are immutable); see [SECURITY_NOTES.md](SECURITY_NOTES.md).
93
+ - **Pre-1.0 format and API:** the key-file format is versioned (v1) but may change before 1.0. Key files from earlier unreleased builds are refused.
94
+ - **Key distribution is out of scope:** nothing authenticates a public key file to a person.
95
+ - **Open medium-severity design items** (combiner does not bind the X25519 ciphertext and public keys; shared HKDF label in classical mode; 128-bit file key) are listed in [SECURITY_NOTES.md](SECURITY_NOTES.md).
96
+
97
+ ## Security notes
98
+
99
+ See [SECURITY_NOTES.md](SECURITY_NOTES.md) and [SECURITY.md](SECURITY.md). Not independently audited; not FIPS 140-3 or CMVP validated.
100
+
101
+ ## Verification
102
+
103
+ [TESTING.md](TESTING.md) · [BENCHMARKS.md](BENCHMARKS.md) · [EVIDENCE.md](EVIDENCE.md) · [VERIFICATION_REPORT.md](VERIFICATION_REPORT.md) · [USE_CASES.md](USE_CASES.md) · [AGENTS.md](AGENTS.md)
104
+
105
+ ## Part of PQBlocks
106
+
107
+ [PQBlocks](https://github.com/PQBlocks) builds open, tested building blocks for the post-quantum transition. This package is its hybrid file-encryption tool.
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pqblocks-files"
7
+ version = "0.1.0"
8
+ description = "Hybrid post-quantum file encryption: ML-KEM-768 plus X25519 key encapsulation with chunked ChaCha20-Poly1305 in the pfsh v1 format."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ requires-python = ">=3.11"
13
+ authors = [{name = "The PQBlocks Authors"}]
14
+ keywords = ["post-quantum", "ml-kem", "x25519", "hybrid", "file-encryption", "chacha20-poly1305", "kem"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Security :: Cryptography",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ ]
26
+ dependencies = ["bech32>=1.2,<2", "cryptography>=42,<51"]
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest", "hypothesis"]
30
+
31
+ [project.scripts]
32
+ pqblocks-files = "pqblocks_files.cli:main"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/PQBlocks/hybrid-file-encryption"
36
+ Documentation = "https://github.com/PQBlocks/hybrid-file-encryption#readme"
37
+ Source = "https://github.com/PQBlocks/hybrid-file-encryption"
38
+ Changelog = "https://github.com/PQBlocks/hybrid-file-encryption/blob/main/CHANGELOG.md"
39
+ Issues = "https://github.com/PQBlocks/hybrid-file-encryption/issues"
40
+ Security = "https://github.com/PQBlocks/hybrid-file-encryption/security/policy"
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,92 @@
1
+ """AEAD layer: ChaCha20-Poly1305 and the HKDF key derivations for the pfsh v1 body and header.
2
+
3
+ Contract:
4
+ derive_payload_key(file_key: bytes, chunk_nonce: bytes) -> 32B
5
+ derive_header_mac_key(file_key: bytes) -> 32B
6
+ chacha20poly1305_encrypt(key, nonce, pt, aad=b'') -> ciphertext || tag
7
+ chacha20poly1305_decrypt(key, nonce, ct_tag, aad=b'') -> plaintext
8
+
9
+ Primitives come from pyca/cryptography (audited library).
10
+ HKDF-SHA256 via the same library. No hand-rolled crypto.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from cryptography.exceptions import InvalidTag
16
+ from cryptography.hazmat.primitives import hashes
17
+ from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
18
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
19
+
20
+ from pqblocks_files.pqtypes import TagVerificationFailed
21
+
22
+
23
+ def derive_payload_key(file_key: bytes, chunk_nonce: bytes) -> bytes:
24
+ """HKDF-SHA256(ikm=file_key, salt=chunk_nonce, info='payload') -> 32B."""
25
+ if len(file_key) != 16:
26
+ raise ValueError(f"file_key must be 16 bytes, got {len(file_key)}")
27
+ if len(chunk_nonce) != 12:
28
+ raise ValueError(f"chunk_nonce must be 12 bytes, got {len(chunk_nonce)}")
29
+ hkdf = HKDF(
30
+ algorithm=hashes.SHA256(),
31
+ length=32,
32
+ salt=chunk_nonce,
33
+ info=b"payload",
34
+ )
35
+ return hkdf.derive(file_key)
36
+
37
+
38
+ def derive_header_mac_key(file_key: bytes) -> bytes:
39
+ """HKDF-SHA256(ikm=file_key, salt=b'', info='header') -> 32B."""
40
+ if len(file_key) != 16:
41
+ raise ValueError(f"file_key must be 16 bytes, got {len(file_key)}")
42
+ hkdf = HKDF(
43
+ algorithm=hashes.SHA256(),
44
+ length=32,
45
+ salt=b"",
46
+ info=b"header",
47
+ )
48
+ return hkdf.derive(file_key)
49
+
50
+
51
+ def chacha20poly1305_encrypt(
52
+ key: bytes,
53
+ nonce: bytes,
54
+ pt: bytes,
55
+ aad: bytes = b"",
56
+ ) -> bytes:
57
+ """Encrypt pt with ChaCha20-Poly1305. Returns ciphertext || tag.
58
+
59
+ key: 32 bytes, nonce: 12 bytes. Output length = len(pt) + 16.
60
+ """
61
+ if len(key) != 32:
62
+ raise ValueError(f"key must be 32 bytes, got {len(key)}")
63
+ if len(nonce) != 12:
64
+ raise ValueError(f"nonce must be 12 bytes, got {len(nonce)}")
65
+ aead = ChaCha20Poly1305(key)
66
+ return aead.encrypt(nonce, pt, aad)
67
+
68
+
69
+ def chacha20poly1305_decrypt(
70
+ key: bytes,
71
+ nonce: bytes,
72
+ ct_tag: bytes,
73
+ aad: bytes = b"",
74
+ ) -> bytes:
75
+ """Decrypt ct_tag with ChaCha20-Poly1305. Returns plaintext.
76
+
77
+ Raises TagVerificationFailed if the Poly1305 tag does not verify.
78
+ key: 32 bytes, nonce: 12 bytes.
79
+ """
80
+ if len(key) != 32:
81
+ raise ValueError(f"key must be 32 bytes, got {len(key)}")
82
+ if len(nonce) != 12:
83
+ raise ValueError(f"nonce must be 12 bytes, got {len(nonce)}")
84
+ if len(ct_tag) < 16:
85
+ raise TagVerificationFailed(
86
+ f"ct_tag too short: {len(ct_tag)} bytes (minimum 16 for tag)"
87
+ )
88
+ aead = ChaCha20Poly1305(key)
89
+ try:
90
+ return aead.decrypt(nonce, ct_tag, aad)
91
+ except InvalidTag:
92
+ raise TagVerificationFailed("Poly1305 tag verification failed") from None