pglite-cipher: SQLCipher-style encryption for Postgres in the browser

Built a sqlcipher like but for postgres wasm for my journal app, was planning to keep it closed but decided otherwise. Almost on parity with sqlcipher with few inmemory exceptions


I built Journal, a local-first notebook. Your notes live in a database on your device, Journal works offline, and it syncs your notes, encrypted, to your own Homebase identity: your own private space for your data, under your own identity rather than a company's account. The tagline on the brand page says "Your notes stay home."

The database on your device is PGlite: real Postgres 18, compiled to WebAssembly by the ElectricSQL folks, running in a Web Worker. Journal ships as a web app and as Tauri apps for macOS, Windows, Linux, iOS and Android. Every one of those is the same web app inside the system webview, which means on every platform the notes end up in the same place: the webview's IndexedDB.

I'd spent a lot of time on the sync half of that promise: notes leave the device encrypted and Homebase stores them encrypted. Then I opened DevTools, went to IndexedDB, and searched the stored bytes for a word I had just typed into a note.

Expectation vs. IndexedDB
Expectation vs. IndexedDB

There it was. pineapple, in plain bytes, inside a Postgres heap file at /pglite/.../base/5/16385, at byte 709. Every note, title and tag was sitting there, and so was the trigram search index, which is a neat pre-chopped copy of your text. Anyone who gets a copy of that profile can read all of it with grep. That copy is easier to come by than it sounds: a laptop backup, a synced home folder, another app or user on the same machine, a support engineer's disk image.

One line from the issue I opened about it sums it up: notes are end-to-end encrypted on Homebase, so this local copy is the last plain-text one. The brand page had to say, honestly, "No, the browser database is not yet encrypted."

Living with a real Postgres in a browser

Before I could fix that, I had to be clear about what running Postgres in a webview had already taught me, because every one of those lessons became a constraint on the fix.

Writes are expensive.

PGlite keeps the whole data directory in memory and flushes changed files to IndexedDB. Postgres writes its WAL in 16 MB segment files, and PGlite's idb:// saves a changed file whole. So early on, every small edit in Journal rewrote about 16 MB, and a full flush took around half a second. The fix was relaxedDurability, so queries stop waiting on the flush. Whatever I built could not make writes slower again.

OPFS isn't an escape hatch.

The Origin Private File System is the obvious faster store, but it breaks in Safari, and Journal's iOS app runs on the same WebKit engine. IndexedDB it is.

Switching to SQLite wasn't an option either.

SQLite has SQLCipher, and encrypted SQLite in the browser exists. But Journal's search is built on Postgres's pg_trgm, the UI runs on PGlite's live queries, and the schema and queries are Postgres. Moving would mean rewriting all of it.

So the requirements wrote themselves. Encrypt everything Postgres stores, file names and sizes included. Use the platform's own WebCrypto, so the key can be non-extractable and there's no cipher code of mine to get wrong. Work on IndexedDB in every webview. Detect tampering. And the hard budget I wrote down before starting: a small edit on a 100 MB database must sync within 2× of plain idb://, or I stop.

I'm not pretending it covers everything. FileVault, BitLocker and iOS Data Protection already protect a stolen device that's switched off. Encrypting inside the app adds protection against other apps and users on the same machine, against backups and synced folders, and against anyone who copies the profile.

The thirty-second version

That's pglite-cipher: encryption at rest for PGlite, in the spirit of SQLCipher. It's open source and works in any app that uses PGlite, Journal or not.

npm install pglite-cipher @electric-sql/pglite
import { PGlite } from '@electric-sql/pglite';
import { EncryptedFs, IndexedDbBackend, importKek } from 'pglite-cipher';

const key = await importKek(rawKey); // 32 random bytes, e.g. from the OS keychain
const fs = new EncryptedFs({ backend: new IndexedDbBackend('data'), key, mode: 'open-or-create' });
const pg = await PGlite.create({ fs, relaxedDurability: true });

await pg.exec('CREATE TABLE IF NOT EXISTS notes (id serial PRIMARY KEY, body text)');

You hand PGlite a filesystem. Everything Postgres writes gets sealed with AES-256-GCM, using the browser's own WebCrypto, before it reaches IndexedDB. Postgres is unchanged and has no idea any of this is happening. The package has zero runtime dependencies and no cryptography of its own: every primitive is a WebCrypto call.

What was there before

Before writing a line of code I went shopping anyway. Surely someone had solved "encrypted database in the browser" already? Several people had, just never for the combination I needed.

pglite-encrypted-fs. The closest thing to what I wanted: an encrypting filesystem for PGlite, using AES-256-GCM. Two things ruled it out for me. It runs on Node only, because it uses Node's crypto module, so it can't run in a browser or a mobile webview. And it encrypts page contents one file at a time while leaving a handful of files in the clear (.conf files, PG_VERSION, postmaster.*), so the file names, sizes and count are all visible. The key comes from a PBKDF2 passphrase and lives in a Node Buffer.

Encrypted SQLite in WASM. This is the mature route. PowerSync's web SDK and Notesnook's web app use SQLite compiled to WASM with SQLite3 Multiple Ciphers, which seals every page with ChaCha20-Poly1305. Evolu ships its own SQLite WASM build that writes the SQLCipher 4 page format (AES-256-CBC with HMAC-SHA512) through its own C codec. They work well. They also mean giving up Postgres, and the cipher runs as C code compiled into WASM, with the key sitting in WASM memory next to the database's heap. I wanted Postgres, and I wanted the crypto to come from the platform.

Field-level encryption. RxDB and Dexie (via dexie-encrypted) can encrypt the fields or tables you choose before they hit IndexedDB. RxDB's free plugin uses crypto-js AES in CBC mode, which has no integrity check; its premium plugin uses WebCrypto AES-GCM. These are document stores, so they don't apply to PGlite. They also show the problem with encrypting fields: RxDB can't index an encrypted field, and dexie-encrypted leaves indexes in plain text.

"Just encrypt the columns yourself." You could encrypt body before every INSERT and decrypt after every SELECT. Then WHERE body ILIKE '%pine%' stops working, so does every index on that column, and Postgres's catalogs and WAL still give away your table names, row counts and sizes. At that point there's not much reason to carry a whole Postgres around.

SQLCipher. The gold standard, in wide use since 2008, and the design I borrowed most from. It's built into SQLite's pager, though, so there is no Postgres version of it, and as above, moving Journal to SQLite wasn't on the table.

Laid side by side:

Option

Runs in a browser

Postgres

Hides file layout

Crypto comes from

PGlite idb://

yes

yes

no

no crypto

pglite-encrypted-fs

no, Node only

yes

no

Node crypto

SQLite WASM + Multiple Ciphers

yes

no

yes

C compiled to WASM

Evolu sqlite-wasm

yes

no

yes

C compiled to WASM

RxDB, dexie-encrypted

yes

no

no

crypto-js, TweetNaCl, or WebCrypto (RxDB premium)

pglite-cipher

yes

yes

yes

the browser's WebCrypto

That last row is the gap: Postgres in a webview, the whole data directory encrypted, file names and sizes hidden, tampering detected, and a key that JavaScript can't read back once it's imported.

Why not just do what SQLCipher does?

SQLCipher hooks into SQLite's pager and encrypts one page at a time on every read and write, with a few bytes reserved at the end of each page for the IV and the MAC. Postgres has no such hook, and its 8 KB pages have no spare bytes for a nonce and a tag. The cipher had to go somewhere else, and there were two candidate spots:

Encrypt on every read and write

Keep plaintext in memory, encrypt changed blocks at sync

Crypto

must be synchronous, so not WebCrypto; I'd need JavaScript or WASM AES

WebCrypto, asynchronous and native

Storage

must be synchronous too: only OPFS sync access handles qualify, and they aren't reliable in every webview I target

any async store: IndexedDB today, something native later

Memory

small

the whole data directory, which PGlite's own idb:// already does

Atomic across files

needs its own journal

one storage transaction per sync

I took the second. PGlite's idb:// already keeps the entire data directory in memory, so this adds no plaintext to memory that wasn't there before. The price is paid at open time, when every record is read and decrypted before Postgres starts. In return, a query never touches cryptography at all.

How it works

Where it sits

pglite-cipher is a PGlite filesystem. EncryptedFs extends PGlite's MemoryFS, so Postgres reads and writes ordinary files in Emscripten's in-memory filesystem (MEMFS). Underneath that sit a tracker, a file map, the cipher and a storage backend.

flowchart LR
  PG[Postgres in WASM] -- read/write files --> MEMFS[MEMFS: plaintext data directory]
  MEMFS -- wrapped ops --> T[Tracker: dirty blocks and inodes]
  T -- snapshot --> FM[File map: plan the sync]
  FM -- records to seal --> C[AES-256-GCM via WebCrypto]
  C -- one atomic commit --> B[(IndexedDB)]
  B -- open: read and decrypt every record --> MEMFS
  classDef pg fill:#336791,stroke:#1f3f5c,color:#ffffff
  classDef el fill:#DACAB0,stroke:#B9A57F,color:#1C1B1A
  class PG,MEMFS pg
  class T,FM,C,B el

Every file under the data directory is covered: tables, indexes, WAL, pg_control, the catalogs, temp files.

Knowing what changed

The tracker wraps the MEMFS operations that change a file (write, msync, setattr, mknod, rename, unlink and friends) and keeps, per file, a bitmap of which 64 KB blocks are dirty. A one-row UPDATE dirties a block or two, so a sync seals a block or two.

Missing a write would be fatal, because the next open would find the store short a block and refuse it. So every snapshot also walks the tree as a safety net. A file whose size or modification time changed with nothing marked gets rewritten whole, and the miss is counted in stats().trackingGaps.

The file map: hiding the layout

The store doesn't know about files at all. It holds blocks under random 32-character hex ids, plus a header and a root. The file map is an encrypted table that says "block 0016ef00… is block 3 of file X". File names, sizes, modes and even the number of files live only inside that encrypted table.

Here is everything someone with a copy of the store sees in IndexedDB:

Key

What it is

0, 1

two copies of a 168-byte header, indistinguishable from random bytes

2

the root, sealed

0016ef00ab02a6ac0e4ec85fa1a9b146 and thousands of friends

sealed blocks, every one exactly the same length

No byte and no name says "pglite-cipher" or "Postgres".

Anatomy of a sealed block

Every value in the store has the same four parts:

<svg viewBox="0 0 640 300" xmlns="http://www.w3.org/2000/svg" font-family="Inter, Noto Sans, system-ui, sans-serif">
  <rect x="0" y="0" width="640" height="300" rx="14" fill="#1C1B1A"/>
  <text x="20" y="32" fill="#F6F1E5" font-size="16" font-weight="700">One stored 64 KB block: 65,580 bytes</text>
  <rect x="20" y="50" width="80" height="60" rx="6" fill="#336791"/>
  <text x="60" y="76" fill="#fff" font-size="14" font-weight="700" text-anchor="middle">salt</text>
  <text x="60" y="96" fill="#E6E4DD" font-size="12" text-anchor="middle">16 B</text>
  <rect x="104" y="50" width="72" height="60" rx="6" fill="#4f86b8"/>
  <text x="140" y="76" fill="#fff" font-size="14" font-weight="700" text-anchor="middle">nonce</text>
  <text x="140" y="96" fill="#F6F1E5" font-size="12" text-anchor="middle">12 B</text>
  <rect x="180" y="50" width="352" height="60" rx="6" fill="#1f3f5c" stroke="#336791"/>
  <text x="356" y="76" fill="#fff" font-size="14" font-weight="700" text-anchor="middle">ciphertext</text>
  <text x="356" y="96" fill="#E6E4DD" font-size="12" text-anchor="middle">65,536 B of Postgres file, scrambled</text>
  <rect x="536" y="50" width="84" height="60" rx="6" fill="#DACAB0"/>
  <text x="578" y="76" fill="#1C1B1A" font-size="14" font-weight="700" text-anchor="middle">tag</text>
  <text x="578" y="96" fill="#1C1B1A" font-size="12" text-anchor="middle">16 B</text>
  <text x="20" y="138" fill="#A8A59D" font-size="12">which session key</text>
  <text x="104" y="154" fill="#A8A59D" font-size="12">a number used once</text>
  <text x="270" y="138" fill="#A8A59D" font-size="12">unreadable without the key</text>
  <text x="536" y="138" fill="#DACAB0" font-size="12" font-weight="700">the tamper seal</text>
  <rect x="20" y="186" width="600" height="92" rx="10" fill="none" stroke="#DACAB0" stroke-dasharray="6 5"/>
  <text x="36" y="212" fill="#DACAB0" font-size="13" font-weight="700">Sealed in, never stored: the address (AAD)</text>
  <text x="36" y="236" fill="#F6F1E5" font-size="13">record type · store id · key id · file id · block index</text>
  <text x="36" y="260" fill="#A8A59D" font-size="12">The tag covers these too. Open the block with any other address and the seal breaks.</text>
  <path d="M578 112 L578 184" stroke="#DACAB0" stroke-width="2" stroke-dasharray="4 4"/>
</svg>

Think of each block as a letter in a tamper-evident envelope. The ciphertext is the letter: 64 KB of a Postgres file, unreadable without the key. The tag is the wax seal: AES-GCM computes it over every bit of the ciphertext, and if a single bit has changed, WebCrypto refuses to decrypt. The nonce is a fresh random 12 bytes per write, because GCM falls apart if one key and nonce ever seal two different letters. The salt says which session key sealed the block (more on keys below).

The seal also covers an address that is never stored: record type, store, key, file and position in that file, as if the seal were stamped across the address label. pglite-cipher opens each block with the address it expects from the file table, so an envelope moved to a different slot fails even though nobody touched the letter.

That's 16 + 12 + 16 = 44 bytes of overhead per block, so a 64 KB block is stored as 65,580 bytes. Keep that number in mind for the performance section, because it caused trouble later.

Keys, in two tiers

flowchart TD
  KEK["KEK: 32 bytes from you (e.g. OS keychain)"] -- AES-256-GCM wrap --> DEK["DEK: 32 random bytes, wrapped in the header"]
  DEK -- "HKDF(metaSalt, header label)" --> HK[header key: seals the meta]
  DEK -- "HKDF(session salt, record info)" --> SK[session subkey: seals every record]
  classDef pg fill:#336791,stroke:#1f3f5c,color:#ffffff
  classDef el fill:#DACAB0,stroke:#B9A57F,color:#1C1B1A
  class KEK,DEK pg
  class HK,SK el

You bring a key-encryption key (KEK). The package draws its own data key (DEK), wraps it under your KEK and keeps it in the header. importKek imports your 32 bytes as a non-extractable CryptoKey that can only wrap and unwrap, then overwrites your raw bytes with zeros.

The DEK never encrypts anything directly. Each writer session draws a 16-byte salt and derives its own subkey from the DEK with HKDF-SHA256. The reason is nonce safety. With random 96-bit nonces, NIST's guidance limits one AES-GCM key to about 2³² encryptions. Each subkey is retired after 2²⁴, which keeps the chance of a nonce collision near 2⁻⁴⁹ per subkey and means the DEK itself never wears out. SQLCipher 5 goes further and derives a fresh subkey for every page write; one per session is what WebCrypto can afford without an extra call per block.

That design gives two kinds of key change. changeKey(newKek) re-wraps the DEK under a new KEK and touches no block, so it takes milliseconds. rotateDataKey() re-encrypts everything under a brand new DEK. It costs about one open plus one full write, and it's the one that helps if someone kept a copy of the old header and knows the old key.

Open, sync, close

Open: unlock a header copy with the KEK, open the root, fetch the file table and check it against the root, then read every block in pages of 512 with up to 64 decrypts in flight, and finally check the counts and fingerprints against the root. Only then does Postgres see a data directory. If anything fails, the half-built directory is deleted, so PGlite never runs initdb over a store it couldn't read.

Sync: take a synchronous snapshot (Postgres runs to completion between engine calls, so it's a consistent cut), plan it against the file map, seal the dirty blocks, any changed table blocks and a new root, and write all of it in one IndexedDB transaction. The store holds either the state before a sync or the state after, never a mix. Every commit also carries expectRoot, so a second tab writing to the same store gets a StaleWriterError instead of silently overwriting the first one's work.

Tamper detection, in plain English

Encryption stops people from reading your data. It doesn't automatically stop them from changing it. Plenty of schemes encrypt perfectly well and still let an attacker swap blocks around, delete some, or put back old ones, and the app happily loads the result. A rolled-back balance or a deleted audit row is a real attack even if nobody can read a single byte.

pglite-cipher checks the whole store on every open, and it does it in three layers.

Every seal. Each block's tag must verify. This catches any change to the bytes of any record, down to a single bit.

Every address. Each block is opened with the address the encrypted file table says it should have: this store, this file, this position. A genuine block in the wrong place fails, and so does a genuine block copied in from another store.

Every count and fingerprint. The root is the signed table of contents. It records how many data blocks exist, and it keeps two SHA-256 fingerprints: one over the file table, and one (the manifest) over the current seal of every block. A missing block changes the count. An extra block has no entry in the table. And here's the subtle one: a block replaced with yesterday's copy of itself passes the seal and the address check, because it really was sealed with your key at that address. But its seal isn't the one in today's fingerprint, so the open still fails.

Any failure ends the same way: CorruptStoreError, and nothing is loaded. The error names a slot or a block id, never a path, a key or any plaintext. The format specification (FORMAT.md) lists every check, and docs/design/integrity.md maps each kind of tampering to the check that catches it.

Pick an attack below and watch the open go through its checks:

const C = { bg: '#1C1B1A', card: '#242321', text: '#F6F1E5', muted: '#A8A59D', pg: '#336791', ok: '#DACAB0', bad: '#E07A5F', warn: '#F2C14E', idle: '#4A4843' };

const STEPS = [
  'Unlock the header with your key',
  'Open the root, the signed table of contents',
  "Check the file table against the root's fingerprint",
  'Open every block at the address the table gives it, and check its seal',
  "Count the blocks and compare every seal with the root's fingerprint",
];

const ATTACKS = [
  { name: 'Use the wrong key', story: 'Someone copies the store and tries to open it with a key they guessed.', fail: 0, why: 'The data key is locked inside the header under your key. A different key does not unlock it, and both header copies agree, so this reads as a wrong key.', result: 'WrongKeyError' },
  { name: 'Flip one bit', story: 'Someone changes a single bit inside one stored block, hoping to turn a 1 into a 3.', fail: 3, why: 'The seal is computed over every bit of the block. One changed bit and the seal no longer matches, so WebCrypto refuses to decrypt it.', result: 'CorruptStoreError' },
  { name: 'Swap two blocks', story: 'Someone swaps two stored blocks, so a block of one table lands where a block of another was.', fail: 3, why: 'Both blocks are genuine, but each was sealed together with its own address. Opened at the address the table expects, the seal breaks.', result: 'CorruptStoreError' },
  { name: 'Copy in a block from another store', story: "Someone copies a block out of another user's encrypted store into this one.", fail: 3, why: 'The sealed address names the store too (a random store id), so a block from elsewhere can never pass as one of these.', result: 'CorruptStoreError' },
  { name: 'Add an extra block', story: 'Someone stores an extra record under a new id.', fail: 3, why: 'Every block id must appear in the encrypted file table. An id nobody listed has no file and no position, so the open stops there.', result: 'CorruptStoreError' },
  { name: 'Delete a block', story: 'Someone deletes a block, or every block of a file, to make some rows vanish.', fail: 4, why: 'The root records how many data blocks exist and fingerprints all of them. One missing and the count is wrong.', result: 'CorruptStoreError' },
  { name: "Put back yesterday's block", story: "Someone kept yesterday's copy of a block and writes it back. It really was sealed with your key, at this exact address.", fail: 4, why: "It passes the seal and the address check. But the root fingerprints the current seal of every block, and yesterday's seal is not in it.", result: 'CorruptStoreError' },
  { name: 'Put back an older root', story: 'Someone restores an older table of contents to roll the database back.', fail: 4, why: "The older root's fingerprints describe older blocks, and they no longer match what is in the store.", result: 'CorruptStoreError' },
  { name: 'Downgrade the format', story: 'Someone edits the header to claim an older version or a weaker cipher.', fail: 0, why: 'Version, cipher and block size are sealed inside the header under a key derived from the data key. Edit them and that seal breaks.', result: 'CorruptStoreError' },
  { name: 'Damage one header copy', story: 'A disk error damages one of the two header copies.', fail: -1, why: 'There are two copies of the header. The good one opens, and the next sync writes both again.', result: 'Opens normally', tone: 'ok' },
  { name: "Restore last week's whole store", story: 'Someone replaces the entire store with a complete copy from last week.', fail: -1, why: "Every byte of that copy is genuine and consistent with itself, so every check passes and it opens with last week's data. Catching this needs a counter kept outside the store. Known limit.", result: "Opens, with last week's data", tone: 'warn' },
];

function App() {
  const [sel, setSel] = useState(1);
  const [shown, setShown] = useState(0);
  const a = ATTACKS[sel];
  const last = a.fail < 0 ? STEPS.length : a.fail + 1;

  useEffect(() => {
    setShown(0);
    let n = 0;
    const t = setInterval(() => { n += 1; setShown(n); if (n >= last + 1) clearInterval(t); }, 420);
    return () => clearInterval(t);
  }, [sel]);

  const state = (i) => {
    if (a.fail >= 0 && i > a.fail) return shown > a.fail ? 'skip' : 'idle';
    if (i >= shown) return 'idle';
    if (i === a.fail) return 'bad';
    return 'ok';
  };
  const done = shown > last;
  const tone = a.tone === 'warn' ? C.warn : a.tone === 'ok' ? C.ok : C.bad;

  return (
    <div style={{ background: C.bg, color: C.text, borderRadius: 14, padding: 16 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {ATTACKS.map((x, i) => (
          <button key={x.name} onClick={() => setSel(i)}
            style={{ minHeight: 36, padding: '6px 12px', borderRadius: 999, cursor: 'pointer', fontSize: 13,
              border: '1px solid ' + (i === sel ? C.ok : C.pg), background: i === sel ? C.pg : 'transparent', color: C.text }}>
            {x.name}
          </button>
        ))}
      </div>
      <div style={{ marginTop: 14, padding: 12, borderRadius: 10, background: C.card, fontSize: 14 }}>
        <div style={{ color: C.muted, fontSize: 12, textTransform: 'uppercase', letterSpacing: 1 }}>The attack</div>
        <div style={{ marginTop: 4 }}>{a.story}</div>
      </div>
      <div style={{ marginTop: 12 }}>
        {STEPS.map((s, i) => {
          const st = state(i);
          const col = st === 'ok' ? C.ok : st === 'bad' ? C.bad : C.idle;
          const icon = st === 'ok' ? '✓' : st === 'bad' ? '✗' : st === 'skip' ? '–' : '·';
          return (
            <div key={s} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '6px 0', opacity: st === 'skip' ? 0.45 : 1, transition: 'opacity 200ms' }}>
              <div style={{ flex: 'none', width: 24, height: 24, borderRadius: 999, border: '2px solid ' + col, color: col, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700 }}>{icon}</div>
              <div style={{ fontSize: 14, lineHeight: '22px', color: st === 'idle' ? C.muted : C.text }}>{s}{st === 'skip' ? ' (not reached)' : ''}</div>
            </div>
          );
        })}
      </div>
      {done && (
        <div style={{ marginTop: 10, padding: 12, borderRadius: 10, border: '2px solid ' + tone }}>
          <div style={{ fontFamily: 'ui-monospace, monospace', fontWeight: 700, color: tone }}>{a.result}</div>
          <div style={{ marginTop: 6, fontSize: 14 }}>{a.why}</div>
        </div>
      )}
    </div>
  );
}

Or, as I like to imagine it:

Every attack ends the same way
Every attack ends the same way

Performance

Encryption is never free, so the honest question is where it costs. In pglite-cipher the cost lands in one place.

Operation

Compared with plain PGlite idb://

Queries

no cost at all: Postgres reads plaintext from memory

Writes (sync)

usually much cheaper

Opening the database

more expensive: every block is read and decrypted first

Memory

about the same: the whole data directory is in memory either way

All numbers below come from the project's benchmark, which runs plain idb:// and pglite-cipher on the same data in the same run and reports the median. Desktop runs are from 2026-11-17 (20 runs each): Chromium and Firefox on a Ryzen 5 4600HS laptop, Playwright's WebKit on an M1 Pro MacBook. Phone and tablet runs are from 2026-11-16.

import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer, CartesianGrid } from 'recharts';

const C = { bg: '#1C1B1A', text: '#F6F1E5', muted: '#A8A59D', pg: '#336791', el: '#DACAB0', grid: '#3A3936' };
const TABS = {
  sync: { title: 'Saving a one-row UPDATE, 100 MB database', a: 'plain idb://', b: 'pglite-cipher',
    data: [{ k: 'Chromium', a: 68.1, b: 4.83 }, { k: 'Firefox', a: 154, b: 6.96 }, { k: 'WebKit', a: 156, b: 2.24 }] },
  open: { title: 'Opening a 100 MB database', a: 'plain idb://', b: 'pglite-cipher',
    data: [{ k: 'Chromium', a: 577, b: 923 }, { k: 'Firefox', a: 1315, b: 1265 }, { k: 'WebKit', a: 416, b: 323 }, { k: 'iPad', a: 668, b: 303 }, { k: 'iPhone*', a: null, b: 934 }, { k: 'Redmi', a: 2479, b: 8600 }] },
  inside: { title: 'Inside an encrypted open: reading vs decrypting', a: 'reading from IndexedDB', b: 'decrypting',
    data: [{ k: 'iPad Air M3', a: 223, b: 68 }, { k: 'iPhone 15', a: 669, b: 141 }, { k: 'Redmi', a: 7700, b: 1200 }] },
};

function App() {
  const [tab, setTab] = useState('sync');
  const t = TABS[tab];
  return (
    <div style={{ background: C.bg, color: C.text, borderRadius: 14, padding: 16 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
        {[['sync', 'Writes'], ['open', 'Open'], ['inside', 'Where the open goes']].map(([id, label]) => (
          <button key={id} onClick={() => setTab(id)}
            style={{ minHeight: 36, padding: '6px 14px', borderRadius: 999, cursor: 'pointer', fontSize: 13,
              border: '1px solid ' + (tab === id ? C.el : C.pg), background: tab === id ? C.pg : 'transparent', color: C.text }}>{label}</button>
        ))}
      </div>
      <div style={{ fontSize: 14, fontWeight: 700 }}>{t.title}</div>
      <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>median, ms; lower is better</div>
      <div style={{ width: '100%', height: 260 }}>
        <ResponsiveContainer>
          <BarChart data={t.data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
            <CartesianGrid vertical={false} stroke={C.grid} />
            <XAxis dataKey="k" tickLine={false} interval={0} tick={{ fill: C.muted, fontSize: 11 }} axisLine={{ stroke: C.grid }} />
            <YAxis width={44} tickLine={false} tick={{ fill: C.muted, fontSize: 11 }} axisLine={false} />
            <Tooltip cursor={{ fill: 'rgba(51,103,145,0.25)' }} contentStyle={{ background: C.bg, border: '1px solid ' + C.pg, color: C.text }} formatter={(v) => (v == null ? 'n/a' : v.toLocaleString() + ' ms')} />
            <Legend wrapperStyle={{ color: C.text, fontSize: 12 }} />
            <Bar dataKey="a" name={t.a} fill={C.pg} radius={[3, 3, 0, 0]} />
            <Bar dataKey="b" name={t.b} fill={C.el} radius={[3, 3, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>
      {tab === 'open' && <div style={{ fontSize: 12, color: C.muted, marginTop: 6 }}>* The plain 100 MB run crashed the iPhone tab; the encrypted one finished every open.</div>}
    </div>
  );
}

Writes got faster

Remember the budget: within 2× of plain idb:// for a small edit, or stop. It came in far under that. After a one-row UPDATE on a 100 MB database, pglite-cipher's sync took 4.83 ms in Chromium against 68.1 ms for plain idb://; in WebKit it was 2.24 ms against 156 ms. That's between 14 and 70 times faster, with encryption on. Inserting one 4 KB row shows the same pattern: 7.11 ms against 551 ms in Chromium.

The reason is the tracker. Plain idb:// saves every changed file whole. Postgres writes its WAL in 16 MB segment files, so touching one WAL page means writing out the whole 16 MB segment again. pglite-cipher seals and writes only the 64 KB blocks that changed, and sealing a few blocks costs far less than writing 16 MB to IndexedDB.

Even the worst case for a write holds up. When Postgres starts a new 16 MB WAL segment, the sync took 89 ms in Chromium, 277 ms in Firefox and 30 ms in WebKit.

Opening is where you pay

To open, pglite-cipher has to read and decrypt every block before Postgres can start. On desktop that's affordable. A 100 MB database (which grows to a 267 MB data directory once Postgres adds WAL and catalogs) opened in 923 ms in Chromium against 577 ms plain. In Firefox the two were about even, 1,265 against 1,315 ms. On Apple hardware the encrypted open was faster than plain: 323 against 416 ms in WebKit on the Mac, and 303 against 668 ms in Safari on an iPad Air M3. The iPhone 15 couldn't finish the plain 100 MB run at all (the tab crashed, which is PGlite hitting iOS's memory limit); the encrypted run opened in 934 ms.

The decryption itself is the cheap part. WebCrypto decrypted 64 KB blocks at about 780 MB/s in Chromium, 1,080 MB/s in Firefox and 5,000 MB/s in WebKit on these machines. The open overlaps the two halves of the job: it reads the next page of 512 blocks from IndexedDB while it decrypts the current page, with up to 64 decrypts in flight. On every device I measured, reading took longer than decrypting.

Why 64 KB blocks?

Postgres writes 8 KB pages, so a smaller block would write fewer bytes per change. But every block costs one WebCrypto call and one IndexedDB value, and an open pays that cost once per block. A 100 MB store holds eight times as many blocks at 8 KB as at 64 KB. An early experiment measured 8, 32 and 64 KB, and 64 KB was the only size that opened 100 MB within the budget (1.5 s on desktop) in all three engines.

The 44 bytes that cost six seconds

Then I tested on an Android phone, a Redmi Note 5 Pro in Chrome. Opening the 100 MB database took 8.6 s, against 2.5 s plain. My first guess was that an old phone decrypts slowly. Wrong: decrypting took about 1.2 s. Reading took 7.7 s.

<svg viewBox="0 0 640 170" xmlns="http://www.w3.org/2000/svg" font-family="Inter, Noto Sans, system-ui, sans-serif">
  <rect x="0" y="0" width="640" height="170" rx="14" fill="#1C1B1A"/>
  <text x="20" y="30" fill="#F6F1E5" font-size="15" font-weight="700">Chromium's limit for storing an IndexedDB value inline</text>
  <rect x="20" y="52" width="560" height="40" rx="6" fill="#336791"/>
  <text x="300" y="77" fill="#fff" font-size="13" text-anchor="middle">65,536 bytes: stored inline, read quickly</text>
  <rect x="580" y="52" width="40" height="40" rx="6" fill="#E07A5F"/>
  <text x="600" y="77" fill="#1C1B1A" font-size="12" font-weight="700" text-anchor="middle">+44</text>
  <line x1="580" y1="44" x2="580" y2="102" stroke="#F6F1E5" stroke-width="2" stroke-dasharray="4 3"/>
  <text x="20" y="126" fill="#DACAB0" font-size="13" font-weight="700">A sealed 64 KB block is 65,580 bytes.</text>
  <text x="20" y="148" fill="#A8A59D" font-size="12">44 bytes over the line, so every block becomes a blob: about 1.1 ms to unwrap each on the Redmi.</text>
</svg>

Remember the 65,580 bytes? Chromium keeps an IndexedDB value inline only up to 64 KiB, which is 65,536 bytes. The salt, nonce and tag push every sealed block 44 bytes over that line, so Chromium stores each one as a separate blob and unwraps it on the calling thread, at about 1.1 ms per block on that phone. A 100 MB database is a few thousand blocks, and that adds up to seconds. A stock vivo V2250 showed the same thing, 8.1 s against 1.8 s.

Only the open is affected. Writes, queries and security are exactly as before. The fix is a store layout that keeps records under the inline limit, which will come in a later release with a migration, and there's an open experiment with an OPFS backend aimed at the same problem. Until then, onProgress reports the blocks phase of an open, so an app can show a progress bar while it waits.

Keys and checks

On a 100 MB database

Chromium

Firefox

WebKit (Mac)

changeKey (new KEK)

7.2 ms

22.6 ms

9.9 ms

verify() (full integrity check)

861 ms

1,611 ms

271 ms

rotateDataKey (re-encrypt everything)

2.5 s

5.0 s

0.75 s

I also simulated a year of use: 365 sessions of edits and checkpoints. That left 263 distinct session salts in the store. Deriving all 263 subkeys at open costs about 1.3 ms in Chromium, so session subkeys don't pile up into a slow open over time.

Current limitations

pglite-cipher is new (0.1.1 on npm), and there are things it doesn't do yet, or can't do at all. I'd rather list them here than have you discover them in production.

It only protects data at rest. While the database is open, everything is plaintext in the page's memory, exactly as it is without encryption. The keys are non-extractable CryptoKeys, but JavaScript can't lock memory or reliably wipe it. Closing the database makes a best-effort wipe of what it owns. Other software running as the same user while the database is open can read that memory.

It can't tell that the whole store was rolled back. If someone replaces the entire store with a complete older copy, every byte of it is genuine, so it opens with the older data. Detecting that would need a counter stored somewhere outside the store, and then a sync lost in a crash would look like an attack. If rollback matters for your app, keep a counter on your own server or in the keychain.

Opening is slow on Android. Covered above: about 3.4 times a plain open on the Redmi, because of Chromium's blob path. The open also loads the whole database into memory and decrypts all of it, so open time and memory grow with the size of the database. There's no random access.

You bring the key. There's no PBKDF2 or Argon2 inside, so the key must be 32 random bytes, ideally from the OS keychain. If you want a password, run it through a proper key-derivation function yourself first.

Exports are plaintext. dumpTar, dumpDataDir() and pg_dump output come out decrypted. That's by design, but it means a backup made that way needs its own protection.

Some metadata is visible. Someone with a copy of the store can tell that a database exists, roughly how big it is (the number of blocks, so the size to the nearest 64 KB), and when it was written: which blocks changed between two copies, and which blocks were written in the same session, because they share a salt.

One writer at a time. Two tabs can't write to the same store. When a second writer commits, the first one's next sync is refused with StaleWriterError instead of risking corruption.

It's new. SQLCipher has been in wide use since 2008. pglite-cipher went public on 2026-11-17. It has had no external review or audit yet, and it isn't FIPS validated. Everything it uses is a standard WebCrypto primitive, but the way they're put together is mine, and fresh eyes are very welcome.

How it stacks up against SQLCipher

SQLCipher

pglite-cipher

Verdict

Cipher

v4: AES-256-CBC + HMAC-SHA512; v5 beta: AES-256-GCM

AES-256-GCM via WebCrypto

parity

What the seal covers

ciphertext, IV, page number

ciphertext, nonce, record type, store, key, file and block index

stronger

What is detected

modified or swapped pages

also truncation, replayed blocks and deleted files, on every open

stronger

Changing keys

PRAGMA rekey re-encrypts every page

changeKey in milliseconds, rotateDataKey re-encrypts

stronger

Memory

page cache only, keys mlocked and wiped

whole database in memory, keys can't be locked

weaker

Open cost

random access, opens at once

decrypts everything at open

weaker

Maturity

FIPS builds, used since 2008

new, not yet reviewed

weaker

Try it


See More (10 posts)