@shieldfive/crypto 1.0.0-alpha.2

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 (104) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/LICENSE +201 -0
  3. package/README.md +241 -0
  4. package/SECURITY.md +123 -0
  5. package/dist/format/header.d.ts +60 -0
  6. package/dist/format/header.d.ts.map +1 -0
  7. package/dist/format/header.js +203 -0
  8. package/dist/format/header.js.map +1 -0
  9. package/dist/identity/index.d.ts +117 -0
  10. package/dist/identity/index.d.ts.map +1 -0
  11. package/dist/identity/index.js +217 -0
  12. package/dist/identity/index.js.map +1 -0
  13. package/dist/index.d.ts +52 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +124 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/internal/encoding.d.ts +33 -0
  18. package/dist/internal/encoding.d.ts.map +1 -0
  19. package/dist/internal/encoding.js +136 -0
  20. package/dist/internal/encoding.js.map +1 -0
  21. package/dist/internal/hkdf.d.ts +14 -0
  22. package/dist/internal/hkdf.d.ts.map +1 -0
  23. package/dist/internal/hkdf.js +27 -0
  24. package/dist/internal/hkdf.js.map +1 -0
  25. package/dist/internal/hmac.d.ts +9 -0
  26. package/dist/internal/hmac.d.ts.map +1 -0
  27. package/dist/internal/hmac.js +18 -0
  28. package/dist/internal/hmac.js.map +1 -0
  29. package/dist/internal/runtime.d.ts +29 -0
  30. package/dist/internal/runtime.d.ts.map +1 -0
  31. package/dist/internal/runtime.js +67 -0
  32. package/dist/internal/runtime.js.map +1 -0
  33. package/dist/internal/sodium.d.ts +12 -0
  34. package/dist/internal/sodium.d.ts.map +1 -0
  35. package/dist/internal/sodium.js +34 -0
  36. package/dist/internal/sodium.js.map +1 -0
  37. package/dist/internal/types.d.ts +94 -0
  38. package/dist/internal/types.d.ts.map +1 -0
  39. package/dist/internal/types.js +65 -0
  40. package/dist/internal/types.js.map +1 -0
  41. package/dist/kdf/argon2id.d.ts +72 -0
  42. package/dist/kdf/argon2id.d.ts.map +1 -0
  43. package/dist/kdf/argon2id.js +97 -0
  44. package/dist/kdf/argon2id.js.map +1 -0
  45. package/dist/migration/v0-bridge.d.ts +94 -0
  46. package/dist/migration/v0-bridge.d.ts.map +1 -0
  47. package/dist/migration/v0-bridge.js +203 -0
  48. package/dist/migration/v0-bridge.js.map +1 -0
  49. package/dist/streams/aes-gcm-v1.d.ts +76 -0
  50. package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
  51. package/dist/streams/aes-gcm-v1.js +322 -0
  52. package/dist/streams/aes-gcm-v1.js.map +1 -0
  53. package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
  54. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
  55. package/dist/suites/aes-gcm-v0/api.js +110 -0
  56. package/dist/suites/aes-gcm-v0/api.js.map +1 -0
  57. package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
  58. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
  59. package/dist/suites/aes-gcm-v1/api.js +179 -0
  60. package/dist/suites/aes-gcm-v1/api.js.map +1 -0
  61. package/dist/suites/aes-gcm-v1/index.d.ts +56 -0
  62. package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
  63. package/dist/suites/aes-gcm-v1/index.js +174 -0
  64. package/dist/suites/aes-gcm-v1/index.js.map +1 -0
  65. package/dist/suites/pq-hybrid-v1/api.d.ts +40 -0
  66. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
  67. package/dist/suites/pq-hybrid-v1/api.js +157 -0
  68. package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
  69. package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
  70. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
  71. package/dist/suites/pq-hybrid-v1/index.js +225 -0
  72. package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
  73. package/dist/suites/xchacha-v1/api.d.ts +29 -0
  74. package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
  75. package/dist/suites/xchacha-v1/api.js +151 -0
  76. package/dist/suites/xchacha-v1/api.js.map +1 -0
  77. package/dist/suites/xchacha-v1/index.d.ts +50 -0
  78. package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
  79. package/dist/suites/xchacha-v1/index.js +133 -0
  80. package/dist/suites/xchacha-v1/index.js.map +1 -0
  81. package/package.json +112 -0
  82. package/spec/format-v0.md +81 -0
  83. package/spec/format-v1.md +245 -0
  84. package/spec/key-derivation.md +122 -0
  85. package/spec/threat-model.md +152 -0
  86. package/src/format/header.ts +284 -0
  87. package/src/identity/index.ts +358 -0
  88. package/src/index.ts +197 -0
  89. package/src/internal/encoding.ts +153 -0
  90. package/src/internal/hkdf.ts +47 -0
  91. package/src/internal/hmac.ts +33 -0
  92. package/src/internal/runtime.ts +80 -0
  93. package/src/internal/sodium.ts +38 -0
  94. package/src/internal/types.ts +128 -0
  95. package/src/kdf/argon2id.ts +164 -0
  96. package/src/migration/v0-bridge.ts +347 -0
  97. package/src/streams/aes-gcm-v1.ts +443 -0
  98. package/src/suites/aes-gcm-v0/api.ts +155 -0
  99. package/src/suites/aes-gcm-v1/api.ts +291 -0
  100. package/src/suites/aes-gcm-v1/index.ts +266 -0
  101. package/src/suites/pq-hybrid-v1/api.ts +259 -0
  102. package/src/suites/pq-hybrid-v1/index.ts +343 -0
  103. package/src/suites/xchacha-v1/api.ts +251 -0
  104. package/src/suites/xchacha-v1/index.ts +213 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Cipher suite 0x02: XChaCha20-Poly1305 v1.
3
+ *
4
+ * 256-bit key, 192-bit nonce. Fresh per-file content key. Per-chunk AEAD
5
+ * with the same file_id-bound AAD as the AES-GCM suite. Implementation via
6
+ * libsodium-wrappers-sumo's `crypto_aead_xchacha20poly1305_ietf_*`.
7
+ *
8
+ * Why not secretstream? secretstream is a higher-level construction that
9
+ * embeds its own state machine and chunk count. We want chunk-level random
10
+ * access (for streaming downloads with range requests), so we use the AEAD
11
+ * primitive directly with our own AAD-bound chunk indexing.
12
+ */
13
+ import { buildChunkAad } from '../../format/header.js';
14
+ import { HKDF_INFO, HEADER_SIZES, } from '../../internal/types.js';
15
+ import { concatBytes, uint64BE } from '../../internal/encoding.js';
16
+ import { hkdfSha256 } from '../../internal/hkdf.js';
17
+ import { randomBytes } from '../../internal/runtime.js';
18
+ import { getSodium } from '../../internal/sodium.js';
19
+ export const XCHACHA_V1_KEY_BYTES = 32;
20
+ export const XCHACHA_V1_NONCE_BYTES = 24;
21
+ export const XCHACHA_V1_TAG_BYTES = 16;
22
+ /** Suite payload layout: 72-byte secretbox-wrapped key + 24-byte nonce = 96 bytes. */
23
+ export const XCHACHA_V1_SUITE_PAYLOAD_LENGTH = 96;
24
+ export function buildXChaChaV1SuitePayload(payload) {
25
+ if (payload.wrappedKey.length !== 72) {
26
+ throw new RangeError('xchacha-v1: wrappedKey must be 72 bytes');
27
+ }
28
+ if (payload.wrapNonce.length !== XCHACHA_V1_NONCE_BYTES) {
29
+ throw new RangeError('xchacha-v1: wrapNonce must be 24 bytes');
30
+ }
31
+ return concatBytes([payload.wrappedKey, payload.wrapNonce]);
32
+ }
33
+ export function parseXChaChaV1SuitePayload(bytes) {
34
+ if (bytes.length !== XCHACHA_V1_SUITE_PAYLOAD_LENGTH) {
35
+ throw new RangeError('xchacha-v1: suite payload must be 96 bytes');
36
+ }
37
+ return {
38
+ wrappedKey: bytes.slice(0, 72),
39
+ wrapNonce: bytes.slice(72, 96),
40
+ };
41
+ }
42
+ async function deriveChunkKey(contentKey, fileId) {
43
+ return hkdfSha256({
44
+ ikm: contentKey,
45
+ salt: fileId,
46
+ info: HKDF_INFO.XCHACHA_CHUNK_KEY,
47
+ length: XCHACHA_V1_KEY_BYTES,
48
+ });
49
+ }
50
+ async function deriveNoncePrefix(fileId) {
51
+ // XChaCha's 24-byte nonce: 16-byte file-derived prefix + 8-byte counter.
52
+ return hkdfSha256({
53
+ ikm: fileId,
54
+ info: HKDF_INFO.XCHACHA_NONCE_PREFIX,
55
+ length: 16,
56
+ });
57
+ }
58
+ function buildNonce(noncePrefix, chunkIndex) {
59
+ const nonce = new Uint8Array(XCHACHA_V1_NONCE_BYTES);
60
+ nonce.set(noncePrefix, 0);
61
+ nonce.set(uint64BE(chunkIndex), 16);
62
+ return nonce;
63
+ }
64
+ export function generateContentMaterial() {
65
+ return {
66
+ contentKey: randomBytes(XCHACHA_V1_KEY_BYTES),
67
+ fileId: randomBytes(HEADER_SIZES.FILE_ID),
68
+ };
69
+ }
70
+ export async function createChunkContext(contentKey, fileId, totalChunks) {
71
+ const chunkKey = await deriveChunkKey(contentKey, fileId);
72
+ const noncePrefix = await deriveNoncePrefix(fileId);
73
+ return { chunkKey, noncePrefix, totalChunks };
74
+ }
75
+ export async function encryptChunk(ctx, chunkIndex, plaintext) {
76
+ const sodium = await getSodium();
77
+ const isFinal = chunkIndex === ctx.totalChunks - 1;
78
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal);
79
+ const nonce = buildNonce(ctx.noncePrefix, chunkIndex);
80
+ return sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, aad, null, nonce, ctx.chunkKey);
81
+ }
82
+ export async function decryptChunk(ctx, chunkIndex, ciphertext) {
83
+ const sodium = await getSodium();
84
+ const isFinal = chunkIndex === ctx.totalChunks - 1;
85
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal);
86
+ const nonce = buildNonce(ctx.noncePrefix, chunkIndex);
87
+ const result = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null, ciphertext, aad, nonce, ctx.chunkKey);
88
+ return result;
89
+ }
90
+ export async function wrapContentKey(options) {
91
+ const sodium = await getSodium();
92
+ const { contentKey, envelopeKey } = options;
93
+ if (contentKey.length !== XCHACHA_V1_KEY_BYTES) {
94
+ throw new RangeError('wrapContentKey: contentKey must be 32 bytes');
95
+ }
96
+ if (envelopeKey.length !== XCHACHA_V1_KEY_BYTES) {
97
+ throw new RangeError('wrapContentKey: envelopeKey must be 32 bytes');
98
+ }
99
+ const wrapNonce = randomBytes(XCHACHA_V1_NONCE_BYTES);
100
+ // crypto_secretbox_easy: outputs 16-byte poly1305 tag + ciphertext = 48 bytes
101
+ const wrapped = sodium.crypto_secretbox_easy(contentKey, wrapNonce, envelopeKey);
102
+ if (wrapped.length !== 48) {
103
+ throw new Error('wrapContentKey: unexpected wrapped length');
104
+ }
105
+ // Pad to 72 bytes for fixed suite_payload size
106
+ const padded = new Uint8Array(72);
107
+ padded.set(wrapped, 0);
108
+ return { wrapped: padded, wrapNonce };
109
+ }
110
+ export async function unwrapContentKey(options) {
111
+ const sodium = await getSodium();
112
+ const { envelopeKey, wrappedField, wrapNonce } = options;
113
+ if (envelopeKey.length !== XCHACHA_V1_KEY_BYTES) {
114
+ throw new RangeError('unwrapContentKey: envelopeKey must be 32 bytes');
115
+ }
116
+ if (wrappedField.length !== 72) {
117
+ throw new RangeError('unwrapContentKey: wrappedField must be 72 bytes');
118
+ }
119
+ if (wrapNonce.length !== XCHACHA_V1_NONCE_BYTES) {
120
+ throw new RangeError('unwrapContentKey: wrapNonce must be 24 bytes');
121
+ }
122
+ // First 48 bytes are tag+key, the rest is reserved zeros.
123
+ const wrapped = wrappedField.slice(0, 48);
124
+ const unwrapped = sodium.crypto_secretbox_open_easy(wrapped, wrapNonce, envelopeKey);
125
+ if (!unwrapped) {
126
+ throw new Error('unwrapContentKey: unwrap failed (wrong envelope key?)');
127
+ }
128
+ return unwrapped;
129
+ }
130
+ export function getSuitePayloadFromHeader(header) {
131
+ return parseXChaChaV1SuitePayload(header.suitePayload);
132
+ }
133
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/suites/xchacha-v1/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACtD,OAAO,EACL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S,EACT,WAAW,CACZ,CAAA;IACD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IAC1E,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,MAAoB;IAEpB,OAAO,0BAA0B,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;AACxD,CAAC"}
package/package.json ADDED
@@ -0,0 +1,112 @@
1
+ {
2
+ "name": "@shieldfive/crypto",
3
+ "version": "1.0.0-alpha.2",
4
+ "description": "Open, audited-ready, post-quantum-hybrid client-side encryption for cloud storage. The cryptographic core of ShieldFive.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://github.com/shieldfive-labs/crypto",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/shieldfive-labs/crypto.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/shieldfive-labs/crypto/issues",
14
+ "email": "security@shieldfive.com"
15
+ },
16
+ "keywords": [
17
+ "encryption",
18
+ "zero-knowledge",
19
+ "end-to-end-encryption",
20
+ "post-quantum",
21
+ "ml-kem",
22
+ "kyber",
23
+ "xchacha20-poly1305",
24
+ "aes-gcm",
25
+ "webcrypto",
26
+ "cloud-storage"
27
+ ],
28
+ "author": "ShieldFive Labs <security@shieldfive.com>",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./package.json": "./package.json",
35
+ "./aes-gcm-v1": {
36
+ "types": "./dist/suites/aes-gcm-v1/api.d.ts",
37
+ "default": "./dist/suites/aes-gcm-v1/api.js"
38
+ },
39
+ "./xchacha-v1": {
40
+ "types": "./dist/suites/xchacha-v1/api.d.ts",
41
+ "default": "./dist/suites/xchacha-v1/api.js"
42
+ },
43
+ "./pq-hybrid-v1": {
44
+ "types": "./dist/suites/pq-hybrid-v1/api.d.ts",
45
+ "default": "./dist/suites/pq-hybrid-v1/api.js"
46
+ },
47
+ "./legacy-v0": {
48
+ "types": "./dist/suites/aes-gcm-v0/api.d.ts",
49
+ "default": "./dist/suites/aes-gcm-v0/api.js"
50
+ },
51
+ "./streams/aes-gcm-v1": {
52
+ "types": "./dist/streams/aes-gcm-v1.d.ts",
53
+ "default": "./dist/streams/aes-gcm-v1.js"
54
+ },
55
+ "./kdf/argon2id": {
56
+ "types": "./dist/kdf/argon2id.d.ts",
57
+ "default": "./dist/kdf/argon2id.js"
58
+ },
59
+ "./identity": {
60
+ "types": "./dist/identity/index.d.ts",
61
+ "default": "./dist/identity/index.js"
62
+ },
63
+ "./migration/v0": {
64
+ "types": "./dist/migration/v0-bridge.d.ts",
65
+ "default": "./dist/migration/v0-bridge.js"
66
+ },
67
+ "./format": {
68
+ "types": "./dist/format/header.d.ts",
69
+ "default": "./dist/format/header.js"
70
+ }
71
+ },
72
+ "files": [
73
+ "dist",
74
+ "src",
75
+ "spec",
76
+ "workers",
77
+ "README.md",
78
+ "SECURITY.md",
79
+ "LICENSE",
80
+ "CHANGELOG.md"
81
+ ],
82
+ "engines": {
83
+ "node": ">=20"
84
+ },
85
+ "sideEffects": false,
86
+ "scripts": {
87
+ "build": "tsc -p tsconfig.json",
88
+ "clean": "rm -rf dist",
89
+ "lint": "eslint src tests",
90
+ "test": "node --experimental-vm-modules --test --import tsx tests/**/*.test.ts",
91
+ "test:unit": "node --experimental-vm-modules --test --import tsx tests/unit/*.test.ts",
92
+ "test:integration": "node --experimental-vm-modules --test --import tsx tests/integration/*.test.ts",
93
+ "format": "prettier --write \"src/**/*.ts\" \"tests/**/*.ts\""
94
+ },
95
+ "peerDependencies": {
96
+ "libsodium-wrappers-sumo": "^0.8.2"
97
+ },
98
+ "peerDependenciesMeta": {
99
+ "libsodium-wrappers-sumo": {
100
+ "optional": true
101
+ }
102
+ },
103
+ "dependencies": {
104
+ "@noble/post-quantum": "^0.5.3"
105
+ },
106
+ "devDependencies": {
107
+ "@types/node": "^22.10.0",
108
+ "libsodium-wrappers-sumo": "^0.8.2",
109
+ "tsx": "^4.20.0",
110
+ "typescript": "^5.7.2"
111
+ }
112
+ }
@@ -0,0 +1,81 @@
1
+ # ShieldFive Crypto File Format v0 (legacy)
2
+
3
+ This document describes the **legacy** ShieldFive production file format,
4
+ present in production from project inception through the v1 transition.
5
+ It is included here so that v1-aware readers can read v0 files indefinitely.
6
+
7
+ **v0 is read-only as of the v1 release.** New encryptions MUST use v1.
8
+
9
+ ## Wire format
10
+
11
+ v0 files are stored as the concatenation of independently-encrypted
12
+ AES-256-GCM chunks:
13
+
14
+ ```
15
+ v0_file := chunk_0 || chunk_1 || ... || chunk_n
16
+ chunk_i := AES-GCM(key=content_key, iv=iv_i, aad=∅, plaintext=plain_i)
17
+ ```
18
+
19
+ Each chunk's ciphertext includes its 16-byte GCM authentication tag.
20
+
21
+ There is **no on-disk header**. Decryption requires the following
22
+ out-of-band metadata, retrieved from the application database:
23
+
24
+ ```
25
+ cipher_version = 1 (uint, currently always 1)
26
+ cipher_chunk_size = 5*1024*1024 or 8*1024*1024 (uint, plaintext bytes per chunk)
27
+ cipher_nonce_prefix = base64(4 random bytes) (per-file)
28
+ csk_wrapped = base64(AES-GCM-wrapped 32-byte content key)
29
+ csk_iv = base64(12-byte IV used for wrapping)
30
+ cipher_parts_sha1 = [SHA-1(chunk_0), ..., SHA-1(chunk_n)] (storage integrity)
31
+ ```
32
+
33
+ The IV for chunk `i` is:
34
+
35
+ ```
36
+ iv_i := nonce_prefix (4 bytes) || uint64_be(i)
37
+ ```
38
+
39
+ The content key is unwrapped with the parent folder/root key using
40
+ AES-GCM. The wrapped key and wrap IV are stored in the database, not in
41
+ the file.
42
+
43
+ ## Limitations of v0 (addressed in v1)
44
+
45
+ These are the reasons v0 is being retired in favor of v1:
46
+
47
+ 1. **No on-disk version byte.** A v0 file is indistinguishable from
48
+ arbitrary ciphertext without out-of-band context.
49
+ 2. **No file_id binding.** Chunks can be spliced between two files
50
+ encrypted with the same content key (which should not occur, but is
51
+ not structurally prevented).
52
+ 3. **No truncation detection.** Trailing chunks can be removed and the
53
+ reader will produce a valid (truncated) plaintext. v0 deployments
54
+ detect this at the application layer using `cipher_parts_sha1`, not in
55
+ the AEAD.
56
+ 4. **No AAD on chunks.** Chunk index, total chunks, and is-final flag are
57
+ not authenticated. Reordering is detected only because the IV depends
58
+ on the index, but reordering does not produce a clear error message.
59
+ 5. **No post-quantum protection.**
60
+ 6. **Suite is hardcoded.** Future cipher upgrades require a new
61
+ `cipher_version` and a database migration, not a per-file decision.
62
+
63
+ ## Migration path
64
+
65
+ v1-aware applications:
66
+
67
+ - MUST be able to decrypt v0 files indefinitely.
68
+ - SHOULD migrate stored v0 files to v1 in the background as users
69
+ download/re-upload them or via batch re-encryption.
70
+ - MUST NOT issue new v0 writes once a v1 deployment is live.
71
+
72
+ The reference v0 implementation lives in `src/suites/aes-gcm-v0/` and
73
+ exposes only a `decryptV0` function. There is no `encryptV0` exported
74
+ symbol; this is intentional.
75
+
76
+ ## Security note
77
+
78
+ v0 is not broken. It is an older design with weaker structural guarantees
79
+ than v1. Files encrypted with v0 remain confidential under the original
80
+ threat model (server compromise, network interception). The v1 upgrade
81
+ adds defense-in-depth, not a fix to a known v0 vulnerability.
@@ -0,0 +1,245 @@
1
+ # ShieldFive Crypto File Format v1
2
+
3
+ This document is the canonical specification for the v1 ShieldFive encrypted
4
+ file format. The implementation in this repository is a reference, not the
5
+ specification — when in doubt, this document governs.
6
+
7
+ ## Goals
8
+
9
+ The v1 format is designed to satisfy these properties simultaneously:
10
+
11
+ 1. **Self-describing.** A reviewer with only the encrypted blob and the
12
+ decryption key (no out-of-band metadata) can decrypt the file.
13
+ 2. **AEAD-bound chunk position.** Truncation, reordering, and chunk-mixing
14
+ between files are detected by the AEAD authenticator, not by application
15
+ logic.
16
+ 3. **Cipher-suite agile.** A single byte selects which cipher suite the file
17
+ was encrypted with. Adding a new suite does not change the parser.
18
+ 4. **Post-quantum hybrid by default.** The default suite combines a classical
19
+ AEAD with ML-KEM-1024 key encapsulation. Files encrypted today survive a
20
+ future cryptographically-relevant quantum computer for the duration of
21
+ the AEAD's classical security.
22
+ 5. **Streaming-friendly.** A reader can decrypt chunk N without buffering
23
+ chunks 0..N-1 in memory, and a writer can emit chunk N without buffering
24
+ future chunks.
25
+
26
+ ## Wire format
27
+
28
+ All multi-byte integers are big-endian. All byte counts are in octets.
29
+
30
+ ```
31
+ encrypted_file := header || chunk_0 || chunk_1 || ... || chunk_n
32
+ ```
33
+
34
+ ### Header
35
+
36
+ ```
37
+ header := magic (5 bytes) = "SF5\x01\x00"
38
+ || suite (1 byte) = cipher suite identifier
39
+ || flags (1 byte) = reserved, must be 0x00
40
+ || file_id (16 bytes) = random per-file identifier
41
+ || chunk_size (4 bytes) = uint32, plaintext bytes per chunk
42
+ || total_chunks (8 bytes) = uint64, total chunk count
43
+ || plaintext_size (8 bytes) = uint64, total plaintext bytes
44
+ || suite_payload_len (2 bytes) = uint16, length of suite_payload
45
+ || suite_payload (variable) = suite-specific bytes (see below)
46
+ || header_mac (32 bytes) = HMAC-SHA-256 over all above bytes
47
+ keyed with derived header_mac_key
48
+ ```
49
+
50
+ The first 5 bytes `53 46 35 01 00` (`"SF5\x01\x00"`) are the file magic. The
51
+ fourth byte is the format major version (0x01). The fifth is reserved for
52
+ future minor-version bumps that remain backward-compatible.
53
+
54
+ `suite` is one of:
55
+
56
+ | Value | Suite | Status |
57
+ | ------ | -------------------------------------- | -------- |
58
+ | `0x00` | (reserved, never assigned) | invalid |
59
+ | `0x01` | `aes-256-gcm-v1` | required |
60
+ | `0x02` | `xchacha20-poly1305-v1` | required |
61
+ | `0x03` | `pq-hybrid-xchacha-mlkem1024-v1` | default |
62
+ | `0x80` | (reserved, custom-suite range begins) | reserved |
63
+
64
+ `flags` is reserved; readers MUST reject any header with a non-zero flags
65
+ byte. Future versions may introduce flags such as
66
+ `0x01 = compressed-plaintext` or `0x02 = sparse-file-encoding`.
67
+
68
+ `file_id` is 16 cryptographically random bytes generated per file. It is
69
+ mixed into every chunk's AAD to bind ciphertext to its file. This prevents
70
+ chunk-mixing attacks where chunks from one file are spliced into another
71
+ file with the same content key.
72
+
73
+ `plaintext_size` is the exact number of plaintext bytes. It allows a reader
74
+ to detect truncation of the final chunk before AEAD verification, and to
75
+ allocate output buffers correctly.
76
+
77
+ `suite_payload` is suite-specific. See "Suite payloads" below.
78
+
79
+ `header_mac` authenticates the entire header (everything before the
80
+ `header_mac` field itself) under a key derived from the content key:
81
+
82
+ ```
83
+ header_mac_key := HKDF-SHA-256(
84
+ ikm = content_key,
85
+ salt = file_id,
86
+ info = "shieldfive/v1/header-mac",
87
+ L = 32
88
+ )
89
+ ```
90
+
91
+ Readers MUST verify `header_mac` before parsing `suite_payload` or any
92
+ chunk. A header_mac failure means the wrong content key was supplied or the
93
+ header has been tampered with.
94
+
95
+ ### Chunks
96
+
97
+ ```
98
+ chunk_i := length (4 bytes) = uint32, length of ciphertext field
99
+ || ciphertext (variable) = AEAD output (includes auth tag)
100
+ ```
101
+
102
+ The AEAD inputs for chunk `i` are:
103
+
104
+ ```
105
+ nonce = chunk_nonce(suite, file_id, i)
106
+ aad = "shieldfive/v1/chunk" || uint64_be(i) || uint64_be(total_chunks)
107
+ || uint8(is_final)
108
+ key = chunk_key(suite, content_key, file_id)
109
+ ```
110
+
111
+ where:
112
+
113
+ - `is_final` is `0x01` for chunk `i = total_chunks - 1`, otherwise `0x00`.
114
+ - `chunk_nonce` and `chunk_key` are defined per suite.
115
+ - `aad` is a fixed-length 36 bytes (19 bytes domain string + 8 + 8 + 1).
116
+
117
+ The plaintext input is:
118
+
119
+ - For all chunks except the final: exactly `chunk_size` plaintext bytes.
120
+ - For the final chunk: between 1 and `chunk_size` plaintext bytes such that
121
+ the sum of all chunks' plaintext lengths equals `plaintext_size`.
122
+
123
+ A chunk with zero plaintext bytes is invalid. A file with `plaintext_size`
124
+ of zero MUST be encoded with `total_chunks = 0` and zero chunks; it is the
125
+ caller's choice whether to permit empty plaintexts at all.
126
+
127
+ ### Length-prefix vs. fixed-size chunks
128
+
129
+ The length prefix exists because some suites (notably any future
130
+ length-extending suite) may emit ciphertext that is not exactly
131
+ `chunk_size + tag_size` bytes. For the suites defined in this version,
132
+ length is always `chunk_size + suite.tag_size` for non-final chunks. Readers
133
+ SHOULD validate this invariant.
134
+
135
+ ## Suite payloads
136
+
137
+ ### `0x01` — `aes-256-gcm-v1`
138
+
139
+ ```
140
+ suite_payload := wrapped_key (60 bytes) = AES-GCM-wrapped 32-byte content key
141
+ || wrap_iv (12 bytes) = AES-GCM IV used for wrapping
142
+ ```
143
+
144
+ - `chunk_key(content_key, file_id)` =
145
+ `HKDF-SHA-256(ikm=content_key, salt=file_id, info="shieldfive/v1/aes-gcm/chunk-key", L=32)`
146
+ - `chunk_nonce(file_id, i)` =
147
+ `truncate12(HKDF-SHA-256(ikm=file_id, salt="", info="shieldfive/v1/aes-gcm/nonce-prefix", L=12))[0..3]`
148
+ `|| uint64_be(i)`
149
+
150
+ The nonce prefix is derived from `file_id` so that two files encrypted with
151
+ the same content key (which never happens under correct use, but defense in
152
+ depth) cannot collide on a `(prefix, counter)` pair.
153
+
154
+ The wrapped content key is wrapped with the *parent envelope key* (folder
155
+ key, vault key, etc.) using AES-256-GCM. This wrapping is OUT OF SCOPE for
156
+ the on-disk file format and is the responsibility of the application's
157
+ keyring module. The 60-byte field above is for files that choose to embed
158
+ the wrapped key inline (e.g. exported files); files stored in the
159
+ ShieldFive vault store the wrapped key in the database and set this field
160
+ to 60 bytes of zero. Whether the field is inline or zero-filled is a deploy
161
+ decision; either way the field length is fixed.
162
+
163
+ ### `0x02` — `xchacha20-poly1305-v1`
164
+
165
+ ```
166
+ suite_payload := wrapped_key (72 bytes) = secretbox-wrapped 32-byte content key
167
+ || wrap_nonce (24 bytes) = XSalsa20 nonce for wrapping
168
+ ```
169
+
170
+ - `chunk_key(content_key, file_id)` =
171
+ `HKDF-SHA-256(ikm=content_key, salt=file_id, info="shieldfive/v1/xchacha/chunk-key", L=32)`
172
+ - `chunk_nonce(file_id, i)` =
173
+ `truncate24(HKDF-SHA-256(ikm=file_id, salt="", info="shieldfive/v1/xchacha/nonce-prefix", L=24))[0..15]`
174
+ `|| uint64_be(i)`
175
+
176
+ XChaCha20's 24-byte nonce gives us a 16-byte random prefix and an 8-byte
177
+ counter, which is structurally safer than AES-GCM's 4+8 split.
178
+
179
+ ### `0x03` — `pq-hybrid-xchacha-mlkem1024-v1` (default)
180
+
181
+ ```
182
+ suite_payload := mlkem_ciphertext (1568 bytes) = ML-KEM-1024 ciphertext
183
+ || classical_wrapped (72 bytes) = secretbox-wrapped classical share
184
+ || classical_nonce (24 bytes) = secretbox nonce for classical wrap
185
+ ```
186
+
187
+ The recipient holds:
188
+
189
+ - A classical key `K_c` (32 bytes), wrapped at the envelope layer like the
190
+ XChaCha suite.
191
+ - An ML-KEM-1024 keypair `(pk_pq, sk_pq)` derived deterministically from
192
+ the user's master secret (see `spec/key-derivation.md`).
193
+
194
+ Encryption:
195
+
196
+ 1. Sender generates a 32-byte classical share `S_c` randomly.
197
+ 2. Sender encapsulates against `pk_pq` to get `(mlkem_ciphertext, S_pq)`.
198
+ `S_pq` is a 32-byte shared secret.
199
+ 3. Combined content key `K = HKDF-SHA-256(ikm = S_c || S_pq, salt = file_id,
200
+ info = "shieldfive/v1/pq-hybrid/combine", L = 32)`.
201
+ 4. Sender wraps `S_c` with `K_c` using XSalsa20-Poly1305 secretbox to
202
+ produce `classical_wrapped`. (The PQ share is recovered from
203
+ `mlkem_ciphertext` via decapsulation; only the classical share needs
204
+ wrapping.)
205
+ 5. Subsequent chunks use the XChaCha20-Poly1305 chunk format with `K`.
206
+
207
+ Decryption:
208
+
209
+ 1. Reader decapsulates `mlkem_ciphertext` with `sk_pq` to recover `S_pq`.
210
+ 2. Reader unwraps `classical_wrapped` with `K_c` to recover `S_c`.
211
+ 3. Reader recomputes `K = HKDF-SHA-256(ikm = S_c || S_pq, ...)`.
212
+ 4. Reader verifies `header_mac` (which uses `K`).
213
+ 5. Reader processes chunks.
214
+
215
+ This construction is IND-CCA2 against an adversary who breaks *either* the
216
+ classical wrap *or* the PQ KEM, but not both. As long as one primitive
217
+ remains secure, the file is secure. Under correct use, both must be broken
218
+ to recover the plaintext.
219
+
220
+ ## Versioning policy
221
+
222
+ - **Format major version (4th byte of magic)** changes when the parser
223
+ changes incompatibly. Old readers MUST refuse to read newer major
224
+ versions.
225
+ - **Format minor version (5th byte of magic)** changes when fields are
226
+ added in ways that older readers can ignore. Currently 0x00. Old readers
227
+ encountering a minor version they don't recognize MUST refuse to decrypt
228
+ unless explicitly configured to ignore unknown minor versions.
229
+ - **Suite identifier** is independent of format version. New suites can be
230
+ added without changing the format version.
231
+
232
+ ## Compatibility with v0 (legacy production format)
233
+
234
+ The current ShieldFive production upload format predates this
235
+ specification. It is referred to as "v0" and is described in
236
+ `spec/format-v0.md`. v0 files do not have the SF5 magic; they are detected
237
+ by the absence of magic and by the presence of the database-stored
238
+ `cipher_version = 1` flag. ShieldFive applications MUST be able to read
239
+ v0 indefinitely; v0 writes are deprecated and SHOULD be migrated to v1.
240
+
241
+ ## Test vectors
242
+
243
+ Implementations MUST produce identical bit-for-bit output for the test
244
+ vectors in `tests/vectors/`. These vectors are computed from a fixed seed
245
+ and committed to the repository.