@decryption/core 0.2.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/stream.js ADDED
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.streamDecrypt = exports.streamEncrypt = exports.StreamDecryptor = exports.StreamEncryptor = exports.deriveStreamKey = exports.generateStreamNonce = exports.STREAM_KEY_LENGTH = exports.STREAM_NONCE_LENGTH = exports.STREAM_TAG_LENGTH = exports.STREAM_CHUNK_SIZE = void 0;
4
+ const chacha_1 = require("@decryption/ciphers/chacha");
5
+ const hkdf_1 = require("@decryption/hashes/hkdf");
6
+ const sha2_1 = require("@decryption/hashes/sha2");
7
+ const utils_1 = require("@decryption/hashes/utils");
8
+ const bytes_1 = require("./bytes");
9
+ const errors_1 = require("./errors");
10
+ /**
11
+ * Chunked authenticated encryption for payloads too large to hold in one buffer.
12
+ *
13
+ * This is the payload layer of the age file format (https://age-encryption.org/v1, "Payload"),
14
+ * which is the STREAM construction of Hoang, Reyhanitabar, Rogaway and Vizár ("Online
15
+ * Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance", 2015), implemented as
16
+ * specified rather than redesigned:
17
+ *
18
+ * - the plaintext is split into 64 KiB chunks, each sealed with ChaCha20-Poly1305;
19
+ * - the 12-byte nonce is an 11-byte big-endian chunk counter followed by one flag byte, `0x01`
20
+ * on the final chunk and `0x00` on every other;
21
+ * - the final chunk may be short, but may be empty only when the whole payload is empty;
22
+ * - the key is `HKDF-SHA256(ikm = file key, salt = 16-byte random nonce, info = "payload")`.
23
+ *
24
+ * Reordered, dropped, duplicated and truncated chunks all fail authentication, because the
25
+ * counter and the final flag are part of every nonce. The test suite decrypts age's own STREAM
26
+ * test vectors with this code.
27
+ */
28
+ /** Plaintext bytes per chunk. */
29
+ exports.STREAM_CHUNK_SIZE = 64 * 1024;
30
+ /** Poly1305 tag appended to every chunk. */
31
+ exports.STREAM_TAG_LENGTH = 16;
32
+ /** Random per-file nonce the payload key is derived with; it precedes the first chunk. */
33
+ exports.STREAM_NONCE_LENGTH = 16;
34
+ /** Length of the derived ChaCha20-Poly1305 payload key. */
35
+ exports.STREAM_KEY_LENGTH = 32;
36
+ const ENCRYPTED_CHUNK_SIZE = exports.STREAM_CHUNK_SIZE + exports.STREAM_TAG_LENGTH;
37
+ const PAYLOAD_INFO = (0, utils_1.utf8ToBytes)('payload');
38
+ const EMPTY = new Uint8Array(0);
39
+ /** Draws the random nonce that is stored in front of the chunks. */
40
+ const generateStreamNonce = () => (0, utils_1.randomBytes)(exports.STREAM_NONCE_LENGTH);
41
+ exports.generateStreamNonce = generateStreamNonce;
42
+ /** Derives the payload key exactly as age does. A file key is used for one payload only. */
43
+ const deriveStreamKey = (fileKey, nonce) => {
44
+ if (fileKey.length < 16) {
45
+ throw new errors_1.InvalidParametersError(`file key must be at least 16 bytes, got ${fileKey.length}`);
46
+ }
47
+ if (nonce.length !== exports.STREAM_NONCE_LENGTH) {
48
+ throw new errors_1.InvalidParametersError(`stream nonce must be ${exports.STREAM_NONCE_LENGTH} bytes, got ${nonce.length}`);
49
+ }
50
+ return (0, hkdf_1.hkdf)(sha2_1.sha256, fileKey, nonce, PAYLOAD_INFO, exports.STREAM_KEY_LENGTH);
51
+ };
52
+ exports.deriveStreamKey = deriveStreamKey;
53
+ /** Builds chunk nonces: an 11-byte big-endian counter, then the last-chunk flag. */
54
+ class ChunkNonces {
55
+ counter = 0;
56
+ /** Number of chunks numbered so far. */
57
+ get count() {
58
+ return this.counter;
59
+ }
60
+ next(last) {
61
+ // 2^53 chunks of 64 KiB is far beyond any real file, but the counter must never wrap.
62
+ if (!Number.isSafeInteger(this.counter + 1)) {
63
+ throw new errors_1.InvalidParametersError('stream chunk counter exhausted');
64
+ }
65
+ const nonce = new Uint8Array(12);
66
+ let remaining = this.counter;
67
+ for (let i = 10; i >= 0 && remaining > 0; i--) {
68
+ nonce[i] = remaining % 256;
69
+ remaining = Math.floor(remaining / 256);
70
+ }
71
+ nonce[11] = last ? 1 : 0;
72
+ this.counter += 1;
73
+ return nonce;
74
+ }
75
+ }
76
+ const assertStreamKey = (key) => {
77
+ if (key.length !== exports.STREAM_KEY_LENGTH) {
78
+ throw new errors_1.InvalidParametersError(`stream key must be ${exports.STREAM_KEY_LENGTH} bytes, got ${key.length}`);
79
+ }
80
+ };
81
+ const joinChunks = (chunks) => chunks.length === 1 ? chunks[0] : (0, utils_1.concatBytes)(...chunks);
82
+ /**
83
+ * Encrypts a payload incrementally. Feed plaintext in pieces of any size through
84
+ * {@link StreamEncryptor.update} and call {@link StreamEncryptor.finish} exactly once; each call
85
+ * returns the ciphertext that is ready to be written. Memory use is bounded by one chunk plus
86
+ * the largest piece passed in.
87
+ */
88
+ class StreamEncryptor {
89
+ key;
90
+ nonces = new ChunkNonces();
91
+ pending = EMPTY;
92
+ finished = false;
93
+ constructor(key) {
94
+ assertStreamKey(key);
95
+ this.key = Uint8Array.from(key);
96
+ }
97
+ update(data) {
98
+ if (this.finished)
99
+ throw new errors_1.InvalidParametersError('stream is already finished');
100
+ if (data.length === 0)
101
+ return EMPTY;
102
+ const sealed = [];
103
+ // A full chunk is only written once more plaintext follows it: whichever chunk turns out to
104
+ // be the last one has to be sealed with the final flag, and only finish() knows that.
105
+ let buffered = data;
106
+ if (this.pending.length === exports.STREAM_CHUNK_SIZE) {
107
+ sealed.push(this.seal(this.pending, false));
108
+ }
109
+ else if (this.pending.length) {
110
+ buffered = (0, utils_1.concatBytes)(this.pending, data);
111
+ }
112
+ let offset = 0;
113
+ while (buffered.length - offset > exports.STREAM_CHUNK_SIZE) {
114
+ sealed.push(this.seal(buffered.subarray(offset, offset + exports.STREAM_CHUNK_SIZE), false));
115
+ offset += exports.STREAM_CHUNK_SIZE;
116
+ }
117
+ this.pending.fill(0);
118
+ this.pending = (0, bytes_1.copyBytes)(buffered, offset);
119
+ return joinChunks(sealed);
120
+ }
121
+ /** Seals whatever is buffered as the final chunk. An empty payload is one empty final chunk. */
122
+ finish() {
123
+ if (this.finished)
124
+ throw new errors_1.InvalidParametersError('stream is already finished');
125
+ this.finished = true;
126
+ try {
127
+ return this.seal(this.pending, true);
128
+ }
129
+ finally {
130
+ this.destroy();
131
+ }
132
+ }
133
+ /** Wipes the key and any buffered plaintext. Called by finish(); call it yourself on abort. */
134
+ destroy() {
135
+ this.finished = true;
136
+ this.key.fill(0);
137
+ this.pending.fill(0);
138
+ this.pending = EMPTY;
139
+ }
140
+ seal(chunk, last) {
141
+ return (0, chacha_1.chacha20poly1305)(this.key, this.nonces.next(last)).encrypt(chunk);
142
+ }
143
+ }
144
+ exports.StreamEncryptor = StreamEncryptor;
145
+ /**
146
+ * Decrypts a payload incrementally. Plaintext returned by {@link StreamDecryptor.update} has been
147
+ * authenticated chunk by chunk, but the payload as a whole is only known to be complete once
148
+ * {@link StreamDecryptor.finish} returns: a truncated file fails there. Callers that write the
149
+ * plaintext somewhere must therefore treat it as provisional until finish() succeeds.
150
+ */
151
+ class StreamDecryptor {
152
+ key;
153
+ nonces = new ChunkNonces();
154
+ pending = EMPTY;
155
+ finished = false;
156
+ constructor(key) {
157
+ assertStreamKey(key);
158
+ this.key = Uint8Array.from(key);
159
+ }
160
+ update(data) {
161
+ if (this.finished)
162
+ throw new errors_1.InvalidParametersError('stream is already finished');
163
+ if (data.length === 0)
164
+ return EMPTY;
165
+ const opened = [];
166
+ // Mirror of the encryptor: a chunk is opened as a non-final one only when ciphertext
167
+ // follows it. The trailing chunk waits for finish(), which requires the final flag.
168
+ let buffered = data;
169
+ if (this.pending.length === ENCRYPTED_CHUNK_SIZE) {
170
+ opened.push(this.open(this.pending, false));
171
+ }
172
+ else if (this.pending.length) {
173
+ buffered = (0, utils_1.concatBytes)(this.pending, data);
174
+ }
175
+ let offset = 0;
176
+ while (buffered.length - offset > ENCRYPTED_CHUNK_SIZE) {
177
+ opened.push(this.open(buffered.subarray(offset, offset + ENCRYPTED_CHUNK_SIZE), false));
178
+ offset += ENCRYPTED_CHUNK_SIZE;
179
+ }
180
+ this.pending = (0, bytes_1.copyBytes)(buffered, offset);
181
+ return joinChunks(opened);
182
+ }
183
+ /** Opens the final chunk. Throws if the payload was truncated or extended. */
184
+ finish() {
185
+ if (this.finished)
186
+ throw new errors_1.InvalidParametersError('stream is already finished');
187
+ try {
188
+ if (this.pending.length < exports.STREAM_TAG_LENGTH) {
189
+ throw new errors_1.CorruptEnvelopeError('encrypted payload is truncated');
190
+ }
191
+ if (this.pending.length === exports.STREAM_TAG_LENGTH && this.nonces.count > 0) {
192
+ // age: "the final chunk MUST NOT be empty unless the whole payload is empty".
193
+ throw new errors_1.CorruptEnvelopeError('encrypted payload ends with an empty chunk');
194
+ }
195
+ return this.open(this.pending, true);
196
+ }
197
+ finally {
198
+ this.destroy();
199
+ }
200
+ }
201
+ /** Wipes the key. Called by finish(); call it yourself when abandoning a stream. */
202
+ destroy() {
203
+ this.finished = true;
204
+ this.key.fill(0);
205
+ this.pending = EMPTY;
206
+ }
207
+ open(chunk, last) {
208
+ const index = this.nonces.count;
209
+ try {
210
+ return (0, chacha_1.chacha20poly1305)(this.key, this.nonces.next(last)).decrypt(chunk);
211
+ }
212
+ catch {
213
+ this.destroy();
214
+ throw new errors_1.CorruptEnvelopeError(`encrypted payload failed authentication at chunk ${index}: it is corrupt, truncated or was modified`);
215
+ }
216
+ }
217
+ }
218
+ exports.StreamDecryptor = StreamDecryptor;
219
+ /** One-shot form of {@link StreamEncryptor}, for payloads already in memory. */
220
+ const streamEncrypt = (key, plaintext) => {
221
+ const encryptor = new StreamEncryptor(key);
222
+ const head = encryptor.update(plaintext);
223
+ return (0, utils_1.concatBytes)(head, encryptor.finish());
224
+ };
225
+ exports.streamEncrypt = streamEncrypt;
226
+ /** One-shot form of {@link StreamDecryptor}. Returns nothing unless the whole payload is intact. */
227
+ const streamDecrypt = (key, ciphertext) => {
228
+ const decryptor = new StreamDecryptor(key);
229
+ const head = decryptor.update(ciphertext);
230
+ return (0, utils_1.concatBytes)(head, decryptor.finish());
231
+ };
232
+ exports.streamDecrypt = streamDecrypt;