@decryption/core 0.4.0 → 0.5.1
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 +113 -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 +2 -2
- package/stream.d.ts +72 -0
- package/stream.js +232 -0
package/README.md
CHANGED
|
@@ -8,14 +8,27 @@
|
|
|
8
8
|
<a href="https://github.com/constructive-io/decryption/actions/workflows/ci.yml">
|
|
9
9
|
<img height="20" src="https://github.com/constructive-io/decryption/actions/workflows/ci.yml/badge.svg" />
|
|
10
10
|
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/decryption/blob/main/LICENSE">
|
|
12
|
+
<img height="20" alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue.svg" />
|
|
13
|
+
</a>
|
|
11
14
|
<a href="https://www.npmjs.com/package/@decryption/core"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/decryption?filename=packages%2Fcore%2Fpackage.json"/></a>
|
|
12
15
|
</p>
|
|
13
16
|
|
|
14
17
|
|
|
15
18
|
<p align="center">
|
|
16
|
-
Authenticated, self-describing envelope encryption — Argon2id + XChaCha20-Poly1305
|
|
19
|
+
Authenticated, self-describing envelope encryption — Argon2id + XChaCha20-Poly1305, with a
|
|
20
|
+
chunked file format for payloads of any size.
|
|
17
21
|
</p>
|
|
18
22
|
|
|
23
|
+
Two formats share the `DCRYPT` magic and a version byte:
|
|
24
|
+
|
|
25
|
+
| Version | For | Shape |
|
|
26
|
+
|---------|-----|-------|
|
|
27
|
+
| 1 | short secrets: a value, a mnemonic, a key | one AEAD over the whole payload, held in memory |
|
|
28
|
+
| 2 | files of any size, one or many ways to unlock | header + 64 KiB authenticated chunks, streamable |
|
|
29
|
+
|
|
30
|
+
Runs anywhere `Uint8Array` does: this package has no Node.js dependency.
|
|
31
|
+
|
|
19
32
|
## Installation
|
|
20
33
|
|
|
21
34
|
```bash
|
|
@@ -50,7 +63,50 @@ decrypt(value, passphrase, { aad: 'DATABASE_URL' }); // ok
|
|
|
50
63
|
decrypt(value, passphrase, { aad: 'STRIPE_KEY' }); // throws WrongPassphraseError
|
|
51
64
|
```
|
|
52
65
|
|
|
53
|
-
##
|
|
66
|
+
## Files of any size
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { encryptFile, decryptFile } from '@decryption/core';
|
|
70
|
+
|
|
71
|
+
const file = encryptFile(bytes, passphrase); // Uint8Array, version 2
|
|
72
|
+
const back = decryptFile(file, passphrase);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
When the payload does not fit in memory, drive the cipher yourself. It is a plain
|
|
76
|
+
`update()` / `finish()` object, so it fits any stream API:
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
import {
|
|
80
|
+
createFileEncryptor,
|
|
81
|
+
createFileDecryptor,
|
|
82
|
+
generateFileKey,
|
|
83
|
+
tryParseFileHeader,
|
|
84
|
+
unwrapWithPassphrase,
|
|
85
|
+
wrapWithPassphrase,
|
|
86
|
+
} from '@decryption/core';
|
|
87
|
+
|
|
88
|
+
const fileKey = generateFileKey();
|
|
89
|
+
const { header, stream } = createFileEncryptor(fileKey, [wrapWithPassphrase(fileKey, passphrase)]);
|
|
90
|
+
|
|
91
|
+
write(header);
|
|
92
|
+
for await (const piece of source) write(stream.update(piece));
|
|
93
|
+
write(stream.finish());
|
|
94
|
+
|
|
95
|
+
// reading: the header first (undefined until enough bytes have arrived), then the chunks
|
|
96
|
+
const parsed = tryParseFileHeader(prefix);
|
|
97
|
+
const decryptor = createFileDecryptor(parsed, unwrapWithPassphrase(parsed, passphrase));
|
|
98
|
+
emit(decryptor.update(prefix.subarray(parsed.length)));
|
|
99
|
+
for await (const piece of rest) emit(decryptor.update(piece));
|
|
100
|
+
emit(decryptor.finish()); // throws if the file was truncated
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Plaintext returned by `update()` is authenticated chunk by chunk, but the file is only known to be
|
|
104
|
+
complete once `finish()` returns. Treat streamed output as provisional until then — write it to a
|
|
105
|
+
temporary file and rename it afterwards, as the `dcrypt` CLI does.
|
|
106
|
+
|
|
107
|
+
For recipients instead of a passphrase, see [`@decryption/keys`](../keys).
|
|
108
|
+
|
|
109
|
+
## Envelope format (version 1)
|
|
54
110
|
|
|
55
111
|
```text
|
|
56
112
|
| magic | ver | suite | t | m | p | salt | nonce | ciphertext || tag |
|
|
@@ -63,6 +119,50 @@ decrypt(value, passphrase, { aad: 'STRIPE_KEY' }); // throws WrongPassphraseEr
|
|
|
63
119
|
- Salt and nonce are drawn from the platform CSPRNG for every encryption.
|
|
64
120
|
- Suite and version bytes make future algorithm changes additive rather than breaking.
|
|
65
121
|
|
|
122
|
+
## File format (version 2)
|
|
123
|
+
|
|
124
|
+
```text
|
|
125
|
+
| magic | ver | suite | count | stanza … stanza | header MAC | nonce | chunk … chunk |
|
|
126
|
+
| DCRYPT | 2 | 2 | u16 | | 32 B | 16 B | |
|
|
127
|
+
|<------------- authenticated by the MAC ------->|
|
|
128
|
+
|
|
129
|
+
stanza: | type u8 | length u16 | body |
|
|
130
|
+
chunk: ChaCha20-Poly1305( ≤ 64 KiB of plaintext ) — ciphertext || 16-byte tag
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
The design is the [age file format](https://age-encryption.org/v1) with binary fields in place of
|
|
134
|
+
text lines. It is deliberately not a new construction:
|
|
135
|
+
|
|
136
|
+
- A random 32-byte **file key** encrypts the payload. Each **stanza** holds one wrapped copy of it:
|
|
137
|
+
type `1` under a passphrase (Argon2id parameters, salt, then the key sealed with
|
|
138
|
+
XChaCha20-Poly1305), type `2` for an X25519 recipient ([`@decryption/keys`](../keys)). A
|
|
139
|
+
passphrase stanza must be the only stanza, as with age's scrypt recipient.
|
|
140
|
+
- The **header MAC** is `HMAC-SHA256` under `HKDF-SHA256(file key, info = "header")`. It is checked
|
|
141
|
+
before any payload is decrypted, so stanzas and KDF costs cannot be edited or downgraded.
|
|
142
|
+
- The **payload** is age's STREAM: the key is
|
|
143
|
+
`HKDF-SHA256(file key, salt = nonce, info = "payload")`; each chunk's 12-byte nonce is an 11-byte
|
|
144
|
+
big-endian counter followed by a flag byte, `0x01` on the last chunk and `0x00` otherwise. The last
|
|
145
|
+
chunk may be short, and may be empty only if the whole payload is.
|
|
146
|
+
|
|
147
|
+
Because the counter and the last-chunk flag are part of every nonce, a chunk that is reordered,
|
|
148
|
+
duplicated, dropped or cut off fails authentication. The decryptor here is stricter than a minimal
|
|
149
|
+
reader: it never releases a chunk as non-final unless more ciphertext follows it. The test suite
|
|
150
|
+
decrypts age's own STREAM vectors ([C2SP/CCTV](https://github.com/C2SP/CCTV/tree/main/age)) with this
|
|
151
|
+
code.
|
|
152
|
+
|
|
153
|
+
Unlocking a file a new way means adding a stanza type; the payload never changes. Readers keep
|
|
154
|
+
stanzas they do not recognise, and bound what they will buffer (1024 stanzas of at most 1024 bytes).
|
|
155
|
+
|
|
156
|
+
`armorFile` / `dearmorFile` give the text form, `dcrypt.v2.<base64>`, for small files that have to
|
|
157
|
+
live in text. Version 2 has no associated-data option.
|
|
158
|
+
|
|
159
|
+
### What is audited
|
|
160
|
+
|
|
161
|
+
The primitives underneath — ChaCha20-Poly1305, XChaCha20-Poly1305, HKDF, HMAC, SHA-256 — come from
|
|
162
|
+
`@noble`, which has been audited upstream. Argon2id is outside that audit's scope, and neither
|
|
163
|
+
envelope format, nor this STREAM implementation, has been audited by a third party. The exact
|
|
164
|
+
boundary is in the [repository README](../../README.md#audit-status).
|
|
165
|
+
|
|
66
166
|
## KDF profiles
|
|
67
167
|
|
|
68
168
|
| Profile | Memory | Passes | Use for |
|
|
@@ -80,7 +180,7 @@ Every failure mode has a distinct type — decryption never silently returns an
|
|
|
80
180
|
| Error | Meaning |
|
|
81
181
|
|-------|---------|
|
|
82
182
|
| `WrongPassphraseError` | Passphrase is wrong or the ciphertext was tampered with |
|
|
83
|
-
| `CorruptEnvelopeError` | Not a `dcrypt` envelope, or
|
|
183
|
+
| `CorruptEnvelopeError` | Not a `dcrypt` envelope, truncated, or a file chunk failed authentication |
|
|
84
184
|
| `UnsupportedEnvelopeError` | Newer format version or unknown algorithm suite |
|
|
85
185
|
| `InvalidParametersError` | Caller passed arguments that cannot be secure |
|
|
86
186
|
|
|
@@ -96,6 +196,16 @@ const sealed = sealWithKey(key, plaintext, 'context');
|
|
|
96
196
|
const opened = openWithKey(key, sealed, 'context');
|
|
97
197
|
```
|
|
98
198
|
|
|
199
|
+
## Credits
|
|
200
|
+
|
|
201
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
202
|
+
|
|
203
|
+
## Disclaimer
|
|
204
|
+
|
|
205
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
206
|
+
|
|
207
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
|
208
|
+
|
|
99
209
|
---
|
|
100
210
|
|
|
101
211
|
## Development
|
package/bytes.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copies a range into a plain Uint8Array. `Buffer.prototype.slice` returns a view of the caller's
|
|
3
|
+
* memory rather than a copy, so `bytes.slice()` must not be relied on to detach from the input.
|
|
4
|
+
*/
|
|
5
|
+
export declare const copyBytes: (bytes: Uint8Array, start?: number, end?: number) => Uint8Array;
|
package/bytes.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.copyBytes = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Copies a range into a plain Uint8Array. `Buffer.prototype.slice` returns a view of the caller's
|
|
6
|
+
* memory rather than a copy, so `bytes.slice()` must not be relied on to detach from the input.
|
|
7
|
+
*/
|
|
8
|
+
const copyBytes = (bytes, start = 0, end = bytes.length) => Uint8Array.prototype.slice.call(bytes, start, end);
|
|
9
|
+
exports.copyBytes = copyBytes;
|
package/envelope.d.ts
CHANGED
|
@@ -4,11 +4,15 @@ export declare const MAGIC: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer
|
|
|
4
4
|
/** Envelope format version implemented by this package. */
|
|
5
5
|
export declare const VERSION = 1;
|
|
6
6
|
/**
|
|
7
|
-
* Algorithm suite identifier.
|
|
8
|
-
*
|
|
7
|
+
* Algorithm suite identifier. The byte is present so that a future suite (say, AES-256-GCM for
|
|
8
|
+
* FIPS environments) can be added without a format break.
|
|
9
|
+
*
|
|
10
|
+
* - `Argon2idXChaCha20Poly1305` is the single-shot version 1 envelope in this file.
|
|
11
|
+
* - `HkdfSha256ChaCha20Poly1305Stream` is the chunked version 2 file format in `file.ts`.
|
|
9
12
|
*/
|
|
10
13
|
export declare enum Suite {
|
|
11
|
-
Argon2idXChaCha20Poly1305 = 1
|
|
14
|
+
Argon2idXChaCha20Poly1305 = 1,
|
|
15
|
+
HkdfSha256ChaCha20Poly1305Stream = 2
|
|
12
16
|
}
|
|
13
17
|
export declare const NONCE_LENGTH = 24;
|
|
14
18
|
export declare const TAG_LENGTH = 16;
|
|
@@ -46,6 +50,24 @@ export declare const parseHeader: (envelope: Uint8Array) => EnvelopeHeader;
|
|
|
46
50
|
* The header is authenticated, so cost parameters cannot be downgraded by an attacker.
|
|
47
51
|
*/
|
|
48
52
|
export declare const encrypt: (plaintext: Uint8Array | string, passphrase: string | Uint8Array, options?: EncryptOptions) => Uint8Array;
|
|
53
|
+
/**
|
|
54
|
+
* A passphrase key derivation kept for reuse. Argon2id is deliberately expensive, so a caller
|
|
55
|
+
* that re-encrypts the same data repeatedly (a vault flushing its snapshot) can derive once and
|
|
56
|
+
* pay only the AEAD cost per write. The salt is part of the derivation and is reused with it;
|
|
57
|
+
* confidentiality still rests on the fresh random nonce chosen for every envelope.
|
|
58
|
+
*/
|
|
59
|
+
export interface DerivedEnvelopeKey {
|
|
60
|
+
key: Uint8Array;
|
|
61
|
+
salt: Uint8Array;
|
|
62
|
+
kdf: KdfParams;
|
|
63
|
+
}
|
|
64
|
+
/** Runs the KDF once, yielding a handle usable with {@link encryptWithDerivedKey}. */
|
|
65
|
+
export declare const deriveEnvelopeKey: (passphrase: string | Uint8Array, kdf?: KdfProfile | KdfParams) => DerivedEnvelopeKey;
|
|
66
|
+
/**
|
|
67
|
+
* {@link encrypt} with the KDF already done. Produces an identical envelope — the header still
|
|
68
|
+
* records the salt and cost parameters, so {@link decrypt} opens it with the passphrase alone.
|
|
69
|
+
*/
|
|
70
|
+
export declare const encryptWithDerivedKey: (plaintext: Uint8Array | string, derived: DerivedEnvelopeKey, options?: Pick<EncryptOptions, "aad">) => Uint8Array;
|
|
49
71
|
/**
|
|
50
72
|
* Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
|
|
51
73
|
* {@link WrongPassphraseError} — this format never returns an empty string on failure.
|
package/envelope.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.openWithKey = exports.sealWithKey = exports.decrypt = exports.encrypt = exports.parseHeader = exports.HEADER_LENGTH = exports.TAG_LENGTH = exports.NONCE_LENGTH = exports.Suite = exports.VERSION = exports.MAGIC = void 0;
|
|
3
|
+
exports.openWithKey = exports.sealWithKey = exports.decrypt = exports.encryptWithDerivedKey = exports.deriveEnvelopeKey = exports.encrypt = exports.parseHeader = exports.HEADER_LENGTH = exports.TAG_LENGTH = exports.NONCE_LENGTH = exports.Suite = exports.VERSION = exports.MAGIC = void 0;
|
|
4
4
|
const chacha_1 = require("@decryption/ciphers/chacha");
|
|
5
5
|
const utils_1 = require("@decryption/hashes/utils");
|
|
6
6
|
const errors_1 = require("./errors");
|
|
@@ -10,12 +10,16 @@ exports.MAGIC = (0, utils_1.utf8ToBytes)('DCRYPT');
|
|
|
10
10
|
/** Envelope format version implemented by this package. */
|
|
11
11
|
exports.VERSION = 1;
|
|
12
12
|
/**
|
|
13
|
-
* Algorithm suite identifier.
|
|
14
|
-
*
|
|
13
|
+
* Algorithm suite identifier. The byte is present so that a future suite (say, AES-256-GCM for
|
|
14
|
+
* FIPS environments) can be added without a format break.
|
|
15
|
+
*
|
|
16
|
+
* - `Argon2idXChaCha20Poly1305` is the single-shot version 1 envelope in this file.
|
|
17
|
+
* - `HkdfSha256ChaCha20Poly1305Stream` is the chunked version 2 file format in `file.ts`.
|
|
15
18
|
*/
|
|
16
19
|
var Suite;
|
|
17
20
|
(function (Suite) {
|
|
18
21
|
Suite[Suite["Argon2idXChaCha20Poly1305"] = 1] = "Argon2idXChaCha20Poly1305";
|
|
22
|
+
Suite[Suite["HkdfSha256ChaCha20Poly1305Stream"] = 2] = "HkdfSha256ChaCha20Poly1305Stream";
|
|
19
23
|
})(Suite || (exports.Suite = Suite = {}));
|
|
20
24
|
exports.NONCE_LENGTH = 24;
|
|
21
25
|
exports.TAG_LENGTH = 16;
|
|
@@ -97,6 +101,31 @@ const encrypt = (plaintext, passphrase, options = {}) => {
|
|
|
97
101
|
}
|
|
98
102
|
};
|
|
99
103
|
exports.encrypt = encrypt;
|
|
104
|
+
/** Runs the KDF once, yielding a handle usable with {@link encryptWithDerivedKey}. */
|
|
105
|
+
const deriveEnvelopeKey = (passphrase, kdf = kdf_1.DEFAULT_KDF_PROFILE) => {
|
|
106
|
+
const params = (0, kdf_1.resolveKdfParams)(kdf);
|
|
107
|
+
const salt = (0, kdf_1.generateSalt)();
|
|
108
|
+
return { key: (0, kdf_1.deriveKey)(passphrase, salt, params), salt, kdf: params };
|
|
109
|
+
};
|
|
110
|
+
exports.deriveEnvelopeKey = deriveEnvelopeKey;
|
|
111
|
+
/**
|
|
112
|
+
* {@link encrypt} with the KDF already done. Produces an identical envelope — the header still
|
|
113
|
+
* records the salt and cost parameters, so {@link decrypt} opens it with the passphrase alone.
|
|
114
|
+
*/
|
|
115
|
+
const encryptWithDerivedKey = (plaintext, derived, options = {}) => {
|
|
116
|
+
assertKey(derived.key);
|
|
117
|
+
const nonce = (0, utils_1.randomBytes)(exports.NONCE_LENGTH);
|
|
118
|
+
const header = encodeHeader({
|
|
119
|
+
version: exports.VERSION,
|
|
120
|
+
suite: Suite.Argon2idXChaCha20Poly1305,
|
|
121
|
+
kdf: derived.kdf,
|
|
122
|
+
salt: derived.salt,
|
|
123
|
+
nonce,
|
|
124
|
+
});
|
|
125
|
+
const aad = (0, utils_1.concatBytes)(header, toBytes(options.aad));
|
|
126
|
+
return (0, utils_1.concatBytes)(header, (0, chacha_1.xchacha20poly1305)(derived.key, nonce, aad).encrypt(toBytes(plaintext)));
|
|
127
|
+
};
|
|
128
|
+
exports.encryptWithDerivedKey = encryptWithDerivedKey;
|
|
100
129
|
/**
|
|
101
130
|
* Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
|
|
102
131
|
* {@link WrongPassphraseError} — this format never returns an empty string on failure.
|
package/esm/bytes.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copies a range into a plain Uint8Array. `Buffer.prototype.slice` returns a view of the caller's
|
|
3
|
+
* memory rather than a copy, so `bytes.slice()` must not be relied on to detach from the input.
|
|
4
|
+
*/
|
|
5
|
+
export const copyBytes = (bytes, start = 0, end = bytes.length) => Uint8Array.prototype.slice.call(bytes, start, end);
|
package/esm/envelope.js
CHANGED
|
@@ -7,12 +7,16 @@ export const MAGIC = utf8ToBytes('DCRYPT');
|
|
|
7
7
|
/** Envelope format version implemented by this package. */
|
|
8
8
|
export const VERSION = 1;
|
|
9
9
|
/**
|
|
10
|
-
* Algorithm suite identifier.
|
|
11
|
-
*
|
|
10
|
+
* Algorithm suite identifier. The byte is present so that a future suite (say, AES-256-GCM for
|
|
11
|
+
* FIPS environments) can be added without a format break.
|
|
12
|
+
*
|
|
13
|
+
* - `Argon2idXChaCha20Poly1305` is the single-shot version 1 envelope in this file.
|
|
14
|
+
* - `HkdfSha256ChaCha20Poly1305Stream` is the chunked version 2 file format in `file.ts`.
|
|
12
15
|
*/
|
|
13
16
|
export var Suite;
|
|
14
17
|
(function (Suite) {
|
|
15
18
|
Suite[Suite["Argon2idXChaCha20Poly1305"] = 1] = "Argon2idXChaCha20Poly1305";
|
|
19
|
+
Suite[Suite["HkdfSha256ChaCha20Poly1305Stream"] = 2] = "HkdfSha256ChaCha20Poly1305Stream";
|
|
16
20
|
})(Suite || (Suite = {}));
|
|
17
21
|
export const NONCE_LENGTH = 24;
|
|
18
22
|
export const TAG_LENGTH = 16;
|
|
@@ -92,6 +96,29 @@ export const encrypt = (plaintext, passphrase, options = {}) => {
|
|
|
92
96
|
key.fill(0);
|
|
93
97
|
}
|
|
94
98
|
};
|
|
99
|
+
/** Runs the KDF once, yielding a handle usable with {@link encryptWithDerivedKey}. */
|
|
100
|
+
export const deriveEnvelopeKey = (passphrase, kdf = DEFAULT_KDF_PROFILE) => {
|
|
101
|
+
const params = resolveKdfParams(kdf);
|
|
102
|
+
const salt = generateSalt();
|
|
103
|
+
return { key: deriveKey(passphrase, salt, params), salt, kdf: params };
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* {@link encrypt} with the KDF already done. Produces an identical envelope — the header still
|
|
107
|
+
* records the salt and cost parameters, so {@link decrypt} opens it with the passphrase alone.
|
|
108
|
+
*/
|
|
109
|
+
export const encryptWithDerivedKey = (plaintext, derived, options = {}) => {
|
|
110
|
+
assertKey(derived.key);
|
|
111
|
+
const nonce = randomBytes(NONCE_LENGTH);
|
|
112
|
+
const header = encodeHeader({
|
|
113
|
+
version: VERSION,
|
|
114
|
+
suite: Suite.Argon2idXChaCha20Poly1305,
|
|
115
|
+
kdf: derived.kdf,
|
|
116
|
+
salt: derived.salt,
|
|
117
|
+
nonce,
|
|
118
|
+
});
|
|
119
|
+
const aad = concatBytes(header, toBytes(options.aad));
|
|
120
|
+
return concatBytes(header, xchacha20poly1305(derived.key, nonce, aad).encrypt(toBytes(plaintext)));
|
|
121
|
+
};
|
|
95
122
|
/**
|
|
96
123
|
* Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
|
|
97
124
|
* {@link WrongPassphraseError} — this format never returns an empty string on failure.
|
package/esm/file.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { base64 } from '@decryption/base';
|
|
2
|
+
import { equalBytes } from '@decryption/ciphers/utils';
|
|
3
|
+
import { hkdf } from '@decryption/hashes/hkdf';
|
|
4
|
+
import { hmac } from '@decryption/hashes/hmac';
|
|
5
|
+
import { sha256 } from '@decryption/hashes/sha2';
|
|
6
|
+
import { concatBytes, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
|
|
7
|
+
import { copyBytes } from './bytes';
|
|
8
|
+
import { MAGIC, NONCE_LENGTH, openWithKey, sealWithKey, Suite, TAG_LENGTH } from './envelope';
|
|
9
|
+
import { CorruptEnvelopeError, InvalidParametersError, UnsupportedEnvelopeError, WrongPassphraseError, } from './errors';
|
|
10
|
+
import { DEFAULT_KDF_PROFILE, deriveKey, generateSalt, resolveKdfParams, SALT_LENGTH, } from './kdf';
|
|
11
|
+
import { deriveStreamKey, generateStreamNonce, STREAM_NONCE_LENGTH, StreamDecryptor, StreamEncryptor, } from './stream';
|
|
12
|
+
/**
|
|
13
|
+
* Version 2 of the dcrypt format: a binary, streamable file envelope.
|
|
14
|
+
*
|
|
15
|
+
* ```text
|
|
16
|
+
* | magic | ver | suite | count | stanza … stanza | header MAC | nonce | STREAM chunks … |
|
|
17
|
+
* | DCRYPT | 2 | 2 | u16 | | 32 B | 16 B | |
|
|
18
|
+
* |<------------- authenticated by the MAC ------->|
|
|
19
|
+
*
|
|
20
|
+
* stanza: | type u8 | length u16 | body |
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* The layout follows the age file format: a random file key encrypts the payload, and each
|
|
24
|
+
* stanza holds one wrapped copy of that key (for a passphrase, or for an X25519 recipient). The
|
|
25
|
+
* header is authenticated with `HMAC-SHA256` under `HKDF-SHA256(file key, info = "header")`, and
|
|
26
|
+
* the payload is the STREAM construction in `stream.ts`. Only the encoding differs from age
|
|
27
|
+
* (binary fields instead of text lines), plus the key wrapping, which reuses this package's
|
|
28
|
+
* Argon2id + XChaCha20-Poly1305 and `@decryption/keys`' X25519 stanzas.
|
|
29
|
+
*
|
|
30
|
+
* Adding a way to unlock a file means adding a stanza type; the payload never changes.
|
|
31
|
+
*/
|
|
32
|
+
/** Format version written in the seventh byte. Version 1 is the single-shot envelope. */
|
|
33
|
+
export const FILE_VERSION = 2;
|
|
34
|
+
/** Length of the random file key. */
|
|
35
|
+
export const FILE_KEY_LENGTH = 32;
|
|
36
|
+
/** Length of the header MAC. */
|
|
37
|
+
export const FILE_MAC_LENGTH = 32;
|
|
38
|
+
/** Prefix of the text (armored) form of a version 2 file, e.g. `dcrypt.v2.<base64>`. */
|
|
39
|
+
export const FILE_ARMOR_PREFIX = 'dcrypt.v2.';
|
|
40
|
+
/** Upper bounds accepted when reading, so a hostile header cannot make a reader buffer forever. */
|
|
41
|
+
export const MAX_STANZAS = 1024;
|
|
42
|
+
export const MAX_STANZA_BODY_LENGTH = 1024;
|
|
43
|
+
/** Known stanza types. Readers keep stanzas of unknown type so newer writers stay readable. */
|
|
44
|
+
export var StanzaType;
|
|
45
|
+
(function (StanzaType) {
|
|
46
|
+
/** Argon2id-derived key wraps the file key. Must be the only stanza, as with age's scrypt. */
|
|
47
|
+
StanzaType[StanzaType["Passphrase"] = 1] = "Passphrase";
|
|
48
|
+
/** X25519 recipient, produced by `@decryption/keys`. */
|
|
49
|
+
StanzaType[StanzaType["X25519"] = 2] = "X25519";
|
|
50
|
+
})(StanzaType || (StanzaType = {}));
|
|
51
|
+
const FIXED_LENGTH = MAGIC.length + 1 + 1 + 2;
|
|
52
|
+
const TRAILER_LENGTH = FILE_MAC_LENGTH + STREAM_NONCE_LENGTH;
|
|
53
|
+
const HEADER_INFO = utf8ToBytes('header');
|
|
54
|
+
const PASSPHRASE_PARAMS_LENGTH = 4 + 4 + 1 + SALT_LENGTH;
|
|
55
|
+
const WRAPPED_KEY_LENGTH = NONCE_LENGTH + FILE_KEY_LENGTH + TAG_LENGTH;
|
|
56
|
+
const PASSPHRASE_CONTEXT = utf8ToBytes('dcrypt-file-passphrase-v2');
|
|
57
|
+
const assertFileKey = (fileKey) => {
|
|
58
|
+
if (fileKey.length !== FILE_KEY_LENGTH) {
|
|
59
|
+
throw new InvalidParametersError(`file key must be ${FILE_KEY_LENGTH} bytes, got ${fileKey.length}`);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const assertStanzas = (stanzas, Failure) => {
|
|
63
|
+
if (stanzas.length === 0)
|
|
64
|
+
throw new Failure('a file needs at least one stanza');
|
|
65
|
+
if (stanzas.length > MAX_STANZAS)
|
|
66
|
+
throw new Failure(`a file can hold at most ${MAX_STANZAS} stanzas`);
|
|
67
|
+
for (const stanza of stanzas) {
|
|
68
|
+
if (!Number.isInteger(stanza.type) || stanza.type < 1 || stanza.type > 255) {
|
|
69
|
+
throw new Failure(`invalid stanza type ${stanza.type}`);
|
|
70
|
+
}
|
|
71
|
+
if (stanza.body.length > MAX_STANZA_BODY_LENGTH) {
|
|
72
|
+
throw new Failure(`stanza body is longer than ${MAX_STANZA_BODY_LENGTH} bytes`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (stanzas.length > 1 && stanzas.some((stanza) => stanza.type === StanzaType.Passphrase)) {
|
|
76
|
+
throw new Failure('a passphrase stanza must be the only stanza in a file');
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
const headerMac = (fileKey, authenticated) => {
|
|
80
|
+
const macKey = hkdf(sha256, fileKey, undefined, HEADER_INFO, 32);
|
|
81
|
+
try {
|
|
82
|
+
return hmac(sha256, macKey, authenticated);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
macKey.fill(0);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/** Draws a fresh random file key. Never reuse one: it is the root of a single file's keys. */
|
|
89
|
+
export const generateFileKey = () => randomBytes(FILE_KEY_LENGTH);
|
|
90
|
+
/** True when `bytes` begin like a version 2 file. Eight bytes are enough to tell. */
|
|
91
|
+
export const isFileEnvelope = (bytes) => {
|
|
92
|
+
if (bytes.length < MAGIC.length + 1)
|
|
93
|
+
return false;
|
|
94
|
+
for (let i = 0; i < MAGIC.length; i++) {
|
|
95
|
+
if (bytes[i] !== MAGIC[i])
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
return bytes[MAGIC.length] === FILE_VERSION;
|
|
99
|
+
};
|
|
100
|
+
/** Encodes the complete header: stanzas, their MAC, and the payload nonce. */
|
|
101
|
+
export const encodeFileHeader = (fileKey, stanzas, nonce = generateStreamNonce()) => {
|
|
102
|
+
assertFileKey(fileKey);
|
|
103
|
+
assertStanzas(stanzas, InvalidParametersError);
|
|
104
|
+
if (nonce.length !== STREAM_NONCE_LENGTH) {
|
|
105
|
+
throw new InvalidParametersError(`stream nonce must be ${STREAM_NONCE_LENGTH} bytes`);
|
|
106
|
+
}
|
|
107
|
+
const fixed = new Uint8Array(FIXED_LENGTH);
|
|
108
|
+
fixed.set(MAGIC, 0);
|
|
109
|
+
fixed[MAGIC.length] = FILE_VERSION;
|
|
110
|
+
fixed[MAGIC.length + 1] = Suite.HkdfSha256ChaCha20Poly1305Stream;
|
|
111
|
+
new DataView(fixed.buffer).setUint16(MAGIC.length + 2, stanzas.length, false);
|
|
112
|
+
const encoded = stanzas.map((stanza) => {
|
|
113
|
+
const bytes = new Uint8Array(3 + stanza.body.length);
|
|
114
|
+
bytes[0] = stanza.type;
|
|
115
|
+
new DataView(bytes.buffer).setUint16(1, stanza.body.length, false);
|
|
116
|
+
bytes.set(stanza.body, 3);
|
|
117
|
+
return bytes;
|
|
118
|
+
});
|
|
119
|
+
const authenticated = concatBytes(fixed, ...encoded);
|
|
120
|
+
return concatBytes(authenticated, headerMac(fileKey, authenticated), nonce);
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* Parses a header from the start of `bytes`. Returns `undefined` when more bytes are needed, so
|
|
124
|
+
* a streaming reader can call it again with a longer prefix. Throws {@link CorruptEnvelopeError}
|
|
125
|
+
* for anything that is not a dcrypt file and {@link UnsupportedEnvelopeError} for versions or
|
|
126
|
+
* suites this build cannot open.
|
|
127
|
+
*/
|
|
128
|
+
export const tryParseFileHeader = (bytes) => {
|
|
129
|
+
for (let i = 0; i < Math.min(bytes.length, MAGIC.length); i++) {
|
|
130
|
+
if (bytes[i] !== MAGIC[i])
|
|
131
|
+
throw new CorruptEnvelopeError('not a dcrypt envelope');
|
|
132
|
+
}
|
|
133
|
+
if (bytes.length < FIXED_LENGTH)
|
|
134
|
+
return undefined;
|
|
135
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
136
|
+
const version = bytes[MAGIC.length];
|
|
137
|
+
const suite = bytes[MAGIC.length + 1];
|
|
138
|
+
if (version !== FILE_VERSION) {
|
|
139
|
+
throw new UnsupportedEnvelopeError(version === 1
|
|
140
|
+
? 'this is a version 1 envelope; open it with decrypt()'
|
|
141
|
+
: `unsupported envelope version ${version}; this build understands versions 1 and ${FILE_VERSION}`);
|
|
142
|
+
}
|
|
143
|
+
if (suite !== Suite.HkdfSha256ChaCha20Poly1305Stream) {
|
|
144
|
+
throw new UnsupportedEnvelopeError(`unsupported algorithm suite ${suite}`);
|
|
145
|
+
}
|
|
146
|
+
const count = view.getUint16(MAGIC.length + 2, false);
|
|
147
|
+
if (count === 0 || count > MAX_STANZAS) {
|
|
148
|
+
throw new CorruptEnvelopeError(`invalid stanza count ${count}`);
|
|
149
|
+
}
|
|
150
|
+
const stanzas = [];
|
|
151
|
+
let offset = FIXED_LENGTH;
|
|
152
|
+
for (let i = 0; i < count; i++) {
|
|
153
|
+
if (bytes.length < offset + 3)
|
|
154
|
+
return undefined;
|
|
155
|
+
const type = bytes[offset];
|
|
156
|
+
const length = view.getUint16(offset + 1, false);
|
|
157
|
+
if (type === 0)
|
|
158
|
+
throw new CorruptEnvelopeError('invalid stanza type 0');
|
|
159
|
+
if (length > MAX_STANZA_BODY_LENGTH) {
|
|
160
|
+
throw new CorruptEnvelopeError(`stanza body is longer than ${MAX_STANZA_BODY_LENGTH} bytes`);
|
|
161
|
+
}
|
|
162
|
+
if (bytes.length < offset + 3 + length)
|
|
163
|
+
return undefined;
|
|
164
|
+
stanzas.push({ type, body: copyBytes(bytes, offset + 3, offset + 3 + length) });
|
|
165
|
+
offset += 3 + length;
|
|
166
|
+
}
|
|
167
|
+
if (bytes.length < offset + TRAILER_LENGTH)
|
|
168
|
+
return undefined;
|
|
169
|
+
assertStanzas(stanzas, CorruptEnvelopeError);
|
|
170
|
+
return {
|
|
171
|
+
version,
|
|
172
|
+
suite,
|
|
173
|
+
stanzas,
|
|
174
|
+
mac: copyBytes(bytes, offset, offset + FILE_MAC_LENGTH),
|
|
175
|
+
nonce: copyBytes(bytes, offset + FILE_MAC_LENGTH, offset + TRAILER_LENGTH),
|
|
176
|
+
authenticated: copyBytes(bytes, 0, offset),
|
|
177
|
+
length: offset + TRAILER_LENGTH,
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
/** {@link tryParseFileHeader} for callers that hold the whole file: a short header is corrupt. */
|
|
181
|
+
export const parseFileHeader = (bytes) => {
|
|
182
|
+
const header = tryParseFileHeader(bytes);
|
|
183
|
+
if (!header)
|
|
184
|
+
throw new CorruptEnvelopeError('envelope header is truncated');
|
|
185
|
+
return header;
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Checks the header MAC with the unwrapped file key. This is what stops an attacker from adding,
|
|
189
|
+
* removing or editing stanzas (for example to lower Argon2id cost parameters) on a file they
|
|
190
|
+
* cannot decrypt. Anyone who can unwrap the file key can also rewrite the header; that is
|
|
191
|
+
* inherent in the design and the same as in age.
|
|
192
|
+
*/
|
|
193
|
+
export const verifyFileHeader = (header, fileKey) => {
|
|
194
|
+
assertFileKey(fileKey);
|
|
195
|
+
if (!equalBytes(headerMac(fileKey, header.authenticated), header.mac)) {
|
|
196
|
+
throw new CorruptEnvelopeError('envelope header failed authentication: it was modified');
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
/** True when the file is unlocked with a passphrase rather than by recipients. */
|
|
200
|
+
export const isPassphraseFile = (header) => header.stanzas.some((stanza) => stanza.type === StanzaType.Passphrase);
|
|
201
|
+
/** Wraps the file key under an Argon2id-derived key. The cost parameters travel in the stanza. */
|
|
202
|
+
export const wrapWithPassphrase = (fileKey, passphrase, kdf = DEFAULT_KDF_PROFILE) => {
|
|
203
|
+
assertFileKey(fileKey);
|
|
204
|
+
const params = resolveKdfParams(kdf);
|
|
205
|
+
if (params.t > 0xffffffff || params.m > 0xffffffff || params.p > 0xff) {
|
|
206
|
+
throw new InvalidParametersError('kdf parameters do not fit the envelope header');
|
|
207
|
+
}
|
|
208
|
+
const salt = generateSalt();
|
|
209
|
+
const prefix = new Uint8Array(PASSPHRASE_PARAMS_LENGTH);
|
|
210
|
+
const view = new DataView(prefix.buffer);
|
|
211
|
+
view.setUint32(0, params.t, false);
|
|
212
|
+
view.setUint32(4, params.m, false);
|
|
213
|
+
prefix[8] = params.p;
|
|
214
|
+
prefix.set(salt, 9);
|
|
215
|
+
const key = deriveKey(passphrase, salt, params);
|
|
216
|
+
try {
|
|
217
|
+
// The parameters are bound as associated data: lowering them changes the derived key anyway,
|
|
218
|
+
// and this keeps a wrapped key from being lifted into a stanza that claims other parameters.
|
|
219
|
+
const wrapped = sealWithKey(key, fileKey, concatBytes(PASSPHRASE_CONTEXT, prefix));
|
|
220
|
+
return { type: StanzaType.Passphrase, body: concatBytes(prefix, wrapped) };
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
key.fill(0);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
/** Recovers the file key from a passphrase file. A wrong passphrase raises {@link WrongPassphraseError}. */
|
|
227
|
+
export const unwrapWithPassphrase = (header, passphrase) => {
|
|
228
|
+
const stanza = header.stanzas.find((candidate) => candidate.type === StanzaType.Passphrase);
|
|
229
|
+
if (!stanza) {
|
|
230
|
+
throw new InvalidParametersError('this file is encrypted to recipients, not with a passphrase');
|
|
231
|
+
}
|
|
232
|
+
if (stanza.body.length !== PASSPHRASE_PARAMS_LENGTH + WRAPPED_KEY_LENGTH) {
|
|
233
|
+
throw new CorruptEnvelopeError('passphrase stanza has the wrong length');
|
|
234
|
+
}
|
|
235
|
+
const prefix = copyBytes(stanza.body, 0, PASSPHRASE_PARAMS_LENGTH);
|
|
236
|
+
const view = new DataView(prefix.buffer, prefix.byteOffset, prefix.byteLength);
|
|
237
|
+
let params;
|
|
238
|
+
try {
|
|
239
|
+
params = resolveKdfParams({ t: view.getUint32(0, false), m: view.getUint32(4, false), p: prefix[8] });
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
throw new CorruptEnvelopeError(`passphrase stanza carries unacceptable kdf parameters: ${error.message}`);
|
|
243
|
+
}
|
|
244
|
+
const key = deriveKey(passphrase, copyBytes(prefix, 9), params);
|
|
245
|
+
try {
|
|
246
|
+
return openWithKey(key, copyBytes(stanza.body, PASSPHRASE_PARAMS_LENGTH), concatBytes(PASSPHRASE_CONTEXT, prefix));
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
throw new WrongPassphraseError();
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
key.fill(0);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
/** Starts a file: encodes its header and returns a streaming encryptor for the payload. */
|
|
256
|
+
export const createFileEncryptor = (fileKey, stanzas) => {
|
|
257
|
+
const nonce = generateStreamNonce();
|
|
258
|
+
const header = encodeFileHeader(fileKey, stanzas, nonce);
|
|
259
|
+
const key = deriveStreamKey(fileKey, nonce);
|
|
260
|
+
try {
|
|
261
|
+
return { header, stream: new StreamEncryptor(key) };
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
key.fill(0);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
/** Verifies the header with `fileKey` and returns a streaming decryptor for the payload. */
|
|
268
|
+
export const createFileDecryptor = (header, fileKey) => {
|
|
269
|
+
verifyFileHeader(header, fileKey);
|
|
270
|
+
const key = deriveStreamKey(fileKey, header.nonce);
|
|
271
|
+
try {
|
|
272
|
+
return new StreamDecryptor(key);
|
|
273
|
+
}
|
|
274
|
+
finally {
|
|
275
|
+
key.fill(0);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
/** Encrypts bytes already in memory under `fileKey`, with the given stanzas in the header. */
|
|
279
|
+
export const sealFile = (plaintext, fileKey, stanzas) => {
|
|
280
|
+
const { header, stream } = createFileEncryptor(fileKey, stanzas);
|
|
281
|
+
const bytes = typeof plaintext === 'string' ? utf8ToBytes(plaintext) : plaintext;
|
|
282
|
+
const head = stream.update(bytes);
|
|
283
|
+
return concatBytes(header, head, stream.finish());
|
|
284
|
+
};
|
|
285
|
+
/**
|
|
286
|
+
* Decrypts a whole file held in memory. `unwrap` turns the parsed header into the file key (with
|
|
287
|
+
* a passphrase, an identity, or anything else). Nothing is returned unless the entire payload
|
|
288
|
+
* authenticates.
|
|
289
|
+
*/
|
|
290
|
+
export const openFile = (bytes, unwrap) => {
|
|
291
|
+
const header = parseFileHeader(bytes);
|
|
292
|
+
const fileKey = unwrap(header);
|
|
293
|
+
try {
|
|
294
|
+
const stream = createFileDecryptor(header, fileKey);
|
|
295
|
+
const head = stream.update(bytes.subarray(header.length));
|
|
296
|
+
return concatBytes(head, stream.finish());
|
|
297
|
+
}
|
|
298
|
+
finally {
|
|
299
|
+
fileKey.fill(0);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
/** Passphrase-encrypts bytes into a version 2 file. */
|
|
303
|
+
export const encryptFile = (plaintext, passphrase, options = {}) => {
|
|
304
|
+
const fileKey = generateFileKey();
|
|
305
|
+
try {
|
|
306
|
+
return sealFile(plaintext, fileKey, [wrapWithPassphrase(fileKey, passphrase, options.kdf)]);
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
fileKey.fill(0);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
/** Inverse of {@link encryptFile}. */
|
|
313
|
+
export const decryptFile = (bytes, passphrase) => openFile(bytes, (header) => unwrapWithPassphrase(header, passphrase));
|
|
314
|
+
/** Text form of a version 2 file, for small payloads that have to live in text. */
|
|
315
|
+
export const armorFile = (file) => FILE_ARMOR_PREFIX + base64.encode(file);
|
|
316
|
+
/** Inverse of {@link armorFile}. */
|
|
317
|
+
export const dearmorFile = (text) => {
|
|
318
|
+
const trimmed = text.trim();
|
|
319
|
+
if (!trimmed.startsWith(FILE_ARMOR_PREFIX)) {
|
|
320
|
+
throw new CorruptEnvelopeError(`armored file must start with "${FILE_ARMOR_PREFIX}"`);
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
return base64.decode(trimmed.slice(FILE_ARMOR_PREFIX.length));
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
throw new CorruptEnvelopeError('armored file is not valid base64');
|
|
327
|
+
}
|
|
328
|
+
};
|