@decryption/core 0.2.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/LICENSE +21 -0
- package/README.md +122 -0
- package/armor.d.ts +11 -0
- package/armor.js +31 -0
- package/envelope.d.ts +57 -0
- package/envelope.js +145 -0
- package/errors.d.ts +20 -0
- package/errors.js +33 -0
- package/esm/armor.js +24 -0
- package/esm/envelope.js +137 -0
- package/esm/errors.js +25 -0
- package/esm/index.js +4 -0
- package/esm/kdf.js +54 -0
- package/index.d.ts +4 -0
- package/index.js +20 -0
- package/kdf.d.ts +45 -0
- package/kdf.js +61 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# @decryption/core
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
Authenticated, self-describing envelope encryption — Argon2id + XChaCha20-Poly1305.
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @decryption/core
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { encryptToString, decryptFromString } from '@decryption/core';
|
|
17
|
+
|
|
18
|
+
const armored = encryptToString('hunter2 is not a good password', passphrase);
|
|
19
|
+
// => "dcrypt.v1.RENSWVBUAQEAAAAD..."
|
|
20
|
+
|
|
21
|
+
const plaintext = decryptFromString(armored, passphrase);
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Binary form, and a cheaper KDF profile for interactive unlocks:
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { encrypt, decrypt } from '@decryption/core';
|
|
28
|
+
|
|
29
|
+
const envelope = encrypt(fileBytes, passphrase, { kdf: 'interactive' });
|
|
30
|
+
const bytes = decrypt(envelope, passphrase);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Bind a ciphertext to its context so values cannot be swapped between fields:
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
const value = encrypt(secret, passphrase, { aad: 'DATABASE_URL' });
|
|
37
|
+
decrypt(value, passphrase, { aad: 'DATABASE_URL' }); // ok
|
|
38
|
+
decrypt(value, passphrase, { aad: 'STRIPE_KEY' }); // throws WrongPassphraseError
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Envelope format
|
|
42
|
+
|
|
43
|
+
```text
|
|
44
|
+
| magic | ver | suite | t | m | p | salt | nonce | ciphertext || tag |
|
|
45
|
+
| DCRYPT | 1 | 1 | u32 | u32 | u8| 16 B | 24 B | n B ||16 B |
|
|
46
|
+
|<--------------------- 57-byte header, authenticated ------->|
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- The header is passed as AEAD associated data, so Argon2id cost parameters cannot be
|
|
50
|
+
downgraded by an attacker without invalidating the tag.
|
|
51
|
+
- Salt and nonce are drawn from the platform CSPRNG for every encryption.
|
|
52
|
+
- Suite and version bytes make future algorithm changes additive rather than breaking.
|
|
53
|
+
|
|
54
|
+
## KDF profiles
|
|
55
|
+
|
|
56
|
+
| Profile | Memory | Passes | Use for |
|
|
57
|
+
|---------|--------|--------|---------|
|
|
58
|
+
| `interactive` | 64 MiB | 2 | CLI prompts and UI unlock |
|
|
59
|
+
| `moderate` (default) | 256 MiB | 3 | files at rest |
|
|
60
|
+
| `sensitive` | 1 GiB | 4 | long-lived recovery material |
|
|
61
|
+
|
|
62
|
+
Parameters are recorded in the envelope, so raising the defaults never breaks old ciphertexts.
|
|
63
|
+
|
|
64
|
+
## Errors
|
|
65
|
+
|
|
66
|
+
Every failure mode has a distinct type — decryption never silently returns an empty string:
|
|
67
|
+
|
|
68
|
+
| Error | Meaning |
|
|
69
|
+
|-------|---------|
|
|
70
|
+
| `WrongPassphraseError` | Passphrase is wrong or the ciphertext was tampered with |
|
|
71
|
+
| `CorruptEnvelopeError` | Not a `dcrypt` envelope, or truncated |
|
|
72
|
+
| `UnsupportedEnvelopeError` | Newer format version or unknown algorithm suite |
|
|
73
|
+
| `InvalidParametersError` | Caller passed arguments that cannot be secure |
|
|
74
|
+
|
|
75
|
+
## Raw-key API
|
|
76
|
+
|
|
77
|
+
For callers that already hold a 32-byte key (e.g. per-recipient wrapping in
|
|
78
|
+
[`@decryption/secrets`](../secrets)):
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { sealWithKey, openWithKey } from '@decryption/core';
|
|
82
|
+
|
|
83
|
+
const sealed = sealWithKey(key, plaintext, 'context');
|
|
84
|
+
const opened = openWithKey(key, sealed, 'context');
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Development
|
|
90
|
+
|
|
91
|
+
### Setup
|
|
92
|
+
|
|
93
|
+
1. Clone the repository:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
git clone https://github.com/constructive-io/decryption.git
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
2. Install dependencies:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
cd decryption
|
|
103
|
+
pnpm install
|
|
104
|
+
pnpm build
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
3. Test the package of interest:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
cd packages/<packagename>
|
|
111
|
+
pnpm test:watch
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Credits
|
|
115
|
+
|
|
116
|
+
**🛠 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).**
|
|
117
|
+
|
|
118
|
+
## Disclaimer
|
|
119
|
+
|
|
120
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
121
|
+
|
|
122
|
+
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.
|
package/armor.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { DecryptOptions, EncryptOptions } from './envelope';
|
|
2
|
+
/** Prefix of the text (armored) representation, e.g. `dcrypt.v1.<base64>`. */
|
|
3
|
+
export declare const ARMOR_PREFIX = "dcrypt.v1.";
|
|
4
|
+
/** Wraps envelope bytes in the single-line text form that is safe to paste anywhere. */
|
|
5
|
+
export declare const armor: (envelope: Uint8Array) => string;
|
|
6
|
+
/** Inverse of {@link armor}. */
|
|
7
|
+
export declare const dearmor: (text: string) => Uint8Array;
|
|
8
|
+
/** Convenience wrapper: encrypt a string and return the armored text form. */
|
|
9
|
+
export declare const encryptToString: (plaintext: string, passphrase: string, options?: EncryptOptions) => string;
|
|
10
|
+
/** Convenience wrapper: decrypt armored text back into a string. */
|
|
11
|
+
export declare const decryptFromString: (armored: string, passphrase: string, options?: DecryptOptions) => string;
|
package/armor.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.decryptFromString = exports.encryptToString = exports.dearmor = exports.armor = exports.ARMOR_PREFIX = void 0;
|
|
4
|
+
const base_1 = require("@decryption/base");
|
|
5
|
+
const envelope_1 = require("./envelope");
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
/** Prefix of the text (armored) representation, e.g. `dcrypt.v1.<base64>`. */
|
|
8
|
+
exports.ARMOR_PREFIX = 'dcrypt.v1.';
|
|
9
|
+
/** Wraps envelope bytes in the single-line text form that is safe to paste anywhere. */
|
|
10
|
+
const armor = (envelope) => exports.ARMOR_PREFIX + base_1.base64.encode(envelope);
|
|
11
|
+
exports.armor = armor;
|
|
12
|
+
/** Inverse of {@link armor}. */
|
|
13
|
+
const dearmor = (text) => {
|
|
14
|
+
const trimmed = text.trim();
|
|
15
|
+
if (!trimmed.startsWith(exports.ARMOR_PREFIX)) {
|
|
16
|
+
throw new errors_1.CorruptEnvelopeError(`armored envelope must start with "${exports.ARMOR_PREFIX}"`);
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
return base_1.base64.decode(trimmed.slice(exports.ARMOR_PREFIX.length));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new errors_1.CorruptEnvelopeError('armored envelope is not valid base64');
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
exports.dearmor = dearmor;
|
|
26
|
+
/** Convenience wrapper: encrypt a string and return the armored text form. */
|
|
27
|
+
const encryptToString = (plaintext, passphrase, options) => (0, exports.armor)((0, envelope_1.encrypt)(plaintext, passphrase, options));
|
|
28
|
+
exports.encryptToString = encryptToString;
|
|
29
|
+
/** Convenience wrapper: decrypt armored text back into a string. */
|
|
30
|
+
const decryptFromString = (armored, passphrase, options) => new TextDecoder().decode((0, envelope_1.decrypt)((0, exports.dearmor)(armored), passphrase, options));
|
|
31
|
+
exports.decryptFromString = decryptFromString;
|
package/envelope.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { KdfParams, KdfProfile } from './kdf';
|
|
2
|
+
/** ASCII `DCRYPT`, the first six bytes of every envelope. */
|
|
3
|
+
export declare const MAGIC: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>;
|
|
4
|
+
/** Envelope format version implemented by this package. */
|
|
5
|
+
export declare const VERSION = 1;
|
|
6
|
+
/**
|
|
7
|
+
* Algorithm suite identifier. Only one suite exists today; the byte is present so that a future
|
|
8
|
+
* suite (say, AES-256-GCM for FIPS environments) can be added without a format break.
|
|
9
|
+
*/
|
|
10
|
+
export declare enum Suite {
|
|
11
|
+
Argon2idXChaCha20Poly1305 = 1
|
|
12
|
+
}
|
|
13
|
+
export declare const NONCE_LENGTH = 24;
|
|
14
|
+
export declare const TAG_LENGTH = 16;
|
|
15
|
+
export declare const HEADER_LENGTH: number;
|
|
16
|
+
export interface EncryptOptions {
|
|
17
|
+
/** Argon2id cost profile name, or explicit parameters. Defaults to `moderate`. */
|
|
18
|
+
kdf?: KdfProfile | KdfParams;
|
|
19
|
+
/**
|
|
20
|
+
* Extra authenticated data bound to the ciphertext but *not* stored in the envelope.
|
|
21
|
+
* The same value must be supplied to {@link decrypt}. Used to bind a ciphertext to its
|
|
22
|
+
* context — e.g. the key name in a secrets file — so values cannot be swapped between fields.
|
|
23
|
+
*/
|
|
24
|
+
aad?: Uint8Array | string;
|
|
25
|
+
}
|
|
26
|
+
export interface DecryptOptions {
|
|
27
|
+
aad?: Uint8Array | string;
|
|
28
|
+
}
|
|
29
|
+
/** Parsed, non-secret metadata of an envelope. */
|
|
30
|
+
export interface EnvelopeHeader {
|
|
31
|
+
version: number;
|
|
32
|
+
suite: Suite;
|
|
33
|
+
kdf: KdfParams;
|
|
34
|
+
salt: Uint8Array;
|
|
35
|
+
nonce: Uint8Array;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Parses (and validates) the envelope header. Throws {@link CorruptEnvelopeError} for anything
|
|
39
|
+
* that is not a `dcrypt` envelope and {@link UnsupportedEnvelopeError} for versions/suites this
|
|
40
|
+
* build cannot open — never a generic error, so callers can give users an accurate message.
|
|
41
|
+
*/
|
|
42
|
+
export declare const parseHeader: (envelope: Uint8Array) => EnvelopeHeader;
|
|
43
|
+
/**
|
|
44
|
+
* Encrypts `plaintext` under `passphrase`, returning a self-describing envelope:
|
|
45
|
+
* `magic || version || suite || argon2id params || salt || nonce || ciphertext || tag`.
|
|
46
|
+
* The header is authenticated, so cost parameters cannot be downgraded by an attacker.
|
|
47
|
+
*/
|
|
48
|
+
export declare const encrypt: (plaintext: Uint8Array | string, passphrase: string | Uint8Array, options?: EncryptOptions) => Uint8Array;
|
|
49
|
+
/**
|
|
50
|
+
* Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
|
|
51
|
+
* {@link WrongPassphraseError} — this format never returns an empty string on failure.
|
|
52
|
+
*/
|
|
53
|
+
export declare const decrypt: (envelope: Uint8Array, passphrase: string | Uint8Array, options?: DecryptOptions) => Uint8Array;
|
|
54
|
+
/** Encrypts with an already-derived 32-byte key: `nonce || ciphertext || tag`, no KDF header. */
|
|
55
|
+
export declare const sealWithKey: (key: Uint8Array, plaintext: Uint8Array | string, aad?: Uint8Array | string) => Uint8Array;
|
|
56
|
+
/** Inverse of {@link sealWithKey}. */
|
|
57
|
+
export declare const openWithKey: (key: Uint8Array, sealed: Uint8Array, aad?: Uint8Array | string) => Uint8Array;
|
package/envelope.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
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;
|
|
4
|
+
const chacha_1 = require("@decryption/ciphers/chacha");
|
|
5
|
+
const utils_1 = require("@decryption/hashes/utils");
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
const kdf_1 = require("./kdf");
|
|
8
|
+
/** ASCII `DCRYPT`, the first six bytes of every envelope. */
|
|
9
|
+
exports.MAGIC = (0, utils_1.utf8ToBytes)('DCRYPT');
|
|
10
|
+
/** Envelope format version implemented by this package. */
|
|
11
|
+
exports.VERSION = 1;
|
|
12
|
+
/**
|
|
13
|
+
* Algorithm suite identifier. Only one suite exists today; the byte is present so that a future
|
|
14
|
+
* suite (say, AES-256-GCM for FIPS environments) can be added without a format break.
|
|
15
|
+
*/
|
|
16
|
+
var Suite;
|
|
17
|
+
(function (Suite) {
|
|
18
|
+
Suite[Suite["Argon2idXChaCha20Poly1305"] = 1] = "Argon2idXChaCha20Poly1305";
|
|
19
|
+
})(Suite || (exports.Suite = Suite = {}));
|
|
20
|
+
exports.NONCE_LENGTH = 24;
|
|
21
|
+
exports.TAG_LENGTH = 16;
|
|
22
|
+
exports.HEADER_LENGTH = exports.MAGIC.length + 1 + 1 + 4 + 4 + 1 + kdf_1.SALT_LENGTH + exports.NONCE_LENGTH;
|
|
23
|
+
const toBytes = (value) => value === undefined ? new Uint8Array(0) : typeof value === 'string' ? (0, utils_1.utf8ToBytes)(value) : value;
|
|
24
|
+
const writeUint32BE = (view, offset, value) => view.setUint32(offset, value, false);
|
|
25
|
+
const encodeHeader = (header) => {
|
|
26
|
+
const bytes = new Uint8Array(exports.HEADER_LENGTH);
|
|
27
|
+
const view = new DataView(bytes.buffer);
|
|
28
|
+
let offset = 0;
|
|
29
|
+
bytes.set(exports.MAGIC, offset);
|
|
30
|
+
offset += exports.MAGIC.length;
|
|
31
|
+
bytes[offset++] = header.version;
|
|
32
|
+
bytes[offset++] = header.suite;
|
|
33
|
+
writeUint32BE(view, offset, header.kdf.t);
|
|
34
|
+
offset += 4;
|
|
35
|
+
writeUint32BE(view, offset, header.kdf.m);
|
|
36
|
+
offset += 4;
|
|
37
|
+
bytes[offset++] = header.kdf.p;
|
|
38
|
+
bytes.set(header.salt, offset);
|
|
39
|
+
offset += kdf_1.SALT_LENGTH;
|
|
40
|
+
bytes.set(header.nonce, offset);
|
|
41
|
+
return bytes;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Parses (and validates) the envelope header. Throws {@link CorruptEnvelopeError} for anything
|
|
45
|
+
* that is not a `dcrypt` envelope and {@link UnsupportedEnvelopeError} for versions/suites this
|
|
46
|
+
* build cannot open — never a generic error, so callers can give users an accurate message.
|
|
47
|
+
*/
|
|
48
|
+
const parseHeader = (envelope) => {
|
|
49
|
+
if (envelope.length < exports.HEADER_LENGTH + exports.TAG_LENGTH) {
|
|
50
|
+
throw new errors_1.CorruptEnvelopeError('envelope is shorter than the minimum header + tag length');
|
|
51
|
+
}
|
|
52
|
+
for (let i = 0; i < exports.MAGIC.length; i++) {
|
|
53
|
+
if (envelope[i] !== exports.MAGIC[i])
|
|
54
|
+
throw new errors_1.CorruptEnvelopeError('not a dcrypt envelope');
|
|
55
|
+
}
|
|
56
|
+
const view = new DataView(envelope.buffer, envelope.byteOffset, envelope.byteLength);
|
|
57
|
+
const version = envelope[6];
|
|
58
|
+
const suite = envelope[7];
|
|
59
|
+
if (version !== exports.VERSION) {
|
|
60
|
+
throw new errors_1.UnsupportedEnvelopeError(`unsupported envelope version ${version}; this build understands version ${exports.VERSION}`);
|
|
61
|
+
}
|
|
62
|
+
if (suite !== Suite.Argon2idXChaCha20Poly1305) {
|
|
63
|
+
throw new errors_1.UnsupportedEnvelopeError(`unsupported algorithm suite ${suite}`);
|
|
64
|
+
}
|
|
65
|
+
const kdf = {
|
|
66
|
+
t: view.getUint32(8, false),
|
|
67
|
+
m: view.getUint32(12, false),
|
|
68
|
+
p: envelope[16],
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
version,
|
|
72
|
+
suite,
|
|
73
|
+
kdf: (0, kdf_1.resolveKdfParams)(kdf),
|
|
74
|
+
salt: envelope.slice(17, 17 + kdf_1.SALT_LENGTH),
|
|
75
|
+
nonce: envelope.slice(17 + kdf_1.SALT_LENGTH, exports.HEADER_LENGTH),
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
exports.parseHeader = parseHeader;
|
|
79
|
+
/**
|
|
80
|
+
* Encrypts `plaintext` under `passphrase`, returning a self-describing envelope:
|
|
81
|
+
* `magic || version || suite || argon2id params || salt || nonce || ciphertext || tag`.
|
|
82
|
+
* The header is authenticated, so cost parameters cannot be downgraded by an attacker.
|
|
83
|
+
*/
|
|
84
|
+
const encrypt = (plaintext, passphrase, options = {}) => {
|
|
85
|
+
const kdf = (0, kdf_1.resolveKdfParams)(options.kdf ?? kdf_1.DEFAULT_KDF_PROFILE);
|
|
86
|
+
const salt = (0, kdf_1.generateSalt)();
|
|
87
|
+
const nonce = (0, utils_1.randomBytes)(exports.NONCE_LENGTH);
|
|
88
|
+
const header = encodeHeader({ version: exports.VERSION, suite: Suite.Argon2idXChaCha20Poly1305, kdf, salt, nonce });
|
|
89
|
+
const key = (0, kdf_1.deriveKey)(passphrase, salt, kdf);
|
|
90
|
+
try {
|
|
91
|
+
const aad = (0, utils_1.concatBytes)(header, toBytes(options.aad));
|
|
92
|
+
const ciphertext = (0, chacha_1.xchacha20poly1305)(key, nonce, aad).encrypt(toBytes(plaintext));
|
|
93
|
+
return (0, utils_1.concatBytes)(header, ciphertext);
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
key.fill(0);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
exports.encrypt = encrypt;
|
|
100
|
+
/**
|
|
101
|
+
* Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
|
|
102
|
+
* {@link WrongPassphraseError} — this format never returns an empty string on failure.
|
|
103
|
+
*/
|
|
104
|
+
const decrypt = (envelope, passphrase, options = {}) => {
|
|
105
|
+
const header = (0, exports.parseHeader)(envelope);
|
|
106
|
+
const key = (0, kdf_1.deriveKey)(passphrase, header.salt, header.kdf);
|
|
107
|
+
try {
|
|
108
|
+
const aad = (0, utils_1.concatBytes)(envelope.slice(0, exports.HEADER_LENGTH), toBytes(options.aad));
|
|
109
|
+
return (0, chacha_1.xchacha20poly1305)(key, header.nonce, aad).decrypt(envelope.slice(exports.HEADER_LENGTH));
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
throw new errors_1.WrongPassphraseError();
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
key.fill(0);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
exports.decrypt = decrypt;
|
|
119
|
+
/** Encrypts with an already-derived 32-byte key: `nonce || ciphertext || tag`, no KDF header. */
|
|
120
|
+
const sealWithKey = (key, plaintext, aad) => {
|
|
121
|
+
assertKey(key);
|
|
122
|
+
const nonce = (0, utils_1.randomBytes)(exports.NONCE_LENGTH);
|
|
123
|
+
return (0, utils_1.concatBytes)(nonce, (0, chacha_1.xchacha20poly1305)(key, nonce, toBytes(aad)).encrypt(toBytes(plaintext)));
|
|
124
|
+
};
|
|
125
|
+
exports.sealWithKey = sealWithKey;
|
|
126
|
+
/** Inverse of {@link sealWithKey}. */
|
|
127
|
+
const openWithKey = (key, sealed, aad) => {
|
|
128
|
+
assertKey(key);
|
|
129
|
+
if (sealed.length < exports.NONCE_LENGTH + exports.TAG_LENGTH) {
|
|
130
|
+
throw new errors_1.CorruptEnvelopeError('sealed payload is too short');
|
|
131
|
+
}
|
|
132
|
+
const nonce = sealed.slice(0, exports.NONCE_LENGTH);
|
|
133
|
+
try {
|
|
134
|
+
return (0, chacha_1.xchacha20poly1305)(key, nonce, toBytes(aad)).decrypt(sealed.slice(exports.NONCE_LENGTH));
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
throw new errors_1.WrongPassphraseError('wrong key, or the sealed payload has been tampered with');
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
exports.openWithKey = openWithKey;
|
|
141
|
+
const assertKey = (key) => {
|
|
142
|
+
if (key.length !== kdf_1.KEY_LENGTH) {
|
|
143
|
+
throw new errors_1.InvalidParametersError(`key must be ${kdf_1.KEY_LENGTH} bytes, got ${key.length}`);
|
|
144
|
+
}
|
|
145
|
+
};
|
package/errors.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Base class for every error thrown by `@decryption/core`. */
|
|
2
|
+
export declare class DecryptionError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* The envelope is well-formed but the key or passphrase is wrong (or the ciphertext
|
|
7
|
+
* was tampered with). AEAD cannot distinguish the two cases.
|
|
8
|
+
*/
|
|
9
|
+
export declare class WrongPassphraseError extends DecryptionError {
|
|
10
|
+
constructor(message?: string);
|
|
11
|
+
}
|
|
12
|
+
/** The bytes are not a `dcrypt` envelope, or the header is truncated/inconsistent. */
|
|
13
|
+
export declare class CorruptEnvelopeError extends DecryptionError {
|
|
14
|
+
}
|
|
15
|
+
/** The envelope was produced by a newer format version or an algorithm we do not implement. */
|
|
16
|
+
export declare class UnsupportedEnvelopeError extends DecryptionError {
|
|
17
|
+
}
|
|
18
|
+
/** Caller passed arguments that cannot produce a secure result. */
|
|
19
|
+
export declare class InvalidParametersError extends DecryptionError {
|
|
20
|
+
}
|
package/errors.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.InvalidParametersError = exports.UnsupportedEnvelopeError = exports.CorruptEnvelopeError = exports.WrongPassphraseError = exports.DecryptionError = void 0;
|
|
4
|
+
/** Base class for every error thrown by `@decryption/core`. */
|
|
5
|
+
class DecryptionError extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = new.target.name;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
exports.DecryptionError = DecryptionError;
|
|
12
|
+
/**
|
|
13
|
+
* The envelope is well-formed but the key or passphrase is wrong (or the ciphertext
|
|
14
|
+
* was tampered with). AEAD cannot distinguish the two cases.
|
|
15
|
+
*/
|
|
16
|
+
class WrongPassphraseError extends DecryptionError {
|
|
17
|
+
constructor(message = 'wrong passphrase, or the ciphertext has been tampered with') {
|
|
18
|
+
super(message);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.WrongPassphraseError = WrongPassphraseError;
|
|
22
|
+
/** The bytes are not a `dcrypt` envelope, or the header is truncated/inconsistent. */
|
|
23
|
+
class CorruptEnvelopeError extends DecryptionError {
|
|
24
|
+
}
|
|
25
|
+
exports.CorruptEnvelopeError = CorruptEnvelopeError;
|
|
26
|
+
/** The envelope was produced by a newer format version or an algorithm we do not implement. */
|
|
27
|
+
class UnsupportedEnvelopeError extends DecryptionError {
|
|
28
|
+
}
|
|
29
|
+
exports.UnsupportedEnvelopeError = UnsupportedEnvelopeError;
|
|
30
|
+
/** Caller passed arguments that cannot produce a secure result. */
|
|
31
|
+
class InvalidParametersError extends DecryptionError {
|
|
32
|
+
}
|
|
33
|
+
exports.InvalidParametersError = InvalidParametersError;
|
package/esm/armor.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { base64 } from '@decryption/base';
|
|
2
|
+
import { decrypt, encrypt } from './envelope';
|
|
3
|
+
import { CorruptEnvelopeError } from './errors';
|
|
4
|
+
/** Prefix of the text (armored) representation, e.g. `dcrypt.v1.<base64>`. */
|
|
5
|
+
export const ARMOR_PREFIX = 'dcrypt.v1.';
|
|
6
|
+
/** Wraps envelope bytes in the single-line text form that is safe to paste anywhere. */
|
|
7
|
+
export const armor = (envelope) => ARMOR_PREFIX + base64.encode(envelope);
|
|
8
|
+
/** Inverse of {@link armor}. */
|
|
9
|
+
export const dearmor = (text) => {
|
|
10
|
+
const trimmed = text.trim();
|
|
11
|
+
if (!trimmed.startsWith(ARMOR_PREFIX)) {
|
|
12
|
+
throw new CorruptEnvelopeError(`armored envelope must start with "${ARMOR_PREFIX}"`);
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
return base64.decode(trimmed.slice(ARMOR_PREFIX.length));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new CorruptEnvelopeError('armored envelope is not valid base64');
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/** Convenience wrapper: encrypt a string and return the armored text form. */
|
|
22
|
+
export const encryptToString = (plaintext, passphrase, options) => armor(encrypt(plaintext, passphrase, options));
|
|
23
|
+
/** Convenience wrapper: decrypt armored text back into a string. */
|
|
24
|
+
export const decryptFromString = (armored, passphrase, options) => new TextDecoder().decode(decrypt(dearmor(armored), passphrase, options));
|
package/esm/envelope.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { xchacha20poly1305 } from '@decryption/ciphers/chacha';
|
|
2
|
+
import { concatBytes, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
|
|
3
|
+
import { CorruptEnvelopeError, InvalidParametersError, UnsupportedEnvelopeError, WrongPassphraseError, } from './errors';
|
|
4
|
+
import { DEFAULT_KDF_PROFILE, deriveKey, generateSalt, KEY_LENGTH, resolveKdfParams, SALT_LENGTH, } from './kdf';
|
|
5
|
+
/** ASCII `DCRYPT`, the first six bytes of every envelope. */
|
|
6
|
+
export const MAGIC = utf8ToBytes('DCRYPT');
|
|
7
|
+
/** Envelope format version implemented by this package. */
|
|
8
|
+
export const VERSION = 1;
|
|
9
|
+
/**
|
|
10
|
+
* Algorithm suite identifier. Only one suite exists today; the byte is present so that a future
|
|
11
|
+
* suite (say, AES-256-GCM for FIPS environments) can be added without a format break.
|
|
12
|
+
*/
|
|
13
|
+
export var Suite;
|
|
14
|
+
(function (Suite) {
|
|
15
|
+
Suite[Suite["Argon2idXChaCha20Poly1305"] = 1] = "Argon2idXChaCha20Poly1305";
|
|
16
|
+
})(Suite || (Suite = {}));
|
|
17
|
+
export const NONCE_LENGTH = 24;
|
|
18
|
+
export const TAG_LENGTH = 16;
|
|
19
|
+
export const HEADER_LENGTH = MAGIC.length + 1 + 1 + 4 + 4 + 1 + SALT_LENGTH + NONCE_LENGTH;
|
|
20
|
+
const toBytes = (value) => value === undefined ? new Uint8Array(0) : typeof value === 'string' ? utf8ToBytes(value) : value;
|
|
21
|
+
const writeUint32BE = (view, offset, value) => view.setUint32(offset, value, false);
|
|
22
|
+
const encodeHeader = (header) => {
|
|
23
|
+
const bytes = new Uint8Array(HEADER_LENGTH);
|
|
24
|
+
const view = new DataView(bytes.buffer);
|
|
25
|
+
let offset = 0;
|
|
26
|
+
bytes.set(MAGIC, offset);
|
|
27
|
+
offset += MAGIC.length;
|
|
28
|
+
bytes[offset++] = header.version;
|
|
29
|
+
bytes[offset++] = header.suite;
|
|
30
|
+
writeUint32BE(view, offset, header.kdf.t);
|
|
31
|
+
offset += 4;
|
|
32
|
+
writeUint32BE(view, offset, header.kdf.m);
|
|
33
|
+
offset += 4;
|
|
34
|
+
bytes[offset++] = header.kdf.p;
|
|
35
|
+
bytes.set(header.salt, offset);
|
|
36
|
+
offset += SALT_LENGTH;
|
|
37
|
+
bytes.set(header.nonce, offset);
|
|
38
|
+
return bytes;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Parses (and validates) the envelope header. Throws {@link CorruptEnvelopeError} for anything
|
|
42
|
+
* that is not a `dcrypt` envelope and {@link UnsupportedEnvelopeError} for versions/suites this
|
|
43
|
+
* build cannot open — never a generic error, so callers can give users an accurate message.
|
|
44
|
+
*/
|
|
45
|
+
export const parseHeader = (envelope) => {
|
|
46
|
+
if (envelope.length < HEADER_LENGTH + TAG_LENGTH) {
|
|
47
|
+
throw new CorruptEnvelopeError('envelope is shorter than the minimum header + tag length');
|
|
48
|
+
}
|
|
49
|
+
for (let i = 0; i < MAGIC.length; i++) {
|
|
50
|
+
if (envelope[i] !== MAGIC[i])
|
|
51
|
+
throw new CorruptEnvelopeError('not a dcrypt envelope');
|
|
52
|
+
}
|
|
53
|
+
const view = new DataView(envelope.buffer, envelope.byteOffset, envelope.byteLength);
|
|
54
|
+
const version = envelope[6];
|
|
55
|
+
const suite = envelope[7];
|
|
56
|
+
if (version !== VERSION) {
|
|
57
|
+
throw new UnsupportedEnvelopeError(`unsupported envelope version ${version}; this build understands version ${VERSION}`);
|
|
58
|
+
}
|
|
59
|
+
if (suite !== Suite.Argon2idXChaCha20Poly1305) {
|
|
60
|
+
throw new UnsupportedEnvelopeError(`unsupported algorithm suite ${suite}`);
|
|
61
|
+
}
|
|
62
|
+
const kdf = {
|
|
63
|
+
t: view.getUint32(8, false),
|
|
64
|
+
m: view.getUint32(12, false),
|
|
65
|
+
p: envelope[16],
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
version,
|
|
69
|
+
suite,
|
|
70
|
+
kdf: resolveKdfParams(kdf),
|
|
71
|
+
salt: envelope.slice(17, 17 + SALT_LENGTH),
|
|
72
|
+
nonce: envelope.slice(17 + SALT_LENGTH, HEADER_LENGTH),
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Encrypts `plaintext` under `passphrase`, returning a self-describing envelope:
|
|
77
|
+
* `magic || version || suite || argon2id params || salt || nonce || ciphertext || tag`.
|
|
78
|
+
* The header is authenticated, so cost parameters cannot be downgraded by an attacker.
|
|
79
|
+
*/
|
|
80
|
+
export const encrypt = (plaintext, passphrase, options = {}) => {
|
|
81
|
+
const kdf = resolveKdfParams(options.kdf ?? DEFAULT_KDF_PROFILE);
|
|
82
|
+
const salt = generateSalt();
|
|
83
|
+
const nonce = randomBytes(NONCE_LENGTH);
|
|
84
|
+
const header = encodeHeader({ version: VERSION, suite: Suite.Argon2idXChaCha20Poly1305, kdf, salt, nonce });
|
|
85
|
+
const key = deriveKey(passphrase, salt, kdf);
|
|
86
|
+
try {
|
|
87
|
+
const aad = concatBytes(header, toBytes(options.aad));
|
|
88
|
+
const ciphertext = xchacha20poly1305(key, nonce, aad).encrypt(toBytes(plaintext));
|
|
89
|
+
return concatBytes(header, ciphertext);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
key.fill(0);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
|
|
97
|
+
* {@link WrongPassphraseError} — this format never returns an empty string on failure.
|
|
98
|
+
*/
|
|
99
|
+
export const decrypt = (envelope, passphrase, options = {}) => {
|
|
100
|
+
const header = parseHeader(envelope);
|
|
101
|
+
const key = deriveKey(passphrase, header.salt, header.kdf);
|
|
102
|
+
try {
|
|
103
|
+
const aad = concatBytes(envelope.slice(0, HEADER_LENGTH), toBytes(options.aad));
|
|
104
|
+
return xchacha20poly1305(key, header.nonce, aad).decrypt(envelope.slice(HEADER_LENGTH));
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
throw new WrongPassphraseError();
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
key.fill(0);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
/** Encrypts with an already-derived 32-byte key: `nonce || ciphertext || tag`, no KDF header. */
|
|
114
|
+
export const sealWithKey = (key, plaintext, aad) => {
|
|
115
|
+
assertKey(key);
|
|
116
|
+
const nonce = randomBytes(NONCE_LENGTH);
|
|
117
|
+
return concatBytes(nonce, xchacha20poly1305(key, nonce, toBytes(aad)).encrypt(toBytes(plaintext)));
|
|
118
|
+
};
|
|
119
|
+
/** Inverse of {@link sealWithKey}. */
|
|
120
|
+
export const openWithKey = (key, sealed, aad) => {
|
|
121
|
+
assertKey(key);
|
|
122
|
+
if (sealed.length < NONCE_LENGTH + TAG_LENGTH) {
|
|
123
|
+
throw new CorruptEnvelopeError('sealed payload is too short');
|
|
124
|
+
}
|
|
125
|
+
const nonce = sealed.slice(0, NONCE_LENGTH);
|
|
126
|
+
try {
|
|
127
|
+
return xchacha20poly1305(key, nonce, toBytes(aad)).decrypt(sealed.slice(NONCE_LENGTH));
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
throw new WrongPassphraseError('wrong key, or the sealed payload has been tampered with');
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
const assertKey = (key) => {
|
|
134
|
+
if (key.length !== KEY_LENGTH) {
|
|
135
|
+
throw new InvalidParametersError(`key must be ${KEY_LENGTH} bytes, got ${key.length}`);
|
|
136
|
+
}
|
|
137
|
+
};
|
package/esm/errors.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Base class for every error thrown by `@decryption/core`. */
|
|
2
|
+
export class DecryptionError extends Error {
|
|
3
|
+
constructor(message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = new.target.name;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The envelope is well-formed but the key or passphrase is wrong (or the ciphertext
|
|
10
|
+
* was tampered with). AEAD cannot distinguish the two cases.
|
|
11
|
+
*/
|
|
12
|
+
export class WrongPassphraseError extends DecryptionError {
|
|
13
|
+
constructor(message = 'wrong passphrase, or the ciphertext has been tampered with') {
|
|
14
|
+
super(message);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** The bytes are not a `dcrypt` envelope, or the header is truncated/inconsistent. */
|
|
18
|
+
export class CorruptEnvelopeError extends DecryptionError {
|
|
19
|
+
}
|
|
20
|
+
/** The envelope was produced by a newer format version or an algorithm we do not implement. */
|
|
21
|
+
export class UnsupportedEnvelopeError extends DecryptionError {
|
|
22
|
+
}
|
|
23
|
+
/** Caller passed arguments that cannot produce a secure result. */
|
|
24
|
+
export class InvalidParametersError extends DecryptionError {
|
|
25
|
+
}
|
package/esm/index.js
ADDED
package/esm/kdf.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { argon2id } from '@decryption/hashes/argon2';
|
|
2
|
+
import { randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
|
|
3
|
+
import { InvalidParametersError } from './errors';
|
|
4
|
+
/** Length in bytes of the salt mixed into every passphrase derivation. */
|
|
5
|
+
export const SALT_LENGTH = 16;
|
|
6
|
+
/** Length in bytes of the symmetric key produced by the KDF. */
|
|
7
|
+
export const KEY_LENGTH = 32;
|
|
8
|
+
/**
|
|
9
|
+
* Named cost profiles. Names — not raw numbers — are what callers should pick, so
|
|
10
|
+
* parameters can be raised over time without changing call sites.
|
|
11
|
+
*
|
|
12
|
+
* - `interactive`: ~64 MiB, suitable for a CLI prompt or UI unlock (sub-second on a laptop).
|
|
13
|
+
* - `moderate`: ~256 MiB, the default for files at rest.
|
|
14
|
+
* - `sensitive`: ~1 GiB, for long-lived recovery material such as Shamir shares.
|
|
15
|
+
*/
|
|
16
|
+
export const KDF_PROFILES = {
|
|
17
|
+
interactive: { t: 2, m: 65536, p: 1 },
|
|
18
|
+
moderate: { t: 3, m: 262144, p: 1 },
|
|
19
|
+
sensitive: { t: 4, m: 1048576, p: 1 },
|
|
20
|
+
};
|
|
21
|
+
export const DEFAULT_KDF_PROFILE = 'moderate';
|
|
22
|
+
/**
|
|
23
|
+
* Lower bounds accepted when *reading* an envelope. Anything weaker is rejected rather than
|
|
24
|
+
* silently trusted, so a tampered header cannot downgrade the work factor to nothing.
|
|
25
|
+
*/
|
|
26
|
+
const MIN_PARAMS = { t: 1, m: 8192, p: 1 };
|
|
27
|
+
export const resolveKdfParams = (profile) => {
|
|
28
|
+
const params = typeof profile === 'string' ? KDF_PROFILES[profile] : profile;
|
|
29
|
+
if (!params)
|
|
30
|
+
throw new InvalidParametersError(`unknown kdf profile: ${String(profile)}`);
|
|
31
|
+
assertKdfParams(params);
|
|
32
|
+
return { t: params.t, m: params.m, p: params.p };
|
|
33
|
+
};
|
|
34
|
+
export const assertKdfParams = ({ t, m, p }) => {
|
|
35
|
+
const positiveInt = (n) => Number.isSafeInteger(n) && n > 0;
|
|
36
|
+
if (!positiveInt(t) || !positiveInt(m) || !positiveInt(p)) {
|
|
37
|
+
throw new InvalidParametersError('kdf parameters must be positive integers');
|
|
38
|
+
}
|
|
39
|
+
if (t < MIN_PARAMS.t || m < MIN_PARAMS.m || p < MIN_PARAMS.p) {
|
|
40
|
+
throw new InvalidParametersError(`kdf parameters below the accepted minimum (t>=${MIN_PARAMS.t}, m>=${MIN_PARAMS.m} KiB, p>=${MIN_PARAMS.p})`);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
export const generateSalt = () => randomBytes(SALT_LENGTH);
|
|
44
|
+
/** Derives a 32-byte symmetric key from a passphrase using Argon2id. */
|
|
45
|
+
export const deriveKey = (passphrase, salt, params) => {
|
|
46
|
+
if (salt.length !== SALT_LENGTH) {
|
|
47
|
+
throw new InvalidParametersError(`salt must be ${SALT_LENGTH} bytes, got ${salt.length}`);
|
|
48
|
+
}
|
|
49
|
+
assertKdfParams(params);
|
|
50
|
+
const secret = typeof passphrase === 'string' ? utf8ToBytes(passphrase) : passphrase;
|
|
51
|
+
if (secret.length === 0)
|
|
52
|
+
throw new InvalidParametersError('passphrase must not be empty');
|
|
53
|
+
return argon2id(secret, salt, { ...params, dkLen: KEY_LENGTH });
|
|
54
|
+
};
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./armor"), exports);
|
|
18
|
+
__exportStar(require("./envelope"), exports);
|
|
19
|
+
__exportStar(require("./errors"), exports);
|
|
20
|
+
__exportStar(require("./kdf"), exports);
|
package/kdf.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Length in bytes of the salt mixed into every passphrase derivation. */
|
|
2
|
+
export declare const SALT_LENGTH = 16;
|
|
3
|
+
/** Length in bytes of the symmetric key produced by the KDF. */
|
|
4
|
+
export declare const KEY_LENGTH = 32;
|
|
5
|
+
/** Argon2id cost parameters recorded verbatim in the envelope header. */
|
|
6
|
+
export interface KdfParams {
|
|
7
|
+
/** Time cost — number of passes. */
|
|
8
|
+
t: number;
|
|
9
|
+
/** Memory cost in KiB. */
|
|
10
|
+
m: number;
|
|
11
|
+
/** Parallelism — number of lanes. */
|
|
12
|
+
p: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Named cost profiles. Names — not raw numbers — are what callers should pick, so
|
|
16
|
+
* parameters can be raised over time without changing call sites.
|
|
17
|
+
*
|
|
18
|
+
* - `interactive`: ~64 MiB, suitable for a CLI prompt or UI unlock (sub-second on a laptop).
|
|
19
|
+
* - `moderate`: ~256 MiB, the default for files at rest.
|
|
20
|
+
* - `sensitive`: ~1 GiB, for long-lived recovery material such as Shamir shares.
|
|
21
|
+
*/
|
|
22
|
+
export declare const KDF_PROFILES: {
|
|
23
|
+
readonly interactive: {
|
|
24
|
+
readonly t: 2;
|
|
25
|
+
readonly m: 65536;
|
|
26
|
+
readonly p: 1;
|
|
27
|
+
};
|
|
28
|
+
readonly moderate: {
|
|
29
|
+
readonly t: 3;
|
|
30
|
+
readonly m: 262144;
|
|
31
|
+
readonly p: 1;
|
|
32
|
+
};
|
|
33
|
+
readonly sensitive: {
|
|
34
|
+
readonly t: 4;
|
|
35
|
+
readonly m: 1048576;
|
|
36
|
+
readonly p: 1;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
export type KdfProfile = keyof typeof KDF_PROFILES;
|
|
40
|
+
export declare const DEFAULT_KDF_PROFILE: KdfProfile;
|
|
41
|
+
export declare const resolveKdfParams: (profile: KdfProfile | KdfParams) => KdfParams;
|
|
42
|
+
export declare const assertKdfParams: ({ t, m, p }: KdfParams) => void;
|
|
43
|
+
export declare const generateSalt: () => Uint8Array;
|
|
44
|
+
/** Derives a 32-byte symmetric key from a passphrase using Argon2id. */
|
|
45
|
+
export declare const deriveKey: (passphrase: string | Uint8Array, salt: Uint8Array, params: KdfParams) => Uint8Array;
|
package/kdf.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.deriveKey = exports.generateSalt = exports.assertKdfParams = exports.resolveKdfParams = exports.DEFAULT_KDF_PROFILE = exports.KDF_PROFILES = exports.KEY_LENGTH = exports.SALT_LENGTH = void 0;
|
|
4
|
+
const argon2_1 = require("@decryption/hashes/argon2");
|
|
5
|
+
const utils_1 = require("@decryption/hashes/utils");
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
/** Length in bytes of the salt mixed into every passphrase derivation. */
|
|
8
|
+
exports.SALT_LENGTH = 16;
|
|
9
|
+
/** Length in bytes of the symmetric key produced by the KDF. */
|
|
10
|
+
exports.KEY_LENGTH = 32;
|
|
11
|
+
/**
|
|
12
|
+
* Named cost profiles. Names — not raw numbers — are what callers should pick, so
|
|
13
|
+
* parameters can be raised over time without changing call sites.
|
|
14
|
+
*
|
|
15
|
+
* - `interactive`: ~64 MiB, suitable for a CLI prompt or UI unlock (sub-second on a laptop).
|
|
16
|
+
* - `moderate`: ~256 MiB, the default for files at rest.
|
|
17
|
+
* - `sensitive`: ~1 GiB, for long-lived recovery material such as Shamir shares.
|
|
18
|
+
*/
|
|
19
|
+
exports.KDF_PROFILES = {
|
|
20
|
+
interactive: { t: 2, m: 65536, p: 1 },
|
|
21
|
+
moderate: { t: 3, m: 262144, p: 1 },
|
|
22
|
+
sensitive: { t: 4, m: 1048576, p: 1 },
|
|
23
|
+
};
|
|
24
|
+
exports.DEFAULT_KDF_PROFILE = 'moderate';
|
|
25
|
+
/**
|
|
26
|
+
* Lower bounds accepted when *reading* an envelope. Anything weaker is rejected rather than
|
|
27
|
+
* silently trusted, so a tampered header cannot downgrade the work factor to nothing.
|
|
28
|
+
*/
|
|
29
|
+
const MIN_PARAMS = { t: 1, m: 8192, p: 1 };
|
|
30
|
+
const resolveKdfParams = (profile) => {
|
|
31
|
+
const params = typeof profile === 'string' ? exports.KDF_PROFILES[profile] : profile;
|
|
32
|
+
if (!params)
|
|
33
|
+
throw new errors_1.InvalidParametersError(`unknown kdf profile: ${String(profile)}`);
|
|
34
|
+
(0, exports.assertKdfParams)(params);
|
|
35
|
+
return { t: params.t, m: params.m, p: params.p };
|
|
36
|
+
};
|
|
37
|
+
exports.resolveKdfParams = resolveKdfParams;
|
|
38
|
+
const assertKdfParams = ({ t, m, p }) => {
|
|
39
|
+
const positiveInt = (n) => Number.isSafeInteger(n) && n > 0;
|
|
40
|
+
if (!positiveInt(t) || !positiveInt(m) || !positiveInt(p)) {
|
|
41
|
+
throw new errors_1.InvalidParametersError('kdf parameters must be positive integers');
|
|
42
|
+
}
|
|
43
|
+
if (t < MIN_PARAMS.t || m < MIN_PARAMS.m || p < MIN_PARAMS.p) {
|
|
44
|
+
throw new errors_1.InvalidParametersError(`kdf parameters below the accepted minimum (t>=${MIN_PARAMS.t}, m>=${MIN_PARAMS.m} KiB, p>=${MIN_PARAMS.p})`);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
exports.assertKdfParams = assertKdfParams;
|
|
48
|
+
const generateSalt = () => (0, utils_1.randomBytes)(exports.SALT_LENGTH);
|
|
49
|
+
exports.generateSalt = generateSalt;
|
|
50
|
+
/** Derives a 32-byte symmetric key from a passphrase using Argon2id. */
|
|
51
|
+
const deriveKey = (passphrase, salt, params) => {
|
|
52
|
+
if (salt.length !== exports.SALT_LENGTH) {
|
|
53
|
+
throw new errors_1.InvalidParametersError(`salt must be ${exports.SALT_LENGTH} bytes, got ${salt.length}`);
|
|
54
|
+
}
|
|
55
|
+
(0, exports.assertKdfParams)(params);
|
|
56
|
+
const secret = typeof passphrase === 'string' ? (0, utils_1.utf8ToBytes)(passphrase) : passphrase;
|
|
57
|
+
if (secret.length === 0)
|
|
58
|
+
throw new errors_1.InvalidParametersError('passphrase must not be empty');
|
|
59
|
+
return (0, argon2_1.argon2id)(secret, salt, { ...params, dkLen: exports.KEY_LENGTH });
|
|
60
|
+
};
|
|
61
|
+
exports.deriveKey = deriveKey;
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@decryption/core",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Versioned authenticated envelope encryption: Argon2id + XChaCha20-Poly1305",
|
|
5
|
+
"author": "Constructive <developers@constructive.io>",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/decryption",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/decryption"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/decryption/issues"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"copy": "makage assets",
|
|
24
|
+
"clean": "makage clean",
|
|
25
|
+
"prepublishOnly": "npm run build",
|
|
26
|
+
"build": "makage build",
|
|
27
|
+
"lint": "eslint . --fix",
|
|
28
|
+
"test": "jest",
|
|
29
|
+
"test:watch": "jest --watch"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"encryption",
|
|
33
|
+
"argon2",
|
|
34
|
+
"xchacha20",
|
|
35
|
+
"aead",
|
|
36
|
+
"envelope"
|
|
37
|
+
],
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@decryption/base": "0.2.0",
|
|
40
|
+
"@decryption/ciphers": "0.2.0",
|
|
41
|
+
"@decryption/hashes": "0.2.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"makage": "0.3.0"
|
|
45
|
+
},
|
|
46
|
+
"gitHead": "8d85fbfdbb1d57da93e99904a03e6e8d8531d281"
|
|
47
|
+
}
|