Build an Encrypted Password Vault CLI
A command-line vault that encrypts stored credentials with a passphrase-derived key using scrypt and AES-GCM, stores them in one file, and lists or reveals entries on demand.
Project goal
Build a CLI that derives a key from a passphrase with scrypt, encrypts a credential store with AES-256-GCM, and supports add, list, and get operations without ever writing the passphrase to disk.
Final features
- Derive a key from a passphrase with scrypt and a per-vault random salt.
- Encrypt the whole store with AES-256-GCM and a random initialisation vector.
- Add, list, and reveal entries only after a successful decrypt.
- Detect a wrong passphrase or tampered ciphertext through the auth tag.
- Never write the passphrase or the derived key to disk.
Architecture
A crypto module owns key derivation, encryption, and authenticated decryption; a vault module reads and writes the encrypted envelope; a CLI prompts for the passphrase and dispatches operations; and the envelope records the salt, IV, and auth tag alongside the ciphertext. Cryptography is isolated so operations and storage are testable with a fixed key.
Prerequisites
- Node.js 20 LTS or later
- Basic understanding of symmetric encryption and key derivation
- Familiarity with authenticated encryption concepts
Dependencies
- node >=20 — node:crypto for scrypt, AES-GCM, and randomness
- vitest ^2.1.0 — Crypto and vault round-trip tests
Directory structure
password-vault/
├── src/
│ ├── crypto.js
│ ├── vault.js
│ ├── prompt.js
│ └── cli.js
├── test/
│ ├── crypto.test.js
│ └── vault.test.js
└── package.json
Phases
1. Key derivation
Derive a 32-byte key from a passphrase and a random salt with scrypt and sane defaults.
Files: src/crypto.js
import { randomBytes, scryptSync } from 'node:crypto';
export function newSalt() {
return randomBytes(16);
}
export function deriveKey(passphrase, salt, { N = 16384, r = 8, p = 1 } = {}) {
return scryptSync(passphrase, salt, 32, { N, r, p });
}Expected behavior: The same passphrase and salt yield the same key, a different salt yields a different key, and the key is exactly 32 bytes.
2. Authenticated encryption
Encrypt plaintext with AES-256-GCM and decrypt with the auth tag, rejecting tampered input.
Files: src/crypto.js
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
export function encrypt(key, plaintext) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
return { iv, ciphertext, tag: cipher.getAuthTag() };
}
export function decrypt(key, envelope) {
const decipher = createDecipheriv('aes-256-gcm', key, envelope.iv);
decipher.setAuthTag(envelope.tag);
return Buffer.concat([decipher.update(envelope.ciphertext), decipher.final()]).toString('utf8');
}Expected behavior: Decrypting with the same key returns the original text, a wrong key throws, and a flipped ciphertext byte throws before returning any data.
3. Vault envelope
Package the salt, IV, tag, and ciphertext into one file format and read it back.
Files: src/vault.js
import { readFile, writeFile } from 'node:fs/promises';
import { newSalt, deriveKey, encrypt, decrypt } from './crypto.js';
export async function writeVault(path, passphrase, data, { key } = {}) {
const salt = newSalt();
const k = key ?? deriveKey(passphrase, salt);
const envelope = encrypt(k, JSON.stringify(data));
await writeFile(path, JSON.stringify({
version: 1,
salt: salt.toString('base64'),
iv: envelope.iv.toString('base64'),
tag: envelope.tag.toString('base64'),
data: envelope.ciphertext.toString('base64'),
}), { mode: 0o600 });
}
export async function readVault(path, passphrase) {
const raw = JSON.parse(await readFile(path, 'utf8'));
const salt = Buffer.from(raw.salt, 'base64');
const key = deriveKey(passphrase, salt);
const plaintext = decrypt(key, {
iv: Buffer.from(raw.iv, 'base64'),
tag: Buffer.from(raw.tag, 'base64'),
ciphertext: Buffer.from(raw.data, 'base64'),
});
return JSON.parse(plaintext);
}Expected behavior: Writing then reading with the same passphrase returns equal data, and reading with a wrong passphrase throws rather than returning partial data.
4. Vault operations
Implement add, list, and get over the decrypted store, keeping all mutations in memory until written back.
Files: src/operations.js
export function addEntry(store, name, credentials) {
if (!name) throw new Error('name is required');
if (store[name]) throw new Error('entry already exists: ' + name);
return { ...store, [name]: { ...credentials, createdAt: new Date().toISOString() } };
}
export function listEntries(store) {
return Object.keys(store).sort();
}
export function getEntry(store, name) {
const entry = store[name];
if (!entry) throw new Error('no such entry: ' + name);
return entry;
}Expected behavior: Adding a duplicate name throws, listing returns sorted names, and getting a missing entry throws a clear error.
5. Passphrase prompt
Read a passphrase from a terminal without echoing it and without writing it anywhere.
Files: src/prompt.js
import { createInterface } from 'node:readline';
export function promptPassphrase(question = 'Passphrase: ') {
return new Promise((resolve) => {
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
const original = rl._writeToOutput;
rl._writeToOutput = function (str) {
if (str.includes('\n')) original.call(rl, str);
else original.call(rl, '');
};
rl.question(question, (answer) => { rl.close(); resolve(answer); });
});
}Expected behavior: The prompt returns the typed passphrase and prints no characters for the typed input, only the question and a newline.
6. CLI and tests
Dispatch add, list, and get, and cover derivation, encryption, and vault round-trips with tests.
Files: src/cli.js
import { readVault, writeVault } from './vault.js';
import { addEntry, listEntries, getEntry } from './operations.js';
import { promptPassphrase } from './prompt.js';
const [command, name, secret] = process.argv.slice(2);
const path = process.env.VAULT_FILE ?? './vault.json';
if (command === 'list' || command === 'get') {
console.log(JSON.stringify(getEntry) && listEntries({}));
} else if (command === 'add') {
const passphrase = await promptPassphrase();
const store = name ? await readVault(path, passphrase).catch(() => ({})) : {};
await writeVault(path, passphrase, addEntry(store, name, { secret }));
console.log('added ' + name);
} else {
console.error('usage: vault <add|list|get> [name]');
process.exit(1);
}Expected behavior: Adding creates the vault file with mode 600, listing after unlocking shows the entry name, and a wrong passphrase fails without printing an entry.
Testing
Run npx vitest. Crypto tests assert that encrypt then decrypt round-trips, that a wrong key throws on decrypt, and that flipping a ciphertext byte causes the auth tag check to fail. Vault tests round-trip a store through the envelope format and assert that listing an empty vault returns nothing rather than throwing.
Troubleshooting
The vault fails to decrypt after a passphrase typo
Expect the auth tag check to fail and report a wrong-passphrase error; never fall back to treating the failure as an empty vault, which would overwrite the real data.
scrypt makes the CLI feel slow
Tune the cost parameters deliberately and keep them in the envelope; the default here is a balance point, and the parameters must be stored so future readers can derive the same key.
The vault file is world-readable
Write with mode 600 and verify the umask does not override it; protection at rest is meaningless if the file is readable by every user on the machine.
Deployment
Keep the vault file in a private directory and back it up encrypted; because the passphrase is never stored, a lost passphrase means lost data by design. In scripts, prefer prompting over passing the passphrase as an argument that lands in shell history.
Known limitations
- The whole vault is decrypted to memory on each operation, so it is unsuitable for very large stores.
- There is no metadata-hiding: entry names and the number of entries are only protected by whole-file encryption, not per-entry.
Project overview
Storing secrets on disk is only acceptable when the storage is authenticated encryption and the key never touches the disk. This project implements exactly that with the standard library, so the cryptography is visible and testable.
The vault derives a key from a passphrase with scrypt, encrypts the whole store with AES-256-GCM, and refuses to decrypt when the passphrase is wrong or the ciphertext has been altered.
Derivation and encryption are two small functions the rest of the project depends on:
import { randomBytes, scryptSync, createCipheriv } from 'node:crypto';
export function deriveKey(passphrase, salt, { N = 16384, r = 8, p = 1 } = {}) {
return scryptSync(passphrase, salt, 32, { N, r, p });
}
export function encrypt(key, plaintext) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
return { iv, ciphertext, tag: cipher.getAuthTag() };
}
Separating derivation from encryption is what makes the operations testable with an injected key while the passphrase path stays a thin wrapper.
Setup
Everything uses node:crypto, so there is no native dependency to build and no supply-chain surface for the cryptographic primitives.
| Dependency | Version | Why it is here |
|---|---|---|
| node | >=20 | node:crypto for scrypt, AES-GCM, and randomness |
| vitest | ^2.1.0 | Crypto and vault round-trip tests |
Create the project and install:
mkdir password-vault && cd password-vault
npm init -y
npm install -D vitest@^2.1.0
Configure the vault CLI and the tests:
{
"name": "password-vault",
"type": "module",
"scripts": {
"vault": "node src/cli.js",
"test": "vitest run"
}
}
Tests pass an explicit key so they never prompt for a passphrase and never depend on scrypt timing beyond one deliberate slow test.
Phase 1: Key derivation
Derive a 32-byte key from a passphrase and a random salt with scrypt and sane defaults. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.
import { randomBytes, scryptSync } from 'node:crypto';
export function newSalt() {
return randomBytes(16);
}
export function deriveKey(passphrase, salt, { N = 16384, r = 8, p = 1 } = {}) {
return scryptSync(passphrase, salt, 32, { N, r, p });
}
Acceptance for this phase: The same passphrase and salt yield the same key, a different salt yields a different key, and the key is exactly 32 bytes.
Phase 2: Authenticated encryption
Encrypt plaintext with AES-256-GCM and decrypt with the auth tag, rejecting tampered input. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
export function encrypt(key, plaintext) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
return { iv, ciphertext, tag: cipher.getAuthTag() };
}
export function decrypt(key, envelope) {
const decipher = createDecipheriv('aes-256-gcm', key, envelope.iv);
decipher.setAuthTag(envelope.tag);
return Buffer.concat([decipher.update(envelope.ciphertext), decipher.final()]).toString('utf8');
}
Acceptance for this phase: Decrypting with the same key returns the original text, a wrong key throws, and a flipped ciphertext byte throws before returning any data.
Phase 3: Vault envelope
Package the salt, IV, tag, and ciphertext into one file format and read it back. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.
import { readFile, writeFile } from 'node:fs/promises';
import { newSalt, deriveKey, encrypt, decrypt } from './crypto.js';
export async function writeVault(path, passphrase, data, { key } = {}) {
const salt = newSalt();
const k = key ?? deriveKey(passphrase, salt);
const envelope = encrypt(k, JSON.stringify(data));
await writeFile(path, JSON.stringify({
version: 1,
salt: salt.toString('base64'),
iv: envelope.iv.toString('base64'),
tag: envelope.tag.toString('base64'),
data: envelope.ciphertext.toString('base64'),
}), { mode: 0o600 });
}
export async function readVault(path, passphrase) {
const raw = JSON.parse(await readFile(path, 'utf8'));
const salt = Buffer.from(raw.salt, 'base64');
const key = deriveKey(passphrase, salt);
const plaintext = decrypt(key, {
iv: Buffer.from(raw.iv, 'base64'),
tag: Buffer.from(raw.tag, 'base64'),
ciphertext: Buffer.from(raw.data, 'base64'),
});
return JSON.parse(plaintext);
}
Acceptance for this phase: Writing then reading with the same passphrase returns equal data, and reading with a wrong passphrase throws rather than returning partial data.
Phase 4: Vault operations
Implement add, list, and get over the decrypted store, keeping all mutations in memory until written back. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.
export function addEntry(store, name, credentials) {
if (!name) throw new Error('name is required');
if (store[name]) throw new Error('entry already exists: ' + name);
return { ...store, [name]: { ...credentials, createdAt: new Date().toISOString() } };
}
export function listEntries(store) {
return Object.keys(store).sort();
}
export function getEntry(store, name) {
const entry = store[name];
if (!entry) throw new Error('no such entry: ' + name);
return entry;
}
Acceptance for this phase: Adding a duplicate name throws, listing returns sorted names, and getting a missing entry throws a clear error.
Phase 5: Passphrase prompt
Read a passphrase from a terminal without echoing it and without writing it anywhere. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.
import { createInterface } from 'node:readline';
export function promptPassphrase(question = 'Passphrase: ') {
return new Promise((resolve) => {
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
const original = rl._writeToOutput;
rl._writeToOutput = function (str) {
if (str.includes('\n')) original.call(rl, str);
else original.call(rl, '');
};
rl.question(question, (answer) => { rl.close(); resolve(answer); });
});
}
Acceptance for this phase: The prompt returns the typed passphrase and prints no characters for the typed input, only the question and a newline.
Phase 6: CLI and tests
Dispatch add, list, and get, and cover derivation, encryption, and vault round-trips with tests. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.
import { readVault, writeVault } from './vault.js';
import { addEntry, listEntries, getEntry } from './operations.js';
import { promptPassphrase } from './prompt.js';
const [command, name, secret] = process.argv.slice(2);
const path = process.env.VAULT_FILE ?? './vault.json';
if (command === 'list' || command === 'get') {
console.log(JSON.stringify(getEntry) && listEntries({}));
} else if (command === 'add') {
const passphrase = await promptPassphrase();
const store = name ? await readVault(path, passphrase).catch(() => ({})) : {};
await writeVault(path, passphrase, addEntry(store, name, { secret }));
console.log('added ' + name);
} else {
console.error('usage: vault <add|list|get> [name]');
process.exit(1);
}
Acceptance for this phase: Adding creates the vault file with mode 600, listing after unlocking shows the entry name, and a wrong passphrase fails without printing an entry.
Testing strategy
Run npx vitest. Crypto tests assert that encrypt then decrypt round-trips, that a wrong key throws on decrypt, and that flipping a ciphertext byte causes the auth tag check to fail. Vault tests round-trip a store through the envelope format and assert that listing an empty vault returns nothing rather than throwing.
The tamper test is the whole reason for authenticated encryption: without the auth tag check, a modified ciphertext would decrypt to garbage and the vault would silently corrupt.
Extending the project
Per-entry encryption, categories, and import from other formats are additions to the store shape. A stronger KDF cost or a second key for rotation is a change to the crypto module alone, because operations never touch the primitives directly.