# Encrypt event payloads end to end

URL: https://docs.folkways.io/docs/guides/encrypt-event-payloads

Encrypt payloads before publishing and decrypt them only in authorized applications.

Folkways transports opaque payload bytes. You can encrypt application data before publishing, then decrypt it in authorized recipients. The service still needs routing and authorization metadata: topic names, event names, publisher identities, headers, payload sizes and timing remain visible. Do not put sensitive plaintext in those fields.

## Manage keys in your application [#manage-keys-in-your-application]

Use a reviewed encryption and key-distribution design appropriate to your product. Provision an AES-GCM key securely to authorized endpoints; never include that key in a token, topic name, event or public application bundle. Define key rotation, member removal and recovery. Removing a member cannot erase keys or plaintext they already received.

The example below assumes an authorized application already has a shared, non-extractable AES-GCM CryptoKey. It does not implement key exchange, sender signatures or protection against an endpoint that has been compromised.

## Encrypt and decrypt [#encrypt-and-decrypt]

```ts check
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();

export async function seal(key: CryptoKey, plaintext: string, context: string) {
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const ciphertext = new Uint8Array(await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv, additionalData: textEncoder.encode(context) },
    key, textEncoder.encode(plaintext),
  ));
  const envelope = new Uint8Array(iv.length + ciphertext.length);
  envelope.set(iv);
  envelope.set(ciphertext, iv.length);
  return envelope;
}

export async function open(key: CryptoKey, sealed: Uint8Array, context: string) {
  if (sealed.length < 28) throw new Error('Invalid encrypted envelope');
  const bytes = Uint8Array.from(sealed);
  const plaintext = await crypto.subtle.decrypt(
    { name: 'AES-GCM', iv: bytes.slice(0, 12), additionalData: textEncoder.encode(context) },
    key, bytes.slice(12),
  );
  return textDecoder.decode(plaintext);
}
```

Generate a fresh nonce for every encryption under the same key and rotate keys within appropriate cryptographic usage limits. The same context must be provided on both sides; here it binds the ciphertext to the room and event name. In production, version the envelope and include a non-secret key identifier in authenticated metadata. Treat authentication failure as an invalid message, not a reason to render unauthenticated plaintext.

## Publish encrypted bytes [#publish-encrypted-bytes]

```ts
const room = client.topic('private/room');
const context = 'private/room:message:v1';
const sub = room.subscribe(async (message) => {
  if (message.name !== 'message') return;
  try {
    console.log(await open(roomKey, message.payload, context));
  } catch {
    console.error('Unable to authenticate encrypted message');
  }
});
await sub.ready;
await room.publish('message', await seal(roomKey, 'Hello', context), { contentType: 'bytes' });
```

Only authorized recipients with the correct key can decrypt the payload. A shared symmetric key does not prove which member created the ciphertext. Use the verified publisher field and additional application-level authentication where necessary.

## Encrypt the local store separately [#encrypt-the-local-store-separately]

The SDK's persistent-store cipher accepts strings and returns strings. Encrypt cached values and queued publishes independently using an application-controlled storage key:

```ts
import { Folkways } from '@folkwaysio/realtime';
import { indexedDbStore } from '@folkwaysio/realtime/stores/indexeddb';

function toBase64(bytes: Uint8Array) {
  let binary = '';
  for (const byte of bytes) binary += String.fromCharCode(byte);
  return btoa(binary);
}
function fromBase64(value: string) {
  return Uint8Array.from(atob(value), c => c.charCodeAt(0));
}

const client = new Folkways.Realtime({
  url, authUrl, store: indexedDbStore(),
  cipher: {
    encrypt: async plain => toBase64(await seal(storageKey, plain, 'local-store:v1')),
    decrypt: async sealed => open(storageKey, fromBase64(sealed), 'local-store:v1'),
  },
});
```

Here storageKey is an application-provisioned key distinct from the room key. Store encryption does not replace payload encryption or protect data in a compromised running application. Clear local data on sign-out, and plan how storage keys are retained or destroyed.

## Verify [#verify]

Check that recipients without the key cannot decode payloads, modified ciphertext is rejected, and authorized recipients can decrypt retained events after reconnect. Test key rotation, lost keys, member removal and local-store recovery. For sensitive applications, obtain an independent security review.

See [Local storage](/docs/js-sdk/local-storage), [private topics](/docs/concepts/topics#private-topics) and
[payload format](/docs/realtime-api/payloads).
