@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/README.md +112 -3
- package/bytes.d.ts +5 -0
- package/bytes.js +9 -0
- package/envelope.d.ts +25 -3
- package/envelope.js +32 -3
- package/esm/bytes.js +5 -0
- package/esm/envelope.js +29 -2
- package/esm/file.js +328 -0
- package/esm/index.js +2 -0
- package/esm/stream.js +223 -0
- package/file.d.ts +114 -0
- package/file.js +348 -0
- package/index.d.ts +2 -0
- package/index.js +2 -0
- package/package.json +5 -5
- package/stream.d.ts +72 -0
- package/stream.js +232 -0
package/esm/stream.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { chacha20poly1305 } from '@decryption/ciphers/chacha';
|
|
2
|
+
import { hkdf } from '@decryption/hashes/hkdf';
|
|
3
|
+
import { sha256 } from '@decryption/hashes/sha2';
|
|
4
|
+
import { concatBytes, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
|
|
5
|
+
import { copyBytes } from './bytes';
|
|
6
|
+
import { CorruptEnvelopeError, InvalidParametersError } from './errors';
|
|
7
|
+
/**
|
|
8
|
+
* Chunked authenticated encryption for payloads too large to hold in one buffer.
|
|
9
|
+
*
|
|
10
|
+
* This is the payload layer of the age file format (https://age-encryption.org/v1, "Payload"),
|
|
11
|
+
* which is the STREAM construction of Hoang, Reyhanitabar, Rogaway and Vizár ("Online
|
|
12
|
+
* Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance", 2015), implemented as
|
|
13
|
+
* specified rather than redesigned:
|
|
14
|
+
*
|
|
15
|
+
* - the plaintext is split into 64 KiB chunks, each sealed with ChaCha20-Poly1305;
|
|
16
|
+
* - the 12-byte nonce is an 11-byte big-endian chunk counter followed by one flag byte, `0x01`
|
|
17
|
+
* on the final chunk and `0x00` on every other;
|
|
18
|
+
* - the final chunk may be short, but may be empty only when the whole payload is empty;
|
|
19
|
+
* - the key is `HKDF-SHA256(ikm = file key, salt = 16-byte random nonce, info = "payload")`.
|
|
20
|
+
*
|
|
21
|
+
* Reordered, dropped, duplicated and truncated chunks all fail authentication, because the
|
|
22
|
+
* counter and the final flag are part of every nonce. The test suite decrypts age's own STREAM
|
|
23
|
+
* test vectors with this code.
|
|
24
|
+
*/
|
|
25
|
+
/** Plaintext bytes per chunk. */
|
|
26
|
+
export const STREAM_CHUNK_SIZE = 64 * 1024;
|
|
27
|
+
/** Poly1305 tag appended to every chunk. */
|
|
28
|
+
export const STREAM_TAG_LENGTH = 16;
|
|
29
|
+
/** Random per-file nonce the payload key is derived with; it precedes the first chunk. */
|
|
30
|
+
export const STREAM_NONCE_LENGTH = 16;
|
|
31
|
+
/** Length of the derived ChaCha20-Poly1305 payload key. */
|
|
32
|
+
export const STREAM_KEY_LENGTH = 32;
|
|
33
|
+
const ENCRYPTED_CHUNK_SIZE = STREAM_CHUNK_SIZE + STREAM_TAG_LENGTH;
|
|
34
|
+
const PAYLOAD_INFO = utf8ToBytes('payload');
|
|
35
|
+
const EMPTY = new Uint8Array(0);
|
|
36
|
+
/** Draws the random nonce that is stored in front of the chunks. */
|
|
37
|
+
export const generateStreamNonce = () => randomBytes(STREAM_NONCE_LENGTH);
|
|
38
|
+
/** Derives the payload key exactly as age does. A file key is used for one payload only. */
|
|
39
|
+
export const deriveStreamKey = (fileKey, nonce) => {
|
|
40
|
+
if (fileKey.length < 16) {
|
|
41
|
+
throw new InvalidParametersError(`file key must be at least 16 bytes, got ${fileKey.length}`);
|
|
42
|
+
}
|
|
43
|
+
if (nonce.length !== STREAM_NONCE_LENGTH) {
|
|
44
|
+
throw new InvalidParametersError(`stream nonce must be ${STREAM_NONCE_LENGTH} bytes, got ${nonce.length}`);
|
|
45
|
+
}
|
|
46
|
+
return hkdf(sha256, fileKey, nonce, PAYLOAD_INFO, STREAM_KEY_LENGTH);
|
|
47
|
+
};
|
|
48
|
+
/** Builds chunk nonces: an 11-byte big-endian counter, then the last-chunk flag. */
|
|
49
|
+
class ChunkNonces {
|
|
50
|
+
counter = 0;
|
|
51
|
+
/** Number of chunks numbered so far. */
|
|
52
|
+
get count() {
|
|
53
|
+
return this.counter;
|
|
54
|
+
}
|
|
55
|
+
next(last) {
|
|
56
|
+
// 2^53 chunks of 64 KiB is far beyond any real file, but the counter must never wrap.
|
|
57
|
+
if (!Number.isSafeInteger(this.counter + 1)) {
|
|
58
|
+
throw new InvalidParametersError('stream chunk counter exhausted');
|
|
59
|
+
}
|
|
60
|
+
const nonce = new Uint8Array(12);
|
|
61
|
+
let remaining = this.counter;
|
|
62
|
+
for (let i = 10; i >= 0 && remaining > 0; i--) {
|
|
63
|
+
nonce[i] = remaining % 256;
|
|
64
|
+
remaining = Math.floor(remaining / 256);
|
|
65
|
+
}
|
|
66
|
+
nonce[11] = last ? 1 : 0;
|
|
67
|
+
this.counter += 1;
|
|
68
|
+
return nonce;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const assertStreamKey = (key) => {
|
|
72
|
+
if (key.length !== STREAM_KEY_LENGTH) {
|
|
73
|
+
throw new InvalidParametersError(`stream key must be ${STREAM_KEY_LENGTH} bytes, got ${key.length}`);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const joinChunks = (chunks) => chunks.length === 1 ? chunks[0] : concatBytes(...chunks);
|
|
77
|
+
/**
|
|
78
|
+
* Encrypts a payload incrementally. Feed plaintext in pieces of any size through
|
|
79
|
+
* {@link StreamEncryptor.update} and call {@link StreamEncryptor.finish} exactly once; each call
|
|
80
|
+
* returns the ciphertext that is ready to be written. Memory use is bounded by one chunk plus
|
|
81
|
+
* the largest piece passed in.
|
|
82
|
+
*/
|
|
83
|
+
export class StreamEncryptor {
|
|
84
|
+
key;
|
|
85
|
+
nonces = new ChunkNonces();
|
|
86
|
+
pending = EMPTY;
|
|
87
|
+
finished = false;
|
|
88
|
+
constructor(key) {
|
|
89
|
+
assertStreamKey(key);
|
|
90
|
+
this.key = Uint8Array.from(key);
|
|
91
|
+
}
|
|
92
|
+
update(data) {
|
|
93
|
+
if (this.finished)
|
|
94
|
+
throw new InvalidParametersError('stream is already finished');
|
|
95
|
+
if (data.length === 0)
|
|
96
|
+
return EMPTY;
|
|
97
|
+
const sealed = [];
|
|
98
|
+
// A full chunk is only written once more plaintext follows it: whichever chunk turns out to
|
|
99
|
+
// be the last one has to be sealed with the final flag, and only finish() knows that.
|
|
100
|
+
let buffered = data;
|
|
101
|
+
if (this.pending.length === STREAM_CHUNK_SIZE) {
|
|
102
|
+
sealed.push(this.seal(this.pending, false));
|
|
103
|
+
}
|
|
104
|
+
else if (this.pending.length) {
|
|
105
|
+
buffered = concatBytes(this.pending, data);
|
|
106
|
+
}
|
|
107
|
+
let offset = 0;
|
|
108
|
+
while (buffered.length - offset > STREAM_CHUNK_SIZE) {
|
|
109
|
+
sealed.push(this.seal(buffered.subarray(offset, offset + STREAM_CHUNK_SIZE), false));
|
|
110
|
+
offset += STREAM_CHUNK_SIZE;
|
|
111
|
+
}
|
|
112
|
+
this.pending.fill(0);
|
|
113
|
+
this.pending = copyBytes(buffered, offset);
|
|
114
|
+
return joinChunks(sealed);
|
|
115
|
+
}
|
|
116
|
+
/** Seals whatever is buffered as the final chunk. An empty payload is one empty final chunk. */
|
|
117
|
+
finish() {
|
|
118
|
+
if (this.finished)
|
|
119
|
+
throw new InvalidParametersError('stream is already finished');
|
|
120
|
+
this.finished = true;
|
|
121
|
+
try {
|
|
122
|
+
return this.seal(this.pending, true);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
this.destroy();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Wipes the key and any buffered plaintext. Called by finish(); call it yourself on abort. */
|
|
129
|
+
destroy() {
|
|
130
|
+
this.finished = true;
|
|
131
|
+
this.key.fill(0);
|
|
132
|
+
this.pending.fill(0);
|
|
133
|
+
this.pending = EMPTY;
|
|
134
|
+
}
|
|
135
|
+
seal(chunk, last) {
|
|
136
|
+
return chacha20poly1305(this.key, this.nonces.next(last)).encrypt(chunk);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Decrypts a payload incrementally. Plaintext returned by {@link StreamDecryptor.update} has been
|
|
141
|
+
* authenticated chunk by chunk, but the payload as a whole is only known to be complete once
|
|
142
|
+
* {@link StreamDecryptor.finish} returns: a truncated file fails there. Callers that write the
|
|
143
|
+
* plaintext somewhere must therefore treat it as provisional until finish() succeeds.
|
|
144
|
+
*/
|
|
145
|
+
export class StreamDecryptor {
|
|
146
|
+
key;
|
|
147
|
+
nonces = new ChunkNonces();
|
|
148
|
+
pending = EMPTY;
|
|
149
|
+
finished = false;
|
|
150
|
+
constructor(key) {
|
|
151
|
+
assertStreamKey(key);
|
|
152
|
+
this.key = Uint8Array.from(key);
|
|
153
|
+
}
|
|
154
|
+
update(data) {
|
|
155
|
+
if (this.finished)
|
|
156
|
+
throw new InvalidParametersError('stream is already finished');
|
|
157
|
+
if (data.length === 0)
|
|
158
|
+
return EMPTY;
|
|
159
|
+
const opened = [];
|
|
160
|
+
// Mirror of the encryptor: a chunk is opened as a non-final one only when ciphertext
|
|
161
|
+
// follows it. The trailing chunk waits for finish(), which requires the final flag.
|
|
162
|
+
let buffered = data;
|
|
163
|
+
if (this.pending.length === ENCRYPTED_CHUNK_SIZE) {
|
|
164
|
+
opened.push(this.open(this.pending, false));
|
|
165
|
+
}
|
|
166
|
+
else if (this.pending.length) {
|
|
167
|
+
buffered = concatBytes(this.pending, data);
|
|
168
|
+
}
|
|
169
|
+
let offset = 0;
|
|
170
|
+
while (buffered.length - offset > ENCRYPTED_CHUNK_SIZE) {
|
|
171
|
+
opened.push(this.open(buffered.subarray(offset, offset + ENCRYPTED_CHUNK_SIZE), false));
|
|
172
|
+
offset += ENCRYPTED_CHUNK_SIZE;
|
|
173
|
+
}
|
|
174
|
+
this.pending = copyBytes(buffered, offset);
|
|
175
|
+
return joinChunks(opened);
|
|
176
|
+
}
|
|
177
|
+
/** Opens the final chunk. Throws if the payload was truncated or extended. */
|
|
178
|
+
finish() {
|
|
179
|
+
if (this.finished)
|
|
180
|
+
throw new InvalidParametersError('stream is already finished');
|
|
181
|
+
try {
|
|
182
|
+
if (this.pending.length < STREAM_TAG_LENGTH) {
|
|
183
|
+
throw new CorruptEnvelopeError('encrypted payload is truncated');
|
|
184
|
+
}
|
|
185
|
+
if (this.pending.length === STREAM_TAG_LENGTH && this.nonces.count > 0) {
|
|
186
|
+
// age: "the final chunk MUST NOT be empty unless the whole payload is empty".
|
|
187
|
+
throw new CorruptEnvelopeError('encrypted payload ends with an empty chunk');
|
|
188
|
+
}
|
|
189
|
+
return this.open(this.pending, true);
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
this.destroy();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Wipes the key. Called by finish(); call it yourself when abandoning a stream. */
|
|
196
|
+
destroy() {
|
|
197
|
+
this.finished = true;
|
|
198
|
+
this.key.fill(0);
|
|
199
|
+
this.pending = EMPTY;
|
|
200
|
+
}
|
|
201
|
+
open(chunk, last) {
|
|
202
|
+
const index = this.nonces.count;
|
|
203
|
+
try {
|
|
204
|
+
return chacha20poly1305(this.key, this.nonces.next(last)).decrypt(chunk);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
this.destroy();
|
|
208
|
+
throw new CorruptEnvelopeError(`encrypted payload failed authentication at chunk ${index}: it is corrupt, truncated or was modified`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/** One-shot form of {@link StreamEncryptor}, for payloads already in memory. */
|
|
213
|
+
export const streamEncrypt = (key, plaintext) => {
|
|
214
|
+
const encryptor = new StreamEncryptor(key);
|
|
215
|
+
const head = encryptor.update(plaintext);
|
|
216
|
+
return concatBytes(head, encryptor.finish());
|
|
217
|
+
};
|
|
218
|
+
/** One-shot form of {@link StreamDecryptor}. Returns nothing unless the whole payload is intact. */
|
|
219
|
+
export const streamDecrypt = (key, ciphertext) => {
|
|
220
|
+
const decryptor = new StreamDecryptor(key);
|
|
221
|
+
const head = decryptor.update(ciphertext);
|
|
222
|
+
return concatBytes(head, decryptor.finish());
|
|
223
|
+
};
|
package/file.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { KdfParams, KdfProfile } from './kdf';
|
|
2
|
+
import { StreamDecryptor, StreamEncryptor } from './stream';
|
|
3
|
+
/**
|
|
4
|
+
* Version 2 of the dcrypt format: a binary, streamable file envelope.
|
|
5
|
+
*
|
|
6
|
+
* ```text
|
|
7
|
+
* | magic | ver | suite | count | stanza … stanza | header MAC | nonce | STREAM chunks … |
|
|
8
|
+
* | DCRYPT | 2 | 2 | u16 | | 32 B | 16 B | |
|
|
9
|
+
* |<------------- authenticated by the MAC ------->|
|
|
10
|
+
*
|
|
11
|
+
* stanza: | type u8 | length u16 | body |
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* The layout follows the age file format: a random file key encrypts the payload, and each
|
|
15
|
+
* stanza holds one wrapped copy of that key (for a passphrase, or for an X25519 recipient). The
|
|
16
|
+
* header is authenticated with `HMAC-SHA256` under `HKDF-SHA256(file key, info = "header")`, and
|
|
17
|
+
* the payload is the STREAM construction in `stream.ts`. Only the encoding differs from age
|
|
18
|
+
* (binary fields instead of text lines), plus the key wrapping, which reuses this package's
|
|
19
|
+
* Argon2id + XChaCha20-Poly1305 and `@decryption/keys`' X25519 stanzas.
|
|
20
|
+
*
|
|
21
|
+
* Adding a way to unlock a file means adding a stanza type; the payload never changes.
|
|
22
|
+
*/
|
|
23
|
+
/** Format version written in the seventh byte. Version 1 is the single-shot envelope. */
|
|
24
|
+
export declare const FILE_VERSION = 2;
|
|
25
|
+
/** Length of the random file key. */
|
|
26
|
+
export declare const FILE_KEY_LENGTH = 32;
|
|
27
|
+
/** Length of the header MAC. */
|
|
28
|
+
export declare const FILE_MAC_LENGTH = 32;
|
|
29
|
+
/** Prefix of the text (armored) form of a version 2 file, e.g. `dcrypt.v2.<base64>`. */
|
|
30
|
+
export declare const FILE_ARMOR_PREFIX = "dcrypt.v2.";
|
|
31
|
+
/** Upper bounds accepted when reading, so a hostile header cannot make a reader buffer forever. */
|
|
32
|
+
export declare const MAX_STANZAS = 1024;
|
|
33
|
+
export declare const MAX_STANZA_BODY_LENGTH = 1024;
|
|
34
|
+
/** Known stanza types. Readers keep stanzas of unknown type so newer writers stay readable. */
|
|
35
|
+
export declare enum StanzaType {
|
|
36
|
+
/** Argon2id-derived key wraps the file key. Must be the only stanza, as with age's scrypt. */
|
|
37
|
+
Passphrase = 1,
|
|
38
|
+
/** X25519 recipient, produced by `@decryption/keys`. */
|
|
39
|
+
X25519 = 2
|
|
40
|
+
}
|
|
41
|
+
/** One wrapped copy of the file key. */
|
|
42
|
+
export interface FileStanza {
|
|
43
|
+
type: number;
|
|
44
|
+
body: Uint8Array;
|
|
45
|
+
}
|
|
46
|
+
/** Parsed, non-secret header of a version 2 file. */
|
|
47
|
+
export interface FileHeader {
|
|
48
|
+
version: number;
|
|
49
|
+
suite: number;
|
|
50
|
+
stanzas: FileStanza[];
|
|
51
|
+
/** HMAC over {@link FileHeader.authenticated}; check it with {@link verifyFileHeader}. */
|
|
52
|
+
mac: Uint8Array;
|
|
53
|
+
/** Per-file nonce the payload key is derived with. */
|
|
54
|
+
nonce: Uint8Array;
|
|
55
|
+
/** The header bytes covered by the MAC. */
|
|
56
|
+
authenticated: Uint8Array;
|
|
57
|
+
/** Offset of the first payload byte. */
|
|
58
|
+
length: number;
|
|
59
|
+
}
|
|
60
|
+
/** Draws a fresh random file key. Never reuse one: it is the root of a single file's keys. */
|
|
61
|
+
export declare const generateFileKey: () => Uint8Array;
|
|
62
|
+
/** True when `bytes` begin like a version 2 file. Eight bytes are enough to tell. */
|
|
63
|
+
export declare const isFileEnvelope: (bytes: Uint8Array) => boolean;
|
|
64
|
+
/** Encodes the complete header: stanzas, their MAC, and the payload nonce. */
|
|
65
|
+
export declare const encodeFileHeader: (fileKey: Uint8Array, stanzas: FileStanza[], nonce?: Uint8Array) => Uint8Array;
|
|
66
|
+
/**
|
|
67
|
+
* Parses a header from the start of `bytes`. Returns `undefined` when more bytes are needed, so
|
|
68
|
+
* a streaming reader can call it again with a longer prefix. Throws {@link CorruptEnvelopeError}
|
|
69
|
+
* for anything that is not a dcrypt file and {@link UnsupportedEnvelopeError} for versions or
|
|
70
|
+
* suites this build cannot open.
|
|
71
|
+
*/
|
|
72
|
+
export declare const tryParseFileHeader: (bytes: Uint8Array) => FileHeader | undefined;
|
|
73
|
+
/** {@link tryParseFileHeader} for callers that hold the whole file: a short header is corrupt. */
|
|
74
|
+
export declare const parseFileHeader: (bytes: Uint8Array) => FileHeader;
|
|
75
|
+
/**
|
|
76
|
+
* Checks the header MAC with the unwrapped file key. This is what stops an attacker from adding,
|
|
77
|
+
* removing or editing stanzas (for example to lower Argon2id cost parameters) on a file they
|
|
78
|
+
* cannot decrypt. Anyone who can unwrap the file key can also rewrite the header; that is
|
|
79
|
+
* inherent in the design and the same as in age.
|
|
80
|
+
*/
|
|
81
|
+
export declare const verifyFileHeader: (header: FileHeader, fileKey: Uint8Array) => void;
|
|
82
|
+
/** True when the file is unlocked with a passphrase rather than by recipients. */
|
|
83
|
+
export declare const isPassphraseFile: (header: FileHeader) => boolean;
|
|
84
|
+
/** Wraps the file key under an Argon2id-derived key. The cost parameters travel in the stanza. */
|
|
85
|
+
export declare const wrapWithPassphrase: (fileKey: Uint8Array, passphrase: string | Uint8Array, kdf?: KdfProfile | KdfParams) => FileStanza;
|
|
86
|
+
/** Recovers the file key from a passphrase file. A wrong passphrase raises {@link WrongPassphraseError}. */
|
|
87
|
+
export declare const unwrapWithPassphrase: (header: FileHeader, passphrase: string | Uint8Array) => Uint8Array;
|
|
88
|
+
/** The header to write first, and the encryptor for everything after it. */
|
|
89
|
+
export interface FileEncryptor {
|
|
90
|
+
header: Uint8Array;
|
|
91
|
+
stream: StreamEncryptor;
|
|
92
|
+
}
|
|
93
|
+
/** Starts a file: encodes its header and returns a streaming encryptor for the payload. */
|
|
94
|
+
export declare const createFileEncryptor: (fileKey: Uint8Array, stanzas: FileStanza[]) => FileEncryptor;
|
|
95
|
+
/** Verifies the header with `fileKey` and returns a streaming decryptor for the payload. */
|
|
96
|
+
export declare const createFileDecryptor: (header: FileHeader, fileKey: Uint8Array) => StreamDecryptor;
|
|
97
|
+
/** Encrypts bytes already in memory under `fileKey`, with the given stanzas in the header. */
|
|
98
|
+
export declare const sealFile: (plaintext: Uint8Array | string, fileKey: Uint8Array, stanzas: FileStanza[]) => Uint8Array;
|
|
99
|
+
/**
|
|
100
|
+
* Decrypts a whole file held in memory. `unwrap` turns the parsed header into the file key (with
|
|
101
|
+
* a passphrase, an identity, or anything else). Nothing is returned unless the entire payload
|
|
102
|
+
* authenticates.
|
|
103
|
+
*/
|
|
104
|
+
export declare const openFile: (bytes: Uint8Array, unwrap: (header: FileHeader) => Uint8Array) => Uint8Array;
|
|
105
|
+
/** Passphrase-encrypts bytes into a version 2 file. */
|
|
106
|
+
export declare const encryptFile: (plaintext: Uint8Array | string, passphrase: string | Uint8Array, options?: {
|
|
107
|
+
kdf?: KdfProfile | KdfParams;
|
|
108
|
+
}) => Uint8Array;
|
|
109
|
+
/** Inverse of {@link encryptFile}. */
|
|
110
|
+
export declare const decryptFile: (bytes: Uint8Array, passphrase: string | Uint8Array) => Uint8Array;
|
|
111
|
+
/** Text form of a version 2 file, for small payloads that have to live in text. */
|
|
112
|
+
export declare const armorFile: (file: Uint8Array) => string;
|
|
113
|
+
/** Inverse of {@link armorFile}. */
|
|
114
|
+
export declare const dearmorFile: (text: string) => Uint8Array;
|