@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.
- package/CHANGELOG.md +81 -0
- package/LICENSE +201 -0
- package/README.md +241 -0
- package/SECURITY.md +123 -0
- package/dist/format/header.d.ts +60 -0
- package/dist/format/header.d.ts.map +1 -0
- package/dist/format/header.js +203 -0
- package/dist/format/header.js.map +1 -0
- package/dist/identity/index.d.ts +117 -0
- package/dist/identity/index.d.ts.map +1 -0
- package/dist/identity/index.js +217 -0
- package/dist/identity/index.js.map +1 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +124 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/encoding.d.ts +33 -0
- package/dist/internal/encoding.d.ts.map +1 -0
- package/dist/internal/encoding.js +136 -0
- package/dist/internal/encoding.js.map +1 -0
- package/dist/internal/hkdf.d.ts +14 -0
- package/dist/internal/hkdf.d.ts.map +1 -0
- package/dist/internal/hkdf.js +27 -0
- package/dist/internal/hkdf.js.map +1 -0
- package/dist/internal/hmac.d.ts +9 -0
- package/dist/internal/hmac.d.ts.map +1 -0
- package/dist/internal/hmac.js +18 -0
- package/dist/internal/hmac.js.map +1 -0
- package/dist/internal/runtime.d.ts +29 -0
- package/dist/internal/runtime.d.ts.map +1 -0
- package/dist/internal/runtime.js +67 -0
- package/dist/internal/runtime.js.map +1 -0
- package/dist/internal/sodium.d.ts +12 -0
- package/dist/internal/sodium.d.ts.map +1 -0
- package/dist/internal/sodium.js +34 -0
- package/dist/internal/sodium.js.map +1 -0
- package/dist/internal/types.d.ts +94 -0
- package/dist/internal/types.d.ts.map +1 -0
- package/dist/internal/types.js +65 -0
- package/dist/internal/types.js.map +1 -0
- package/dist/kdf/argon2id.d.ts +72 -0
- package/dist/kdf/argon2id.d.ts.map +1 -0
- package/dist/kdf/argon2id.js +97 -0
- package/dist/kdf/argon2id.js.map +1 -0
- package/dist/migration/v0-bridge.d.ts +94 -0
- package/dist/migration/v0-bridge.d.ts.map +1 -0
- package/dist/migration/v0-bridge.js +203 -0
- package/dist/migration/v0-bridge.js.map +1 -0
- package/dist/streams/aes-gcm-v1.d.ts +76 -0
- package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
- package/dist/streams/aes-gcm-v1.js +322 -0
- package/dist/streams/aes-gcm-v1.js.map +1 -0
- package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
- package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v0/api.js +110 -0
- package/dist/suites/aes-gcm-v0/api.js.map +1 -0
- package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
- package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v1/api.js +179 -0
- package/dist/suites/aes-gcm-v1/api.js.map +1 -0
- package/dist/suites/aes-gcm-v1/index.d.ts +56 -0
- package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v1/index.js +174 -0
- package/dist/suites/aes-gcm-v1/index.js.map +1 -0
- package/dist/suites/pq-hybrid-v1/api.d.ts +40 -0
- package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
- package/dist/suites/pq-hybrid-v1/api.js +157 -0
- package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
- package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
- package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
- package/dist/suites/pq-hybrid-v1/index.js +225 -0
- package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
- package/dist/suites/xchacha-v1/api.d.ts +29 -0
- package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
- package/dist/suites/xchacha-v1/api.js +151 -0
- package/dist/suites/xchacha-v1/api.js.map +1 -0
- package/dist/suites/xchacha-v1/index.d.ts +50 -0
- package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
- package/dist/suites/xchacha-v1/index.js +133 -0
- package/dist/suites/xchacha-v1/index.js.map +1 -0
- package/package.json +112 -0
- package/spec/format-v0.md +81 -0
- package/spec/format-v1.md +245 -0
- package/spec/key-derivation.md +122 -0
- package/spec/threat-model.md +152 -0
- package/src/format/header.ts +284 -0
- package/src/identity/index.ts +358 -0
- package/src/index.ts +197 -0
- package/src/internal/encoding.ts +153 -0
- package/src/internal/hkdf.ts +47 -0
- package/src/internal/hmac.ts +33 -0
- package/src/internal/runtime.ts +80 -0
- package/src/internal/sodium.ts +38 -0
- package/src/internal/types.ts +128 -0
- package/src/kdf/argon2id.ts +164 -0
- package/src/migration/v0-bridge.ts +347 -0
- package/src/streams/aes-gcm-v1.ts +443 -0
- package/src/suites/aes-gcm-v0/api.ts +155 -0
- package/src/suites/aes-gcm-v1/api.ts +291 -0
- package/src/suites/aes-gcm-v1/index.ts +266 -0
- package/src/suites/pq-hybrid-v1/api.ts +259 -0
- package/src/suites/pq-hybrid-v1/index.ts +343 -0
- package/src/suites/xchacha-v1/api.ts +251 -0
- package/src/suites/xchacha-v1/index.ts +213 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* High-level encrypt/decrypt API for the XChaCha20-Poly1305 v1 suite.
|
|
3
|
+
* Mirrors the shape of the AES-GCM v1 API; behavior is identical at the
|
|
4
|
+
* format layer.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
buildAuthenticatedHeader,
|
|
9
|
+
parseHeader,
|
|
10
|
+
verifyHeaderMac,
|
|
11
|
+
HeaderError,
|
|
12
|
+
} from '../../format/header.js'
|
|
13
|
+
import {
|
|
14
|
+
XCHACHA_V1_SUITE_PAYLOAD_LENGTH,
|
|
15
|
+
XCHACHA_V1_TAG_BYTES,
|
|
16
|
+
createChunkContext,
|
|
17
|
+
decryptChunk,
|
|
18
|
+
encryptChunk,
|
|
19
|
+
generateContentMaterial,
|
|
20
|
+
parseXChaChaV1SuitePayload,
|
|
21
|
+
} from './index.js'
|
|
22
|
+
import {
|
|
23
|
+
DEFAULT_CHUNK_SIZE,
|
|
24
|
+
type EncryptedFile,
|
|
25
|
+
HEADER_SIZES,
|
|
26
|
+
MAX_TOTAL_CHUNKS,
|
|
27
|
+
type ProgressCallback,
|
|
28
|
+
SUITE,
|
|
29
|
+
} from '../../internal/types.js'
|
|
30
|
+
import {
|
|
31
|
+
asBlobPart,
|
|
32
|
+
readUint32BE,
|
|
33
|
+
uint32BE,
|
|
34
|
+
} from '../../internal/encoding.js'
|
|
35
|
+
|
|
36
|
+
const LENGTH_PREFIX_BYTES = 4
|
|
37
|
+
|
|
38
|
+
export interface XChaChaEncryptOptions {
|
|
39
|
+
blob: Blob
|
|
40
|
+
contentKey?: Uint8Array
|
|
41
|
+
fileId?: Uint8Array
|
|
42
|
+
suitePayloadOverride?: Uint8Array
|
|
43
|
+
chunkSize?: number
|
|
44
|
+
onProgress?: ProgressCallback
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function encryptBlob(
|
|
48
|
+
options: XChaChaEncryptOptions,
|
|
49
|
+
): Promise<EncryptedFile & { contentKey: Uint8Array }> {
|
|
50
|
+
const { blob, onProgress } = options
|
|
51
|
+
if (!(blob instanceof Blob)) {
|
|
52
|
+
throw new TypeError('encryptBlob: blob must be a Blob or File')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
|
|
56
|
+
if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
|
|
57
|
+
throw new RangeError('encryptBlob: chunkSize must be a positive integer')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const plaintextSize = blob.size
|
|
61
|
+
const totalChunks =
|
|
62
|
+
plaintextSize === 0 ? 0 : Math.ceil(plaintextSize / chunkSize)
|
|
63
|
+
if (totalChunks > MAX_TOTAL_CHUNKS) {
|
|
64
|
+
throw new RangeError('encryptBlob: file would exceed total_chunks limit')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const generated = generateContentMaterial()
|
|
68
|
+
const contentKey = options.contentKey ?? generated.contentKey
|
|
69
|
+
const fileId = options.fileId ?? generated.fileId
|
|
70
|
+
if (contentKey.length !== 32) {
|
|
71
|
+
throw new RangeError('encryptBlob: contentKey must be 32 bytes')
|
|
72
|
+
}
|
|
73
|
+
if (fileId.length !== HEADER_SIZES.FILE_ID) {
|
|
74
|
+
throw new RangeError('encryptBlob: fileId must be 16 bytes')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const suitePayload =
|
|
78
|
+
options.suitePayloadOverride ??
|
|
79
|
+
new Uint8Array(XCHACHA_V1_SUITE_PAYLOAD_LENGTH)
|
|
80
|
+
if (suitePayload.length !== XCHACHA_V1_SUITE_PAYLOAD_LENGTH) {
|
|
81
|
+
throw new RangeError(
|
|
82
|
+
`encryptBlob: suitePayloadOverride must be ${XCHACHA_V1_SUITE_PAYLOAD_LENGTH} bytes`,
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const header = await buildAuthenticatedHeader(
|
|
87
|
+
{
|
|
88
|
+
suite: SUITE.XCHACHA20_POLY1305_V1,
|
|
89
|
+
fileId,
|
|
90
|
+
chunkSize,
|
|
91
|
+
totalChunks,
|
|
92
|
+
plaintextSize,
|
|
93
|
+
suitePayload,
|
|
94
|
+
},
|
|
95
|
+
contentKey,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
const ctx = await createChunkContext(contentKey, fileId, totalChunks)
|
|
99
|
+
|
|
100
|
+
const parts: BlobPart[] = [asBlobPart(header)]
|
|
101
|
+
for (let i = 0; i < totalChunks; i += 1) {
|
|
102
|
+
const start = i * chunkSize
|
|
103
|
+
const end = Math.min(start + chunkSize, plaintextSize)
|
|
104
|
+
const plaintextBytes = new Uint8Array(
|
|
105
|
+
await blob.slice(start, end).arrayBuffer(),
|
|
106
|
+
)
|
|
107
|
+
const ciphertext = await encryptChunk(ctx, i, plaintextBytes)
|
|
108
|
+
parts.push(asBlobPart(uint32BE(ciphertext.length)))
|
|
109
|
+
parts.push(asBlobPart(ciphertext))
|
|
110
|
+
onProgress?.((i + 1) / Math.max(totalChunks, 1))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (totalChunks === 0) onProgress?.(1)
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
blob: new Blob(parts, { type: 'application/octet-stream' }),
|
|
117
|
+
suite: SUITE.XCHACHA20_POLY1305_V1,
|
|
118
|
+
fileId,
|
|
119
|
+
chunkSize,
|
|
120
|
+
totalChunks,
|
|
121
|
+
plaintextSize,
|
|
122
|
+
contentKey,
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface XChaChaDecryptOptions {
|
|
127
|
+
blob: Blob
|
|
128
|
+
contentKey: Uint8Array
|
|
129
|
+
onProgress?: ProgressCallback
|
|
130
|
+
allowedSuites?: ReadonlyArray<number>
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function decryptBlob(
|
|
134
|
+
options: XChaChaDecryptOptions,
|
|
135
|
+
): Promise<Blob> {
|
|
136
|
+
const { blob, contentKey, onProgress } = options
|
|
137
|
+
if (!(blob instanceof Blob)) {
|
|
138
|
+
throw new TypeError('decryptBlob: blob must be a Blob or File')
|
|
139
|
+
}
|
|
140
|
+
if (contentKey.length !== 32) {
|
|
141
|
+
throw new RangeError('decryptBlob: contentKey must be 32 bytes')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const headerProbeBytes = new Uint8Array(
|
|
145
|
+
await blob.slice(0, Math.min(blob.size, 4096)).arrayBuffer(),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
let parsed: ReturnType<typeof parseHeader>
|
|
149
|
+
try {
|
|
150
|
+
parsed = parseHeader(headerProbeBytes)
|
|
151
|
+
} catch (err) {
|
|
152
|
+
if (err instanceof HeaderError && err.code === 'header_too_short') {
|
|
153
|
+
const allHeaderBytes = new Uint8Array(
|
|
154
|
+
await blob
|
|
155
|
+
.slice(0, Math.min(blob.size, 4 + 0xffff + 1024))
|
|
156
|
+
.arrayBuffer(),
|
|
157
|
+
)
|
|
158
|
+
parsed = parseHeader(allHeaderBytes)
|
|
159
|
+
} else {
|
|
160
|
+
throw err
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (
|
|
165
|
+
options.allowedSuites &&
|
|
166
|
+
!options.allowedSuites.includes(parsed.suite)
|
|
167
|
+
) {
|
|
168
|
+
throw new HeaderError('suite_not_allowed')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (parsed.suite !== SUITE.XCHACHA20_POLY1305_V1) {
|
|
172
|
+
throw new HeaderError(
|
|
173
|
+
`decryptBlob: this entry point only supports xchacha20-poly1305-v1; got suite 0x${parsed.suite.toString(16)}`,
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
parseXChaChaV1SuitePayload(parsed.suitePayload)
|
|
178
|
+
await verifyHeaderMac(parsed, contentKey)
|
|
179
|
+
|
|
180
|
+
const ctx = await createChunkContext(
|
|
181
|
+
contentKey,
|
|
182
|
+
parsed.fileId,
|
|
183
|
+
parsed.totalChunks,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
const plaintextParts: BlobPart[] = []
|
|
187
|
+
let cursor = parsed.headerLength
|
|
188
|
+
let bytesEmitted = 0
|
|
189
|
+
|
|
190
|
+
for (let i = 0; i < parsed.totalChunks; i += 1) {
|
|
191
|
+
if (cursor + LENGTH_PREFIX_BYTES > blob.size) {
|
|
192
|
+
throw new HeaderError('chunk_length_truncated')
|
|
193
|
+
}
|
|
194
|
+
const lenBytes = new Uint8Array(
|
|
195
|
+
await blob.slice(cursor, cursor + LENGTH_PREFIX_BYTES).arrayBuffer(),
|
|
196
|
+
)
|
|
197
|
+
cursor += LENGTH_PREFIX_BYTES
|
|
198
|
+
const cipherLen = readUint32BE(lenBytes)
|
|
199
|
+
|
|
200
|
+
const isFinal = i === parsed.totalChunks - 1
|
|
201
|
+
const minCipher = 1 + XCHACHA_V1_TAG_BYTES
|
|
202
|
+
const maxCipher = parsed.chunkSize + XCHACHA_V1_TAG_BYTES
|
|
203
|
+
if (cipherLen < minCipher || cipherLen > maxCipher) {
|
|
204
|
+
throw new HeaderError('chunk_length_out_of_range')
|
|
205
|
+
}
|
|
206
|
+
if (!isFinal && cipherLen !== maxCipher) {
|
|
207
|
+
throw new HeaderError('non_final_chunk_wrong_size')
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (cursor + cipherLen > blob.size) {
|
|
211
|
+
throw new HeaderError('chunk_truncated')
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const cipherBytes = new Uint8Array(
|
|
215
|
+
await blob.slice(cursor, cursor + cipherLen).arrayBuffer(),
|
|
216
|
+
)
|
|
217
|
+
cursor += cipherLen
|
|
218
|
+
|
|
219
|
+
const plaintext = await decryptChunk(ctx, i, cipherBytes)
|
|
220
|
+
bytesEmitted += plaintext.length
|
|
221
|
+
plaintextParts.push(asBlobPart(plaintext))
|
|
222
|
+
|
|
223
|
+
onProgress?.((i + 1) / Math.max(parsed.totalChunks, 1))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (bytesEmitted !== parsed.plaintextSize) {
|
|
227
|
+
throw new HeaderError('plaintext_size_mismatch')
|
|
228
|
+
}
|
|
229
|
+
if (cursor !== blob.size) {
|
|
230
|
+
throw new HeaderError('trailing_bytes_after_last_chunk')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (parsed.totalChunks === 0) onProgress?.(1)
|
|
234
|
+
|
|
235
|
+
return new Blob(plaintextParts, { type: 'application/octet-stream' })
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export async function encryptBytes(
|
|
239
|
+
bytes: Uint8Array,
|
|
240
|
+
options: Omit<XChaChaEncryptOptions, 'blob'>,
|
|
241
|
+
): Promise<EncryptedFile & { contentKey: Uint8Array }> {
|
|
242
|
+
const blob = new Blob([asBlobPart(bytes)])
|
|
243
|
+
return encryptBlob({ blob, ...options })
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export async function decryptToBytes(
|
|
247
|
+
options: XChaChaDecryptOptions,
|
|
248
|
+
): Promise<Uint8Array> {
|
|
249
|
+
const blob = await decryptBlob(options)
|
|
250
|
+
return new Uint8Array(await blob.arrayBuffer())
|
|
251
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
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
|
+
|
|
14
|
+
import { buildChunkAad } from '../../format/header.js'
|
|
15
|
+
import {
|
|
16
|
+
HKDF_INFO,
|
|
17
|
+
HEADER_SIZES,
|
|
18
|
+
type ParsedHeader,
|
|
19
|
+
} from '../../internal/types.js'
|
|
20
|
+
import { concatBytes, uint64BE } from '../../internal/encoding.js'
|
|
21
|
+
import { hkdfSha256 } from '../../internal/hkdf.js'
|
|
22
|
+
import { randomBytes } from '../../internal/runtime.js'
|
|
23
|
+
import { getSodium } from '../../internal/sodium.js'
|
|
24
|
+
|
|
25
|
+
export const XCHACHA_V1_KEY_BYTES = 32
|
|
26
|
+
export const XCHACHA_V1_NONCE_BYTES = 24
|
|
27
|
+
export const XCHACHA_V1_TAG_BYTES = 16
|
|
28
|
+
|
|
29
|
+
/** Suite payload layout: 72-byte secretbox-wrapped key + 24-byte nonce = 96 bytes. */
|
|
30
|
+
export const XCHACHA_V1_SUITE_PAYLOAD_LENGTH = 96
|
|
31
|
+
|
|
32
|
+
export interface XChaChaV1SuitePayload {
|
|
33
|
+
wrappedKey: Uint8Array // 32-byte key + 16-byte secretbox tag = 48 bytes; padded to 72
|
|
34
|
+
wrapNonce: Uint8Array // 24 bytes
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function buildXChaChaV1SuitePayload(
|
|
38
|
+
payload: XChaChaV1SuitePayload,
|
|
39
|
+
): Uint8Array {
|
|
40
|
+
if (payload.wrappedKey.length !== 72) {
|
|
41
|
+
throw new RangeError('xchacha-v1: wrappedKey must be 72 bytes')
|
|
42
|
+
}
|
|
43
|
+
if (payload.wrapNonce.length !== XCHACHA_V1_NONCE_BYTES) {
|
|
44
|
+
throw new RangeError('xchacha-v1: wrapNonce must be 24 bytes')
|
|
45
|
+
}
|
|
46
|
+
return concatBytes([payload.wrappedKey, payload.wrapNonce])
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseXChaChaV1SuitePayload(
|
|
50
|
+
bytes: Uint8Array,
|
|
51
|
+
): XChaChaV1SuitePayload {
|
|
52
|
+
if (bytes.length !== XCHACHA_V1_SUITE_PAYLOAD_LENGTH) {
|
|
53
|
+
throw new RangeError('xchacha-v1: suite payload must be 96 bytes')
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
wrappedKey: bytes.slice(0, 72),
|
|
57
|
+
wrapNonce: bytes.slice(72, 96),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function deriveChunkKey(
|
|
62
|
+
contentKey: Uint8Array,
|
|
63
|
+
fileId: Uint8Array,
|
|
64
|
+
): Promise<Uint8Array> {
|
|
65
|
+
return hkdfSha256({
|
|
66
|
+
ikm: contentKey,
|
|
67
|
+
salt: fileId,
|
|
68
|
+
info: HKDF_INFO.XCHACHA_CHUNK_KEY,
|
|
69
|
+
length: XCHACHA_V1_KEY_BYTES,
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function deriveNoncePrefix(fileId: Uint8Array): Promise<Uint8Array> {
|
|
74
|
+
// XChaCha's 24-byte nonce: 16-byte file-derived prefix + 8-byte counter.
|
|
75
|
+
return hkdfSha256({
|
|
76
|
+
ikm: fileId,
|
|
77
|
+
info: HKDF_INFO.XCHACHA_NONCE_PREFIX,
|
|
78
|
+
length: 16,
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function buildNonce(noncePrefix: Uint8Array, chunkIndex: number): Uint8Array {
|
|
83
|
+
const nonce = new Uint8Array(XCHACHA_V1_NONCE_BYTES)
|
|
84
|
+
nonce.set(noncePrefix, 0)
|
|
85
|
+
nonce.set(uint64BE(chunkIndex), 16)
|
|
86
|
+
return nonce
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function generateContentMaterial(): {
|
|
90
|
+
contentKey: Uint8Array
|
|
91
|
+
fileId: Uint8Array
|
|
92
|
+
} {
|
|
93
|
+
return {
|
|
94
|
+
contentKey: randomBytes(XCHACHA_V1_KEY_BYTES),
|
|
95
|
+
fileId: randomBytes(HEADER_SIZES.FILE_ID),
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface XChaChaV1ChunkContext {
|
|
100
|
+
chunkKey: Uint8Array
|
|
101
|
+
noncePrefix: Uint8Array
|
|
102
|
+
totalChunks: number
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function createChunkContext(
|
|
106
|
+
contentKey: Uint8Array,
|
|
107
|
+
fileId: Uint8Array,
|
|
108
|
+
totalChunks: number,
|
|
109
|
+
): Promise<XChaChaV1ChunkContext> {
|
|
110
|
+
const chunkKey = await deriveChunkKey(contentKey, fileId)
|
|
111
|
+
const noncePrefix = await deriveNoncePrefix(fileId)
|
|
112
|
+
return { chunkKey, noncePrefix, totalChunks }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function encryptChunk(
|
|
116
|
+
ctx: XChaChaV1ChunkContext,
|
|
117
|
+
chunkIndex: number,
|
|
118
|
+
plaintext: Uint8Array,
|
|
119
|
+
): Promise<Uint8Array> {
|
|
120
|
+
const sodium = await getSodium()
|
|
121
|
+
const isFinal = chunkIndex === ctx.totalChunks - 1
|
|
122
|
+
const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
|
|
123
|
+
const nonce = buildNonce(ctx.noncePrefix, chunkIndex)
|
|
124
|
+
return sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
|
|
125
|
+
plaintext,
|
|
126
|
+
aad,
|
|
127
|
+
null,
|
|
128
|
+
nonce,
|
|
129
|
+
ctx.chunkKey,
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function decryptChunk(
|
|
134
|
+
ctx: XChaChaV1ChunkContext,
|
|
135
|
+
chunkIndex: number,
|
|
136
|
+
ciphertext: Uint8Array,
|
|
137
|
+
): Promise<Uint8Array> {
|
|
138
|
+
const sodium = await getSodium()
|
|
139
|
+
const isFinal = chunkIndex === ctx.totalChunks - 1
|
|
140
|
+
const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
|
|
141
|
+
const nonce = buildNonce(ctx.noncePrefix, chunkIndex)
|
|
142
|
+
const result = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
|
|
143
|
+
null,
|
|
144
|
+
ciphertext,
|
|
145
|
+
aad,
|
|
146
|
+
nonce,
|
|
147
|
+
ctx.chunkKey,
|
|
148
|
+
)
|
|
149
|
+
return result
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function wrapContentKey(options: {
|
|
153
|
+
contentKey: Uint8Array
|
|
154
|
+
envelopeKey: Uint8Array
|
|
155
|
+
}): Promise<{ wrapped: Uint8Array; wrapNonce: Uint8Array }> {
|
|
156
|
+
const sodium = await getSodium()
|
|
157
|
+
const { contentKey, envelopeKey } = options
|
|
158
|
+
if (contentKey.length !== XCHACHA_V1_KEY_BYTES) {
|
|
159
|
+
throw new RangeError('wrapContentKey: contentKey must be 32 bytes')
|
|
160
|
+
}
|
|
161
|
+
if (envelopeKey.length !== XCHACHA_V1_KEY_BYTES) {
|
|
162
|
+
throw new RangeError('wrapContentKey: envelopeKey must be 32 bytes')
|
|
163
|
+
}
|
|
164
|
+
const wrapNonce = randomBytes(XCHACHA_V1_NONCE_BYTES)
|
|
165
|
+
// crypto_secretbox_easy: outputs 16-byte poly1305 tag + ciphertext = 48 bytes
|
|
166
|
+
const wrapped = sodium.crypto_secretbox_easy(
|
|
167
|
+
contentKey,
|
|
168
|
+
wrapNonce,
|
|
169
|
+
envelopeKey,
|
|
170
|
+
)
|
|
171
|
+
if (wrapped.length !== 48) {
|
|
172
|
+
throw new Error('wrapContentKey: unexpected wrapped length')
|
|
173
|
+
}
|
|
174
|
+
// Pad to 72 bytes for fixed suite_payload size
|
|
175
|
+
const padded = new Uint8Array(72)
|
|
176
|
+
padded.set(wrapped, 0)
|
|
177
|
+
return { wrapped: padded, wrapNonce }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function unwrapContentKey(options: {
|
|
181
|
+
envelopeKey: Uint8Array
|
|
182
|
+
wrappedField: Uint8Array
|
|
183
|
+
wrapNonce: Uint8Array
|
|
184
|
+
}): Promise<Uint8Array> {
|
|
185
|
+
const sodium = await getSodium()
|
|
186
|
+
const { envelopeKey, wrappedField, wrapNonce } = options
|
|
187
|
+
if (envelopeKey.length !== XCHACHA_V1_KEY_BYTES) {
|
|
188
|
+
throw new RangeError('unwrapContentKey: envelopeKey must be 32 bytes')
|
|
189
|
+
}
|
|
190
|
+
if (wrappedField.length !== 72) {
|
|
191
|
+
throw new RangeError('unwrapContentKey: wrappedField must be 72 bytes')
|
|
192
|
+
}
|
|
193
|
+
if (wrapNonce.length !== XCHACHA_V1_NONCE_BYTES) {
|
|
194
|
+
throw new RangeError('unwrapContentKey: wrapNonce must be 24 bytes')
|
|
195
|
+
}
|
|
196
|
+
// First 48 bytes are tag+key, the rest is reserved zeros.
|
|
197
|
+
const wrapped = wrappedField.slice(0, 48)
|
|
198
|
+
const unwrapped = sodium.crypto_secretbox_open_easy(
|
|
199
|
+
wrapped,
|
|
200
|
+
wrapNonce,
|
|
201
|
+
envelopeKey,
|
|
202
|
+
)
|
|
203
|
+
if (!unwrapped) {
|
|
204
|
+
throw new Error('unwrapContentKey: unwrap failed (wrong envelope key?)')
|
|
205
|
+
}
|
|
206
|
+
return unwrapped
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function getSuitePayloadFromHeader(
|
|
210
|
+
header: ParsedHeader,
|
|
211
|
+
): XChaChaV1SuitePayload {
|
|
212
|
+
return parseXChaChaV1SuitePayload(header.suitePayload)
|
|
213
|
+
}
|