Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions encryption/encrypt-node/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# @keyv/encrypt-node [<img width="100" align="right" src="https://jaredwray.com/images/keyv-symbol.svg" alt="keyv">](https://github.com/jaredwray/keyv)

> Node.js crypto encryption for Keyv

[![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml)
[![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv)
[![npm](https://img.shields.io/npm/v/@keyv/encrypt-node.svg)](https://www.npmjs.com/package/@keyv/encrypt-node)
[![npm](https://img.shields.io/npm/dm/@keyv/encrypt-node)](https://npmjs.com/package/@keyv/encrypt-node)

Encrypt and decrypt values stored in [Keyv](https://github.com/jaredwray/keyv) using the Node.js `crypto` module. Supports AES-GCM (default), AES-CCM, ChaCha20-Poly1305, AES-CBC, and any cipher available in your Node.js installation.

## Install

```shell
npm install --save keyv @keyv/encrypt-node
```

## Usage

```javascript
import Keyv from 'keyv';
import KeyvEncryptNode from '@keyv/encrypt-node';

const encryption = new KeyvEncryptNode({ key: 'your-secret-key' });
const keyv = new Keyv({ encryption });

await keyv.set('foo', 'bar');
const value = await keyv.get('foo'); // 'bar' (decrypted automatically)
```

## API

### new KeyvEncryptNode(options)

#### options.key

Type: `string | Buffer`\
**Required**

The encryption key. String keys are hashed with SHA-256 and truncated to the required length for the algorithm. Buffer keys are used directly and must match the expected key length.

#### options.algorithm

Type: `string`\
Default: `'aes-256-gcm'`

The cipher algorithm to use. Supports any algorithm available via Node.js `crypto.getCipherInfo()`, including:

- `aes-256-gcm`, `aes-192-gcm`, `aes-128-gcm` (AEAD)
- `aes-256-ccm`, `aes-192-ccm`, `aes-128-ccm` (AEAD)
- `chacha20-poly1305` (AEAD)
- `aes-256-cbc`, `aes-192-cbc`, `aes-128-cbc`

#### options.encoding

Type: `BufferEncoding`\
Default: `'base64'`

The encoding used for the encrypted output string. Common options: `'base64'`, `'hex'`.

## Cross-Compatibility

Data encrypted with `@keyv/encrypt-node` using AES-GCM or AES-CBC can be decrypted by `@keyv/encrypt-web` (and vice versa) when using the same key and algorithm. Both packages use the same wire format:

- **AES-GCM**: `base64([IV (12 bytes) || AuthTag (16 bytes) || Ciphertext])`
- **AES-CBC**: `base64([IV (16 bytes) || Ciphertext])`

## License

[MIT © Jared Wray](LICENSE)
48 changes: 45 additions & 3 deletions encryption/encrypt-node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,39 @@ const CCM_MODES = new Set(["ccm"]);

const AUTH_TAG_LENGTH = 16;

/**
* Options for {@link KeyvEncryptNode}.
*/
export type KeyvEncryptNodeOptions = {
/** Encryption key. Strings are hashed with SHA-256 to derive a 32-byte key. Buffers are used directly. */
/** Encryption key. Strings are hashed with SHA-256 and truncated to the required length. Buffers are used directly and must match the algorithm's key length. */
key: string | Buffer;
/** Cipher algorithm to use. Default: "aes-256-gcm". */
/** Cipher algorithm to use. Any algorithm supported by Node.js `crypto.getCipherInfo()`. @defaultValue `"aes-256-gcm"` */
algorithm?: string;
/** Output encoding for the encrypted string. Default: "base64". */
/** Output encoding for the encrypted string. @defaultValue `"base64"` */
encoding?: BufferEncoding;
};

/**
* Node.js `crypto`-based encryption adapter for Keyv.
*
* Encrypts and decrypts string values using any cipher supported by the
* Node.js `crypto` module. Defaults to AES-256-GCM with authenticated
* encryption. The encrypted output is a base64 string containing the IV,
* authentication tag (for AEAD ciphers), and ciphertext.
*
* Wire format (AEAD): `[IV || AuthTag (16 bytes) || Ciphertext]`
* Wire format (non-AEAD): `[IV || Ciphertext]`
*
* @example
* ```ts
* import Keyv from "keyv";
* import KeyvEncryptNode from "@keyv/encrypt-node";
*
* const encryption = new KeyvEncryptNode({ key: "my-secret" });
* const keyv = new Keyv({ encryption });
* await keyv.set("foo", "bar");
* ```
*/
export class KeyvEncryptNode implements KeyvEncryptionAdapter {
private readonly _key: Buffer;
private readonly _algorithm: string;
Expand All @@ -31,6 +55,12 @@ export class KeyvEncryptNode implements KeyvEncryptionAdapter {
private readonly _isAead: boolean;
private readonly _isCcm: boolean;

/**
* Creates a new encryption adapter.
* @param options - Configuration options including key, algorithm, and encoding.
* @throws If the algorithm is not supported by Node.js crypto.
* @throws If a Buffer key does not match the expected length for the algorithm.
*/
constructor(options: KeyvEncryptNodeOptions) {
this._algorithm = (options.algorithm ?? "aes-256-gcm").toLowerCase();
this._encoding = options.encoding ?? "base64";
Expand All @@ -57,6 +87,11 @@ export class KeyvEncryptNode implements KeyvEncryptionAdapter {
}
}

/**
* Encrypts a plaintext string.
* @param data - The plaintext string to encrypt.
* @returns The encrypted string encoded with the configured encoding.
*/
encrypt(data: string): string {
const iv = randomBytes(this._ivLength);
const cipherOptions = this._isCcm
Expand All @@ -81,6 +116,13 @@ export class KeyvEncryptNode implements KeyvEncryptionAdapter {
return packed.toString(this._encoding);
}

/**
* Decrypts an encrypted string back to its original plaintext.
* @param data - The encrypted string to decrypt.
* @returns The original plaintext string.
* @throws If the ciphertext has been tampered with (AEAD modes).
* @throws If the wrong key is used for decryption.
*/
decrypt(data: string): string {
const packed = Buffer.from(data, this._encoding);

Expand Down
21 changes: 21 additions & 0 deletions encryption/encrypt-web/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021-2026 Jared Wray

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
61 changes: 61 additions & 0 deletions encryption/encrypt-web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# @keyv/encrypt-web [<img width="100" align="right" src="https://jaredwray.com/images/keyv-symbol.svg" alt="keyv">](https://github.com/jaredwray/keyv)

> Web Crypto API encryption for Keyv

[![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml)
[![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv)
[![npm](https://img.shields.io/npm/v/@keyv/encrypt-web.svg)](https://www.npmjs.com/package/@keyv/encrypt-web)
[![npm](https://img.shields.io/npm/dm/@keyv/encrypt-web)](https://npmjs.com/package/@keyv/encrypt-web)

Encrypt and decrypt values stored in [Keyv](https://github.com/jaredwray/keyv) using the Web Crypto API (`crypto.subtle`). Works in browsers, Deno, Cloudflare Workers, and Node.js 18+. No Node.js-specific dependencies.

## Install

```shell
npm install --save keyv @keyv/encrypt-web
```

## Usage

```javascript
import Keyv from 'keyv';
import KeyvEncryptWeb from '@keyv/encrypt-web';

const encryption = new KeyvEncryptWeb({ key: 'your-secret-key' });
const keyv = new Keyv({ encryption });

await keyv.set('foo', 'bar');
const value = await keyv.get('foo'); // 'bar' (decrypted automatically)
```

## API

### new KeyvEncryptWeb(options)

#### options.key

Type: `string | Uint8Array`\
**Required**

The encryption key. String keys are hashed with SHA-256 and truncated to the required length for the algorithm. Uint8Array keys are used directly and must match the expected key length.

#### options.algorithm

Type: `WebAlgorithm`\
Default: `'aes-256-gcm'`

The cipher algorithm to use. Supported values:

- `aes-256-gcm`, `aes-192-gcm`, `aes-128-gcm` (AEAD, recommended)
- `aes-256-cbc`, `aes-192-cbc`, `aes-128-cbc`

## Cross-Compatibility

Data encrypted with `@keyv/encrypt-web` using AES-GCM or AES-CBC can be decrypted by `@keyv/encrypt-node` (and vice versa) when using the same key and algorithm. Both packages use the same wire format:

- **AES-GCM**: `base64([IV (12 bytes) || AuthTag (16 bytes) || Ciphertext])`
- **AES-CBC**: `base64([IV (16 bytes) || Ciphertext])`

## License

[MIT © Jared Wray](LICENSE)
73 changes: 73 additions & 0 deletions encryption/encrypt-web/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"name": "@keyv/encrypt-web",
"version": "6.0.0-alpha.4",
"description": "Web Crypto API encryption adapter for Keyv",
"type": "module",
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": {
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
}
},
"scripts": {
"build": "tsdown",
"prepublishOnly": "pnpm build",
"lint": "biome check --write --error-on-warnings",
"lint:ci": "biome check --error-on-warnings",
"test": "pnpm lint && vitest run --coverage",
"test:ci": "pnpm lint:ci && vitest --run --sequence.setupFiles=list --coverage",
"clean": "rimraf ./node_modules ./coverage ./dist"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jaredwray/keyv.git"
},
"keywords": [
"encryption",
"web-crypto",
"webcrypto",
"browser",
"keyv",
"storage",
"adapter",
"key",
"value",
"store",
"cache",
"aes",
"gcm"
],
"author": "Jared Wray <me@jaredwray.com> (https://jaredwray.com)",
"license": "MIT",
"bugs": {
"url": "https://github.com/jaredwray/keyv/issues"
},
"homepage": "https://github.com/jaredwray/keyv",
"dependencies": {},
"peerDependencies": {
"keyv": "workspace:^"
},
"devDependencies": {
"@biomejs/biome": "^2.3.13",
"@faker-js/faker": "^9.8.0",
"@vitest/coverage-v8": "^4.0.18",
"rimraf": "^6.1.2",
"vitest": "^4.0.18"
},
"engines": {
"node": ">= 18"
},
"files": [
"dist",
"LICENSE"
]
}
Loading
Loading