A tiny, dependency-free TypeScript wrapper over the Web Crypto API.
One primitive — AES-256-GCM in a compact iv:tag:ciphertext base64 envelope —
exposed as two patterns:
- Password vault — derive a key from a password (PBKDF2-SHA-256, 600k iterations) and encrypt/decrypt locally. For offline-first apps that sync ciphertext a server can't read.
- Sealed share —
seal()encrypts under a fresh random key and hands the key back. Store the ciphertext anywhere; deliver the key out-of-band (a URL fragment is ideal — browsers never send it to the server) and the recipientopen()s it. A zero-knowledge shareable-link primitive.
Runs in browsers and Node 18+ (globalThis.crypto.subtle). No dependencies.
Extracted from production use in CreightonTracker.
Go twin: webcrypto-envelope-go - wire-compatible, not just a port. An envelope produced by either implementation opens in the other; both test suites prove it with fixtures sealed by the opposite side. Encrypt in a browser, decrypt in a Go service - or the reverse.
This is deliberately narrow: one primitive, two patterns, one wire format.
If your ciphertexts don't need to be iv:tag:ciphertext base64, and you don't
need browser + Node + Go interop on that shape, other libraries are probably
a better fit.
- vs.
libsodium.js/tweetnacl- those are general crypto toolkits with dozens of primitives and their own opinions about serialization (secretbox,crypto_box, etc.). If you're already using one, keep using it. This library trades generality for a single, boring format that a Go or Rust service can round-trip against without a shared crypto library. - vs. hand-rolled Web Crypto - the traps are consistent and unforgiving: concatenating the auth tag onto the ciphertext (or forgetting to), reusing an IV across encryptions with the same key, PBKDF2 iteration counts stuck at 2013's recommendation, non-constant-time comparison of tags. Each of those has a test here specifically because it's the shape of a real bug.
- vs. a KMS or vault - if the server should hold the key, use a KMS. This library exists for the two cases where the server must not hold the key: offline-first password-vault sync, and zero-knowledge shareable links. It won't help you with envelope encryption at rest inside your own service.
npm install @stephenspage/webcrypto-envelopeReleases are published to npm via GitHub Actions with OIDC Trusted Publishing, so every version carries a signed provenance statement.
If you prefer to install straight from GitHub (a prepare hook builds it on
install):
npm install github:JacobStephens2/webcrypto-envelopeimport { deriveKey, randomSalt, encrypt, decrypt } from '@stephenspage/webcrypto-envelope';
const salt = randomSalt(); // store alongside the user (not secret)
const key = await deriveKey(password, salt); // PBKDF2 → AES-256-GCM
const blob = await encrypt(JSON.stringify(data), key); // "iv:tag:ciphertext"
// ... sync `blob` to a server that can never read it ...
const data = JSON.parse(await decrypt(blob, key));import { seal, open } from '@stephenspage/webcrypto-envelope';
// On the sharer's device:
const { key, envelope } = await seal(JSON.stringify(report));
await api.storeShare(token, envelope); // server holds only ciphertext
const link = `https://app.example/share/${token}#${key}`; // key lives in the fragment
// In the recipient's browser (no account, no password):
const envelope = await api.getShare(token); // server returns the opaque blob
const key = location.hash.slice(1); // never sent to the server
const report = JSON.parse(await open(envelope, key));| Function | Purpose |
|---|---|
deriveKey(password, saltB64, { iterations?, extractable? }) |
PBKDF2-SHA-256 → AES-256-GCM CryptoKey (non-extractable by default) |
exportRawKey(key) → string |
Export an extractable Envelope key as padded base64 (for persist / wrap) |
importKey(rawB64) |
Import base64 encoding of exactly 32 raw bytes as an Envelope key |
encrypt(plaintext, key) → string |
AES-256-GCM; returns iv:tag:ciphertext (base64) |
decrypt(envelope, key) → string |
Throws on wrong key or tampering (GCM auth) |
seal(plaintext) → { key, envelope } |
Encrypt under a fresh random key |
open(envelope, keyB64) |
Decrypt a sealed payload |
randomKey() / randomSalt(bytes?) |
base64 random key / salt |
An Envelope key is a 256-bit secret AES-GCM key. importKey and open
accept base64 that decodes to exactly 32 raw bytes, including omitted padding
and ASCII whitespace. Shorter keys (including formerly accepted 16- and 24-byte
keys) and every other decoded size are intentionally rejected.
encrypt, decrypt, and exportRawKey require a secret CryptoKey reporting
AES-GCM with a 256-bit length. Conforming keys created outside this library
remain supported, including encrypt-only keys for encryption and decrypt-only
keys for decryption. exportRawKey also checks that the actual exported material
is 32 bytes and returns padded base64.
Key policy failures reject with an ordinary Error whose message is
Invalid key (expected a 256-bit AES-GCM key). For conforming keys, native
Web Crypto identity, permitted-usage, extractability, and authentication failures
still propagate. Invalid key base64 retains the native decoding error. decrypt
decodes the Envelope before checking the key policy; open imports its key
before decoding the Envelope. Imported keys remain non-extractable with both
encrypt and decrypt usages, and derived keys remain non-extractable by default.
An Envelope is three base64 fields in iv:tag:ciphertext order. The
authentication tag must decode to exactly 16 bytes; ciphertext may be empty.
Encryption generates a 12-byte IV and emits padded base64. Decoding also accepts
omitted padding, ASCII whitespace, and IV lengths supported by the Web Crypto
provider (including 16-byte IVs).
Decoding intentionally rejects formerly accepted envelopes whose tag and
ciphertext were resegmented into a non-16-byte tag, even if the reconstructed
ciphertext-followed-by-tag bytes are unchanged. Both decrypt and open reject
these with Invalid envelope format (expected a 16-byte tag). Wrong field counts
still report Invalid envelope format (expected iv:tag:ciphertext); invalid
base64 and authentication failures propagate from the underlying APIs.
seal/open: the link is the credential. Anyone with the full URL (including the fragment) can decrypt. Pair it with short-lived, revocable tokens server-side and treat the link like a password. Fragments aren't sent inRefereror server logs — don't undo that by shippinglocation.hrefto analytics.- Metadata isn't hidden. GCM protects content + integrity, not the fact that something was stored, its size, or timing.
- Key handling is yours. If you persist a derived key (e.g. to survive
reloads), you trade some at-rest protection for UX — prefer a non-extractable
CryptoKeykept in memory, or re-derive per session, where you can. - This is a thin convenience layer over a vetted primitive (AES-256-GCM), not a protocol. For multi-party or long-lived key management, use a real protocol.
MIT © Jacob Stephens