@decryption/core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/file.js ADDED
@@ -0,0 +1,348 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dearmorFile = exports.armorFile = exports.decryptFile = exports.encryptFile = exports.openFile = exports.sealFile = exports.createFileDecryptor = exports.createFileEncryptor = exports.unwrapWithPassphrase = exports.wrapWithPassphrase = exports.isPassphraseFile = exports.verifyFileHeader = exports.parseFileHeader = exports.tryParseFileHeader = exports.encodeFileHeader = exports.isFileEnvelope = exports.generateFileKey = exports.StanzaType = exports.MAX_STANZA_BODY_LENGTH = exports.MAX_STANZAS = exports.FILE_ARMOR_PREFIX = exports.FILE_MAC_LENGTH = exports.FILE_KEY_LENGTH = exports.FILE_VERSION = void 0;
4
+ const base_1 = require("@decryption/base");
5
+ const utils_1 = require("@decryption/ciphers/utils");
6
+ const hkdf_1 = require("@decryption/hashes/hkdf");
7
+ const hmac_1 = require("@decryption/hashes/hmac");
8
+ const sha2_1 = require("@decryption/hashes/sha2");
9
+ const utils_2 = require("@decryption/hashes/utils");
10
+ const bytes_1 = require("./bytes");
11
+ const envelope_1 = require("./envelope");
12
+ const errors_1 = require("./errors");
13
+ const kdf_1 = require("./kdf");
14
+ const stream_1 = require("./stream");
15
+ /**
16
+ * Version 2 of the dcrypt format: a binary, streamable file envelope.
17
+ *
18
+ * ```text
19
+ * | magic | ver | suite | count | stanza … stanza | header MAC | nonce | STREAM chunks … |
20
+ * | DCRYPT | 2 | 2 | u16 | | 32 B | 16 B | |
21
+ * |<------------- authenticated by the MAC ------->|
22
+ *
23
+ * stanza: | type u8 | length u16 | body |
24
+ * ```
25
+ *
26
+ * The layout follows the age file format: a random file key encrypts the payload, and each
27
+ * stanza holds one wrapped copy of that key (for a passphrase, or for an X25519 recipient). The
28
+ * header is authenticated with `HMAC-SHA256` under `HKDF-SHA256(file key, info = "header")`, and
29
+ * the payload is the STREAM construction in `stream.ts`. Only the encoding differs from age
30
+ * (binary fields instead of text lines), plus the key wrapping, which reuses this package's
31
+ * Argon2id + XChaCha20-Poly1305 and `@decryption/keys`' X25519 stanzas.
32
+ *
33
+ * Adding a way to unlock a file means adding a stanza type; the payload never changes.
34
+ */
35
+ /** Format version written in the seventh byte. Version 1 is the single-shot envelope. */
36
+ exports.FILE_VERSION = 2;
37
+ /** Length of the random file key. */
38
+ exports.FILE_KEY_LENGTH = 32;
39
+ /** Length of the header MAC. */
40
+ exports.FILE_MAC_LENGTH = 32;
41
+ /** Prefix of the text (armored) form of a version 2 file, e.g. `dcrypt.v2.<base64>`. */
42
+ exports.FILE_ARMOR_PREFIX = 'dcrypt.v2.';
43
+ /** Upper bounds accepted when reading, so a hostile header cannot make a reader buffer forever. */
44
+ exports.MAX_STANZAS = 1024;
45
+ exports.MAX_STANZA_BODY_LENGTH = 1024;
46
+ /** Known stanza types. Readers keep stanzas of unknown type so newer writers stay readable. */
47
+ var StanzaType;
48
+ (function (StanzaType) {
49
+ /** Argon2id-derived key wraps the file key. Must be the only stanza, as with age's scrypt. */
50
+ StanzaType[StanzaType["Passphrase"] = 1] = "Passphrase";
51
+ /** X25519 recipient, produced by `@decryption/keys`. */
52
+ StanzaType[StanzaType["X25519"] = 2] = "X25519";
53
+ })(StanzaType || (exports.StanzaType = StanzaType = {}));
54
+ const FIXED_LENGTH = envelope_1.MAGIC.length + 1 + 1 + 2;
55
+ const TRAILER_LENGTH = exports.FILE_MAC_LENGTH + stream_1.STREAM_NONCE_LENGTH;
56
+ const HEADER_INFO = (0, utils_2.utf8ToBytes)('header');
57
+ const PASSPHRASE_PARAMS_LENGTH = 4 + 4 + 1 + kdf_1.SALT_LENGTH;
58
+ const WRAPPED_KEY_LENGTH = envelope_1.NONCE_LENGTH + exports.FILE_KEY_LENGTH + envelope_1.TAG_LENGTH;
59
+ const PASSPHRASE_CONTEXT = (0, utils_2.utf8ToBytes)('dcrypt-file-passphrase-v2');
60
+ const assertFileKey = (fileKey) => {
61
+ if (fileKey.length !== exports.FILE_KEY_LENGTH) {
62
+ throw new errors_1.InvalidParametersError(`file key must be ${exports.FILE_KEY_LENGTH} bytes, got ${fileKey.length}`);
63
+ }
64
+ };
65
+ const assertStanzas = (stanzas, Failure) => {
66
+ if (stanzas.length === 0)
67
+ throw new Failure('a file needs at least one stanza');
68
+ if (stanzas.length > exports.MAX_STANZAS)
69
+ throw new Failure(`a file can hold at most ${exports.MAX_STANZAS} stanzas`);
70
+ for (const stanza of stanzas) {
71
+ if (!Number.isInteger(stanza.type) || stanza.type < 1 || stanza.type > 255) {
72
+ throw new Failure(`invalid stanza type ${stanza.type}`);
73
+ }
74
+ if (stanza.body.length > exports.MAX_STANZA_BODY_LENGTH) {
75
+ throw new Failure(`stanza body is longer than ${exports.MAX_STANZA_BODY_LENGTH} bytes`);
76
+ }
77
+ }
78
+ if (stanzas.length > 1 && stanzas.some((stanza) => stanza.type === StanzaType.Passphrase)) {
79
+ throw new Failure('a passphrase stanza must be the only stanza in a file');
80
+ }
81
+ };
82
+ const headerMac = (fileKey, authenticated) => {
83
+ const macKey = (0, hkdf_1.hkdf)(sha2_1.sha256, fileKey, undefined, HEADER_INFO, 32);
84
+ try {
85
+ return (0, hmac_1.hmac)(sha2_1.sha256, macKey, authenticated);
86
+ }
87
+ finally {
88
+ macKey.fill(0);
89
+ }
90
+ };
91
+ /** Draws a fresh random file key. Never reuse one: it is the root of a single file's keys. */
92
+ const generateFileKey = () => (0, utils_2.randomBytes)(exports.FILE_KEY_LENGTH);
93
+ exports.generateFileKey = generateFileKey;
94
+ /** True when `bytes` begin like a version 2 file. Eight bytes are enough to tell. */
95
+ const isFileEnvelope = (bytes) => {
96
+ if (bytes.length < envelope_1.MAGIC.length + 1)
97
+ return false;
98
+ for (let i = 0; i < envelope_1.MAGIC.length; i++) {
99
+ if (bytes[i] !== envelope_1.MAGIC[i])
100
+ return false;
101
+ }
102
+ return bytes[envelope_1.MAGIC.length] === exports.FILE_VERSION;
103
+ };
104
+ exports.isFileEnvelope = isFileEnvelope;
105
+ /** Encodes the complete header: stanzas, their MAC, and the payload nonce. */
106
+ const encodeFileHeader = (fileKey, stanzas, nonce = (0, stream_1.generateStreamNonce)()) => {
107
+ assertFileKey(fileKey);
108
+ assertStanzas(stanzas, errors_1.InvalidParametersError);
109
+ if (nonce.length !== stream_1.STREAM_NONCE_LENGTH) {
110
+ throw new errors_1.InvalidParametersError(`stream nonce must be ${stream_1.STREAM_NONCE_LENGTH} bytes`);
111
+ }
112
+ const fixed = new Uint8Array(FIXED_LENGTH);
113
+ fixed.set(envelope_1.MAGIC, 0);
114
+ fixed[envelope_1.MAGIC.length] = exports.FILE_VERSION;
115
+ fixed[envelope_1.MAGIC.length + 1] = envelope_1.Suite.HkdfSha256ChaCha20Poly1305Stream;
116
+ new DataView(fixed.buffer).setUint16(envelope_1.MAGIC.length + 2, stanzas.length, false);
117
+ const encoded = stanzas.map((stanza) => {
118
+ const bytes = new Uint8Array(3 + stanza.body.length);
119
+ bytes[0] = stanza.type;
120
+ new DataView(bytes.buffer).setUint16(1, stanza.body.length, false);
121
+ bytes.set(stanza.body, 3);
122
+ return bytes;
123
+ });
124
+ const authenticated = (0, utils_2.concatBytes)(fixed, ...encoded);
125
+ return (0, utils_2.concatBytes)(authenticated, headerMac(fileKey, authenticated), nonce);
126
+ };
127
+ exports.encodeFileHeader = encodeFileHeader;
128
+ /**
129
+ * Parses a header from the start of `bytes`. Returns `undefined` when more bytes are needed, so
130
+ * a streaming reader can call it again with a longer prefix. Throws {@link CorruptEnvelopeError}
131
+ * for anything that is not a dcrypt file and {@link UnsupportedEnvelopeError} for versions or
132
+ * suites this build cannot open.
133
+ */
134
+ const tryParseFileHeader = (bytes) => {
135
+ for (let i = 0; i < Math.min(bytes.length, envelope_1.MAGIC.length); i++) {
136
+ if (bytes[i] !== envelope_1.MAGIC[i])
137
+ throw new errors_1.CorruptEnvelopeError('not a dcrypt envelope');
138
+ }
139
+ if (bytes.length < FIXED_LENGTH)
140
+ return undefined;
141
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
142
+ const version = bytes[envelope_1.MAGIC.length];
143
+ const suite = bytes[envelope_1.MAGIC.length + 1];
144
+ if (version !== exports.FILE_VERSION) {
145
+ throw new errors_1.UnsupportedEnvelopeError(version === 1
146
+ ? 'this is a version 1 envelope; open it with decrypt()'
147
+ : `unsupported envelope version ${version}; this build understands versions 1 and ${exports.FILE_VERSION}`);
148
+ }
149
+ if (suite !== envelope_1.Suite.HkdfSha256ChaCha20Poly1305Stream) {
150
+ throw new errors_1.UnsupportedEnvelopeError(`unsupported algorithm suite ${suite}`);
151
+ }
152
+ const count = view.getUint16(envelope_1.MAGIC.length + 2, false);
153
+ if (count === 0 || count > exports.MAX_STANZAS) {
154
+ throw new errors_1.CorruptEnvelopeError(`invalid stanza count ${count}`);
155
+ }
156
+ const stanzas = [];
157
+ let offset = FIXED_LENGTH;
158
+ for (let i = 0; i < count; i++) {
159
+ if (bytes.length < offset + 3)
160
+ return undefined;
161
+ const type = bytes[offset];
162
+ const length = view.getUint16(offset + 1, false);
163
+ if (type === 0)
164
+ throw new errors_1.CorruptEnvelopeError('invalid stanza type 0');
165
+ if (length > exports.MAX_STANZA_BODY_LENGTH) {
166
+ throw new errors_1.CorruptEnvelopeError(`stanza body is longer than ${exports.MAX_STANZA_BODY_LENGTH} bytes`);
167
+ }
168
+ if (bytes.length < offset + 3 + length)
169
+ return undefined;
170
+ stanzas.push({ type, body: (0, bytes_1.copyBytes)(bytes, offset + 3, offset + 3 + length) });
171
+ offset += 3 + length;
172
+ }
173
+ if (bytes.length < offset + TRAILER_LENGTH)
174
+ return undefined;
175
+ assertStanzas(stanzas, errors_1.CorruptEnvelopeError);
176
+ return {
177
+ version,
178
+ suite,
179
+ stanzas,
180
+ mac: (0, bytes_1.copyBytes)(bytes, offset, offset + exports.FILE_MAC_LENGTH),
181
+ nonce: (0, bytes_1.copyBytes)(bytes, offset + exports.FILE_MAC_LENGTH, offset + TRAILER_LENGTH),
182
+ authenticated: (0, bytes_1.copyBytes)(bytes, 0, offset),
183
+ length: offset + TRAILER_LENGTH,
184
+ };
185
+ };
186
+ exports.tryParseFileHeader = tryParseFileHeader;
187
+ /** {@link tryParseFileHeader} for callers that hold the whole file: a short header is corrupt. */
188
+ const parseFileHeader = (bytes) => {
189
+ const header = (0, exports.tryParseFileHeader)(bytes);
190
+ if (!header)
191
+ throw new errors_1.CorruptEnvelopeError('envelope header is truncated');
192
+ return header;
193
+ };
194
+ exports.parseFileHeader = parseFileHeader;
195
+ /**
196
+ * Checks the header MAC with the unwrapped file key. This is what stops an attacker from adding,
197
+ * removing or editing stanzas (for example to lower Argon2id cost parameters) on a file they
198
+ * cannot decrypt. Anyone who can unwrap the file key can also rewrite the header; that is
199
+ * inherent in the design and the same as in age.
200
+ */
201
+ const verifyFileHeader = (header, fileKey) => {
202
+ assertFileKey(fileKey);
203
+ if (!(0, utils_1.equalBytes)(headerMac(fileKey, header.authenticated), header.mac)) {
204
+ throw new errors_1.CorruptEnvelopeError('envelope header failed authentication: it was modified');
205
+ }
206
+ };
207
+ exports.verifyFileHeader = verifyFileHeader;
208
+ /** True when the file is unlocked with a passphrase rather than by recipients. */
209
+ const isPassphraseFile = (header) => header.stanzas.some((stanza) => stanza.type === StanzaType.Passphrase);
210
+ exports.isPassphraseFile = isPassphraseFile;
211
+ /** Wraps the file key under an Argon2id-derived key. The cost parameters travel in the stanza. */
212
+ const wrapWithPassphrase = (fileKey, passphrase, kdf = kdf_1.DEFAULT_KDF_PROFILE) => {
213
+ assertFileKey(fileKey);
214
+ const params = (0, kdf_1.resolveKdfParams)(kdf);
215
+ if (params.t > 0xffffffff || params.m > 0xffffffff || params.p > 0xff) {
216
+ throw new errors_1.InvalidParametersError('kdf parameters do not fit the envelope header');
217
+ }
218
+ const salt = (0, kdf_1.generateSalt)();
219
+ const prefix = new Uint8Array(PASSPHRASE_PARAMS_LENGTH);
220
+ const view = new DataView(prefix.buffer);
221
+ view.setUint32(0, params.t, false);
222
+ view.setUint32(4, params.m, false);
223
+ prefix[8] = params.p;
224
+ prefix.set(salt, 9);
225
+ const key = (0, kdf_1.deriveKey)(passphrase, salt, params);
226
+ try {
227
+ // The parameters are bound as associated data: lowering them changes the derived key anyway,
228
+ // and this keeps a wrapped key from being lifted into a stanza that claims other parameters.
229
+ const wrapped = (0, envelope_1.sealWithKey)(key, fileKey, (0, utils_2.concatBytes)(PASSPHRASE_CONTEXT, prefix));
230
+ return { type: StanzaType.Passphrase, body: (0, utils_2.concatBytes)(prefix, wrapped) };
231
+ }
232
+ finally {
233
+ key.fill(0);
234
+ }
235
+ };
236
+ exports.wrapWithPassphrase = wrapWithPassphrase;
237
+ /** Recovers the file key from a passphrase file. A wrong passphrase raises {@link WrongPassphraseError}. */
238
+ const unwrapWithPassphrase = (header, passphrase) => {
239
+ const stanza = header.stanzas.find((candidate) => candidate.type === StanzaType.Passphrase);
240
+ if (!stanza) {
241
+ throw new errors_1.InvalidParametersError('this file is encrypted to recipients, not with a passphrase');
242
+ }
243
+ if (stanza.body.length !== PASSPHRASE_PARAMS_LENGTH + WRAPPED_KEY_LENGTH) {
244
+ throw new errors_1.CorruptEnvelopeError('passphrase stanza has the wrong length');
245
+ }
246
+ const prefix = (0, bytes_1.copyBytes)(stanza.body, 0, PASSPHRASE_PARAMS_LENGTH);
247
+ const view = new DataView(prefix.buffer, prefix.byteOffset, prefix.byteLength);
248
+ let params;
249
+ try {
250
+ params = (0, kdf_1.resolveKdfParams)({ t: view.getUint32(0, false), m: view.getUint32(4, false), p: prefix[8] });
251
+ }
252
+ catch (error) {
253
+ throw new errors_1.CorruptEnvelopeError(`passphrase stanza carries unacceptable kdf parameters: ${error.message}`);
254
+ }
255
+ const key = (0, kdf_1.deriveKey)(passphrase, (0, bytes_1.copyBytes)(prefix, 9), params);
256
+ try {
257
+ return (0, envelope_1.openWithKey)(key, (0, bytes_1.copyBytes)(stanza.body, PASSPHRASE_PARAMS_LENGTH), (0, utils_2.concatBytes)(PASSPHRASE_CONTEXT, prefix));
258
+ }
259
+ catch {
260
+ throw new errors_1.WrongPassphraseError();
261
+ }
262
+ finally {
263
+ key.fill(0);
264
+ }
265
+ };
266
+ exports.unwrapWithPassphrase = unwrapWithPassphrase;
267
+ /** Starts a file: encodes its header and returns a streaming encryptor for the payload. */
268
+ const createFileEncryptor = (fileKey, stanzas) => {
269
+ const nonce = (0, stream_1.generateStreamNonce)();
270
+ const header = (0, exports.encodeFileHeader)(fileKey, stanzas, nonce);
271
+ const key = (0, stream_1.deriveStreamKey)(fileKey, nonce);
272
+ try {
273
+ return { header, stream: new stream_1.StreamEncryptor(key) };
274
+ }
275
+ finally {
276
+ key.fill(0);
277
+ }
278
+ };
279
+ exports.createFileEncryptor = createFileEncryptor;
280
+ /** Verifies the header with `fileKey` and returns a streaming decryptor for the payload. */
281
+ const createFileDecryptor = (header, fileKey) => {
282
+ (0, exports.verifyFileHeader)(header, fileKey);
283
+ const key = (0, stream_1.deriveStreamKey)(fileKey, header.nonce);
284
+ try {
285
+ return new stream_1.StreamDecryptor(key);
286
+ }
287
+ finally {
288
+ key.fill(0);
289
+ }
290
+ };
291
+ exports.createFileDecryptor = createFileDecryptor;
292
+ /** Encrypts bytes already in memory under `fileKey`, with the given stanzas in the header. */
293
+ const sealFile = (plaintext, fileKey, stanzas) => {
294
+ const { header, stream } = (0, exports.createFileEncryptor)(fileKey, stanzas);
295
+ const bytes = typeof plaintext === 'string' ? (0, utils_2.utf8ToBytes)(plaintext) : plaintext;
296
+ const head = stream.update(bytes);
297
+ return (0, utils_2.concatBytes)(header, head, stream.finish());
298
+ };
299
+ exports.sealFile = sealFile;
300
+ /**
301
+ * Decrypts a whole file held in memory. `unwrap` turns the parsed header into the file key (with
302
+ * a passphrase, an identity, or anything else). Nothing is returned unless the entire payload
303
+ * authenticates.
304
+ */
305
+ const openFile = (bytes, unwrap) => {
306
+ const header = (0, exports.parseFileHeader)(bytes);
307
+ const fileKey = unwrap(header);
308
+ try {
309
+ const stream = (0, exports.createFileDecryptor)(header, fileKey);
310
+ const head = stream.update(bytes.subarray(header.length));
311
+ return (0, utils_2.concatBytes)(head, stream.finish());
312
+ }
313
+ finally {
314
+ fileKey.fill(0);
315
+ }
316
+ };
317
+ exports.openFile = openFile;
318
+ /** Passphrase-encrypts bytes into a version 2 file. */
319
+ const encryptFile = (plaintext, passphrase, options = {}) => {
320
+ const fileKey = (0, exports.generateFileKey)();
321
+ try {
322
+ return (0, exports.sealFile)(plaintext, fileKey, [(0, exports.wrapWithPassphrase)(fileKey, passphrase, options.kdf)]);
323
+ }
324
+ finally {
325
+ fileKey.fill(0);
326
+ }
327
+ };
328
+ exports.encryptFile = encryptFile;
329
+ /** Inverse of {@link encryptFile}. */
330
+ const decryptFile = (bytes, passphrase) => (0, exports.openFile)(bytes, (header) => (0, exports.unwrapWithPassphrase)(header, passphrase));
331
+ exports.decryptFile = decryptFile;
332
+ /** Text form of a version 2 file, for small payloads that have to live in text. */
333
+ const armorFile = (file) => exports.FILE_ARMOR_PREFIX + base_1.base64.encode(file);
334
+ exports.armorFile = armorFile;
335
+ /** Inverse of {@link armorFile}. */
336
+ const dearmorFile = (text) => {
337
+ const trimmed = text.trim();
338
+ if (!trimmed.startsWith(exports.FILE_ARMOR_PREFIX)) {
339
+ throw new errors_1.CorruptEnvelopeError(`armored file must start with "${exports.FILE_ARMOR_PREFIX}"`);
340
+ }
341
+ try {
342
+ return base_1.base64.decode(trimmed.slice(exports.FILE_ARMOR_PREFIX.length));
343
+ }
344
+ catch {
345
+ throw new errors_1.CorruptEnvelopeError('armored file is not valid base64');
346
+ }
347
+ };
348
+ exports.dearmorFile = dearmorFile;
package/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from './armor';
2
2
  export * from './envelope';
3
3
  export * from './errors';
4
+ export * from './file';
4
5
  export * from './kdf';
6
+ export * from './stream';
package/index.js CHANGED
@@ -17,4 +17,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./armor"), exports);
18
18
  __exportStar(require("./envelope"), exports);
19
19
  __exportStar(require("./errors"), exports);
20
+ __exportStar(require("./file"), exports);
20
21
  __exportStar(require("./kdf"), exports);
22
+ __exportStar(require("./stream"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decryption/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Versioned authenticated envelope encryption: Argon2id + XChaCha20-Poly1305",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "main": "index.js",
@@ -43,5 +43,5 @@
43
43
  "devDependencies": {
44
44
  "makage": "0.3.0"
45
45
  },
46
- "gitHead": "49eff05f5fa934d2d045372f0ddb4626190822dd"
46
+ "gitHead": "9f301de50e0b3f40746c6d23ba5ab8d343869efe"
47
47
  }
package/stream.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Chunked authenticated encryption for payloads too large to hold in one buffer.
3
+ *
4
+ * This is the payload layer of the age file format (https://age-encryption.org/v1, "Payload"),
5
+ * which is the STREAM construction of Hoang, Reyhanitabar, Rogaway and Vizár ("Online
6
+ * Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance", 2015), implemented as
7
+ * specified rather than redesigned:
8
+ *
9
+ * - the plaintext is split into 64 KiB chunks, each sealed with ChaCha20-Poly1305;
10
+ * - the 12-byte nonce is an 11-byte big-endian chunk counter followed by one flag byte, `0x01`
11
+ * on the final chunk and `0x00` on every other;
12
+ * - the final chunk may be short, but may be empty only when the whole payload is empty;
13
+ * - the key is `HKDF-SHA256(ikm = file key, salt = 16-byte random nonce, info = "payload")`.
14
+ *
15
+ * Reordered, dropped, duplicated and truncated chunks all fail authentication, because the
16
+ * counter and the final flag are part of every nonce. The test suite decrypts age's own STREAM
17
+ * test vectors with this code.
18
+ */
19
+ /** Plaintext bytes per chunk. */
20
+ export declare const STREAM_CHUNK_SIZE: number;
21
+ /** Poly1305 tag appended to every chunk. */
22
+ export declare const STREAM_TAG_LENGTH = 16;
23
+ /** Random per-file nonce the payload key is derived with; it precedes the first chunk. */
24
+ export declare const STREAM_NONCE_LENGTH = 16;
25
+ /** Length of the derived ChaCha20-Poly1305 payload key. */
26
+ export declare const STREAM_KEY_LENGTH = 32;
27
+ /** Draws the random nonce that is stored in front of the chunks. */
28
+ export declare const generateStreamNonce: () => Uint8Array;
29
+ /** Derives the payload key exactly as age does. A file key is used for one payload only. */
30
+ export declare const deriveStreamKey: (fileKey: Uint8Array, nonce: Uint8Array) => Uint8Array;
31
+ /**
32
+ * Encrypts a payload incrementally. Feed plaintext in pieces of any size through
33
+ * {@link StreamEncryptor.update} and call {@link StreamEncryptor.finish} exactly once; each call
34
+ * returns the ciphertext that is ready to be written. Memory use is bounded by one chunk plus
35
+ * the largest piece passed in.
36
+ */
37
+ export declare class StreamEncryptor {
38
+ private readonly key;
39
+ private readonly nonces;
40
+ private pending;
41
+ private finished;
42
+ constructor(key: Uint8Array);
43
+ update(data: Uint8Array): Uint8Array;
44
+ /** Seals whatever is buffered as the final chunk. An empty payload is one empty final chunk. */
45
+ finish(): Uint8Array;
46
+ /** Wipes the key and any buffered plaintext. Called by finish(); call it yourself on abort. */
47
+ destroy(): void;
48
+ private seal;
49
+ }
50
+ /**
51
+ * Decrypts a payload incrementally. Plaintext returned by {@link StreamDecryptor.update} has been
52
+ * authenticated chunk by chunk, but the payload as a whole is only known to be complete once
53
+ * {@link StreamDecryptor.finish} returns: a truncated file fails there. Callers that write the
54
+ * plaintext somewhere must therefore treat it as provisional until finish() succeeds.
55
+ */
56
+ export declare class StreamDecryptor {
57
+ private readonly key;
58
+ private readonly nonces;
59
+ private pending;
60
+ private finished;
61
+ constructor(key: Uint8Array);
62
+ update(data: Uint8Array): Uint8Array;
63
+ /** Opens the final chunk. Throws if the payload was truncated or extended. */
64
+ finish(): Uint8Array;
65
+ /** Wipes the key. Called by finish(); call it yourself when abandoning a stream. */
66
+ destroy(): void;
67
+ private open;
68
+ }
69
+ /** One-shot form of {@link StreamEncryptor}, for payloads already in memory. */
70
+ export declare const streamEncrypt: (key: Uint8Array, plaintext: Uint8Array) => Uint8Array;
71
+ /** One-shot form of {@link StreamDecryptor}. Returns nothing unless the whole payload is intact. */
72
+ export declare const streamDecrypt: (key: Uint8Array, ciphertext: Uint8Array) => Uint8Array;