Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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)
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"
]
}
162 changes: 162 additions & 0 deletions encryption/encrypt-web/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import type { KeyvEncryptionAdapter } from "keyv";

const AUTH_TAG_LENGTH = 16;

export type WebAlgorithm =
| "aes-128-gcm"
| "aes-192-gcm"
| "aes-256-gcm"
| "aes-128-cbc"
| "aes-192-cbc"
| "aes-256-cbc";

export type KeyvEncryptWebOptions = {
/** Encryption key. Strings are hashed with SHA-256 to derive the required key length. Uint8Array used directly. */
key: string | Uint8Array;
/** Algorithm. Default: "aes-256-gcm". */
algorithm?: WebAlgorithm;
};

type AlgorithmConfig = {
webCryptoName: "AES-GCM" | "AES-CBC";
keyLength: number;
ivLength: number;
isAead: boolean;
};

const ALGORITHM_MAP: Record<WebAlgorithm, AlgorithmConfig> = {
"aes-128-gcm": { webCryptoName: "AES-GCM", keyLength: 16, ivLength: 12, isAead: true },
"aes-192-gcm": { webCryptoName: "AES-GCM", keyLength: 24, ivLength: 12, isAead: true },
"aes-256-gcm": { webCryptoName: "AES-GCM", keyLength: 32, ivLength: 12, isAead: true },
"aes-128-cbc": { webCryptoName: "AES-CBC", keyLength: 16, ivLength: 16, isAead: false },
"aes-192-cbc": { webCryptoName: "AES-CBC", keyLength: 24, ivLength: 16, isAead: false },
"aes-256-cbc": { webCryptoName: "AES-CBC", keyLength: 32, ivLength: 16, isAead: false },
};

function uint8ArrayToBase64(bytes: Uint8Array): string {
let binary = "";
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}

return btoa(binary);
}

function base64ToUint8Array(base64: string): Uint8Array {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}

return bytes;
}

function concat(...arrays: Uint8Array[]): Uint8Array {
let totalLength = 0;
for (const array of arrays) {
totalLength += array.length;
}

const result = new Uint8Array(totalLength);
let offset = 0;
for (const array of arrays) {
result.set(array, offset);
offset += array.length;
}

return result;
}

export class KeyvEncryptWeb implements KeyvEncryptionAdapter {
private readonly _config: AlgorithmConfig;
private readonly _keyPromise: Promise<CryptoKey>;

constructor(options: KeyvEncryptWebOptions) {
const algorithm = (options.algorithm ?? "aes-256-gcm").toLowerCase() as WebAlgorithm;
const config = ALGORITHM_MAP[algorithm];
if (!config) {
throw new Error(`Unsupported cipher algorithm: ${algorithm}`);
}

this._config = config;

if (options.key instanceof Uint8Array) {
if (options.key.length !== config.keyLength) {
throw new Error(`Key must be ${config.keyLength} bytes for ${algorithm}`);
}

this._keyPromise = crypto.subtle.importKey(
"raw",
options.key,
{ name: config.webCryptoName },
false,
["encrypt", "decrypt"],
);
} else {
const encoded = new TextEncoder().encode(options.key);
this._keyPromise = crypto.subtle.digest("SHA-256", encoded).then((hash) => {
const keyBytes = new Uint8Array(hash).slice(0, config.keyLength);
return crypto.subtle.importKey("raw", keyBytes, { name: config.webCryptoName }, false, [
"encrypt",
"decrypt",
]);
});
}
}

async encrypt(data: string): Promise<string> {
const cryptoKey = await this._keyPromise;
const iv = crypto.getRandomValues(new Uint8Array(this._config.ivLength));
const encoded = new TextEncoder().encode(data);

if (this._config.isAead) {
const ciphertext = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv, tagLength: AUTH_TAG_LENGTH * 8 },
cryptoKey,
encoded,
);

// Web Crypto returns [ciphertext || authTag], rearrange to [IV || authTag || ciphertext]
const combined = new Uint8Array(ciphertext);
const actualCiphertext = combined.slice(0, combined.length - AUTH_TAG_LENGTH);
const authTag = combined.slice(combined.length - AUTH_TAG_LENGTH);
const packed = concat(iv, authTag, actualCiphertext);
return uint8ArrayToBase64(packed);
}

const ciphertext = await crypto.subtle.encrypt({ name: "AES-CBC", iv }, cryptoKey, encoded);

const packed = concat(iv, new Uint8Array(ciphertext));
return uint8ArrayToBase64(packed);
}

async decrypt(data: string): Promise<string> {
const cryptoKey = await this._keyPromise;
const packed = base64ToUint8Array(data);

if (this._config.isAead) {
const iv = packed.slice(0, this._config.ivLength);
const authTag = packed.slice(this._config.ivLength, this._config.ivLength + AUTH_TAG_LENGTH);
const ciphertext = packed.slice(this._config.ivLength + AUTH_TAG_LENGTH);

// Reassemble for Web Crypto: [ciphertext || authTag]
const webCombined = concat(ciphertext, authTag);
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv, tagLength: AUTH_TAG_LENGTH * 8 },
cryptoKey,
webCombined,
);

return new TextDecoder().decode(decrypted);
}

const iv = packed.slice(0, this._config.ivLength);
const ciphertext = packed.slice(this._config.ivLength);
const decrypted = await crypto.subtle.decrypt({ name: "AES-CBC", iv }, cryptoKey, ciphertext);

return new TextDecoder().decode(decrypted);
}
}

export default KeyvEncryptWeb;
Loading
Loading