> From *AT Protocol Spaces: A Field Guide* on atproto.how, revised 2026-11-23.
> Web page: https://atproto.how/atproto-spaces-field-guide/5-cryptography
> Index for agents: https://atproto.how/llms.txt · Text CC BY-SA 4.0, code samples MIT.

# Chapter 5 · Cryptography in depth

> **Note**
>
> *Who this chapter is for.* This chapter is dense because its subject is dense. Most readers, and most developers, never need the internals of these algorithms and data structures, and can probably skip it. It is written mostly for people building storage and sync applications and tools.

Commits in a space repo aren’t signed with the account’s signing key, because permissioned data shouldn’t carry proof of authorship that survives a leak outside the space \[spec\]. A syncer still needs to know that its copy is complete and that it came from the repo host. Spaces use four cryptographic constructions: LtHash to summarize a repo, HPKE secret export to agree a per-request secret, RFC 9421 `hmac-sha256` signatures to authenticate a commit or record under that secret, and RFC 9421 `ecdsa-p256-sha256` signatures to bind a credential to its holder.

If cryptography is new to you, each one does one job:

- LtHash makes a short fingerprint of every record in a repo, so a reader can check that its copy is complete.
- HPKE secret export lets the reader and the repo host agree on a secret for one request, without ever sending the secret itself.
- The HMAC signature uses that secret to show that a response came from the repo host and wasn’t changed on the way.
- The ECDSA signature shows that a request came from the app the credential was issued to.

In atproto-crates, `atproto-space` implements all four: `set_hash` (LtHash), `kem` (the shared secret), `mac` (commit and record MACs) and `http_signature` (credential binding). `atproto-space-client` signs and verifies through them \[crates\].

> **If you’re building an app**
>
> If you use a library such as `@atproto/space` or `atproto-space-client`, you won’t implement any of this, but it helps to know what a failed check means. `@atproto/space` is the official TypeScript package, maintained by Bluesky Social PBC, and `atproto-space-client` is the Rust client in atproto-crates. A MAC failure usually means the author rotated a key, so refresh their DID document and retry. A digest mismatch means your copy has drifted, so recover the repo with `getRepo`. If you’re writing the library, this chapter is your specification, and [Appendix G](https://atproto.how/atproto-spaces-field-guide/g-worked-values.md) holds worked values to test against.

<a id="lthash-the-set-hash"></a>

## 5.1 LtHash, the set hash

LtHash keeps a running total. Each record is turned into a long list of numbers. Writing the record adds those numbers to the total, and deleting it subtracts them. Addition doesn’t care about order, so two copies that hold the same records always reach the same total, however the records arrived. The commit carries a short fingerprint of that total. A syncer that computes the same fingerprint from its own copy holds the same records as the host. The numbers come from a one-way hash, so neither the total nor the fingerprint can be turned back into records. Two copies can be compared without revealing what either one holds.

LtHash comes from Lewi, Kim, Maykov, and Weis, [Securing Update Propagation with Homomorphic Hashing](https://eprint.iacr.org/2019/227). Spaces use the 16-bit variant: a 2048-byte state read as 1024 little-endian `uint16` lanes \[spec\].

Each record contributes one element, the UTF-8 bytes of `{collection}/{rkey}/{record_cid}`, where `record_cid` is the [DASL CID](https://dasl.ing/cid.html) of the record’s [DRISL](https://dasl.ing/drisl.html) encoding, rendered as a string \[spec\]. For example:

<a id="code-5-1"></a>

```text
community.lexicon.calendar.rsvp/3n2gtxdkr222p/bafyreiblr6f6oy3zi426nksahddwp4tgsfgedtqk27fyxqtav66kjvwkgu
```

Both sides must produce identical bytes. `atproto-space` exposes `record_element_bytes(collection, rkey, cid)` so callers don’t hand-format it \[crates\].

Adding means expand the element to 2048 bytes with BLAKE3 in XOF mode, read those bytes as 1024 little-endian `uint16` lanes, and add each lane into the state modulo 65536. Removing subtracts instead \[spec\]. An update is a remove of the old element and an add of the new one.

<a id="code-5-2"></a>

```python
from blake3 import blake3
import hashlib, struct

def lanes(elem: bytes):
    raw = blake3(elem).digest(length=2048)
    return struct.unpack("<1024H", raw)

def add(state, elem):
    return [(a + b) & 0xFFFF
            for a, b in zip(state, lanes(elem))]

def sub(state, elem):
    return [(a - b) & 0xFFFF
            for a, b in zip(state, lanes(elem))]

def digest(state):
    raw = struct.pack("<1024H", *state)
    return hashlib.sha256(raw).digest()

EMPTY = [0] * 1024
```

**Reference: Properties**

Both operations are commutative, so the state depends only on the current set of records, never on the order of writes \[spec\]. The empty state is all zeroes, and the commit’s `data` is `sha256(state)`. The host keeps the full state, and the commit carries this digest.

**Reference: Security**

Collision resistance rests on a lattice problem, which is believed to resist quantum attack \[spec\].

Lanes are little-endian. The signature halves and the HPKE labels in this chapter are big-endian.

<a id="why-macs-and-not-signatures"></a>

## 5.2 Why MACs and not signatures

> *In the family space.* Before Marcus removed him, Jake could see everyone’s reunion RSVPs in the family app, and he kept a copy of Ruth’s. If he shows it to someone outside the family, can that person check that Ruth wrote it?

A public record is signed so anyone, anywhere, forever, can confirm who wrote it. If someone had a PLC audit log for an identity, and a MST (or slice of one) they effectively have offline content that is self verifying. Permissioned data should not carry proof of authorship that survives a leak outside its access boundary, so space repos are not signed \[spec\]. Holmgren’s [permissioned data diary](https://dholms.leaflet.pub/) makes the full case.

Instead the syncer and the repo host agree an ephemeral secret for one request, and the host returns a MAC (message authentication code) under it. A MAC is a short tag computed from a message and a secret, and only someone who holds the secret can make one or check one. The syncer can check the MAC, so it trusts the response. But the syncer could have computed the MAC itself, so the MAC proves nothing to anyone else. This property is called **deniability**.

<a id="the-shared-secret"></a>

## 5.3 The shared secret

The secret comes from the [secret export](https://www.rfc-editor.org/rfc/rfc9180#section-6.2) feature of HPKE ([RFC 9180](https://www.rfc-editor.org/rfc/rfc9180)). Only export is used, so nothing is encrypted \[spec\].

**Reference: The HPKE suite** \[spec\]

| Parameter | Value |
| --- | --- |
| Mode | Base (`0x00`) |
| KEM | DHKEM(P-256, HKDF-SHA256), `0x0010` |
| KDF | HKDF-SHA256, `0x0001` |
| AEAD | Export-only, `0xFFFF` |
| `info` | `"atproto-mac"` |
| `exporter_context` | empty |
| `L` | 32 |

```text
// on the syncer
enc, shared_secret = SendExportBase(
    author_kem_public_key,
    info="atproto-mac",
    exporter_context="", L=32)

// on the repo host
shared_secret = ReceiveExportBase(
    enc, author_kem_private_key,
    info="atproto-mac",
    exporter_context="", L=32)
```

With this suite, `enc` is the syncer’s ephemeral P-256 public key. The syncer sends it as the `keyid` of its MAC request, encoded as a `did:key`. HPKE encodes `enc` as an uncompressed point, while `did:key` uses the compressed form, so convert at that boundary \[spec\]. The syncer should derive a new secret for every request, including retries and each page of a paginated response; the repo host derives its copy after authorizing the request \[spec\].

Where no HPKE library with secret export is available, the spec’s non-normative appendix spells the same result in plain ECDH and HKDF-SHA256 calls:

<a id="code-5-3"></a>

```text
kem_id   = "KEM" || uint16be(0x0010)
suite_id = "HPKE" || uint16be(0x0010)
        || uint16be(0x0001) || uint16be(0xFFFF)

LabeledExtract(id, salt, label, ikm) =
  HKDF-Extract(salt, "HPKE-v1" || id || label || ikm)
LabeledExpand(id, prk, label, info, L) =
  HKDF-Expand(prk, uint16be(L) || "HPKE-v1"
              || id || label || info, L)

// 1. ECDH; keys uncompressed (0x04 || x || y)
dh = ECDH(ephemeral_priv, author_pub)  // syncer
   = ECDH(author_priv, ephemeral_pub)  // host
eae_prk    = LabeledExtract(kem_id, "", "eae_prk", dh)
kem_secret = LabeledExpand(kem_id, eae_prk,
               "shared_secret",
               ephemeral_pub || author_pub, 32)

// 2. Key schedule, base mode, no PSK
psk_id_hash = LabeledExtract(suite_id, "",
                "psk_id_hash", "")
info_hash   = LabeledExtract(suite_id, "",
                "info_hash", "atproto-mac")
context     = 0x00 || psk_id_hash || info_hash
secret      = LabeledExtract(suite_id, kem_secret,
                "secret", "")
exporter_secret = LabeledExpand(suite_id, secret,
                "exp", context, 32)

// 3. Export, empty exporter context
shared_secret = LabeledExpand(suite_id,
                exporter_secret, "sec", "", 32)
```

Check either path against the export-only P-256 entry in the [HPKE test vectors](https://github.com/cfrg/draft-irtf-cfrg-hpke/blob/master/test-vectors.json). This KEM is not post-quantum secure; a future version may swap in one that is, such as ML-KEM \[spec\].

<a id="macs-as-http-message-signatures"></a>

## 5.4 MACs as HTTP Message Signatures

A MAC is an [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421) HTTP Message Signature using `hmac-sha256` ([§3.3.3](https://www.rfc-editor.org/rfc/rfc9421#section-3.3.3)), keyed with `shared_secret`. If an `alg` parameter is present, it must be `hmac-sha256` \[spec\]. Methods that return a commit or a single record require one when called with a space credential.

The syncer asks for a MAC with `Accept-Signature`. The `tag` names the **profile**, which fixes the covered header:

**Reference: MAC profiles** \[spec\]

| Profile (`tag`) | Covered header | Methods |
| --- | --- | --- |
| `atproto-space-commit` | `Atproto-Space-Commit` | `getLatestCommit`, `getRepo`, `listRepoOps` |
| `atproto-space-record` | `Atproto-Space-Record` | `getRecord` |

**Reference: A commit MAC** \[spec\]

The family app asks Ruth’s PDS for her latest commit, after she changed her RSVP.

```http
Accept-Signature: mac=("atproto-space-commit";sf);
  keyid="did:key:zDnaenqFhbY4sffBMz5ZatBohkr8LNNAe1pWTmG6C88rMc477";
  tag="atproto-space-commit"
```

The value is wrapped here for width; on the wire it is one line. The label (`mac`) is the syncer’s choice. `keyid` is the ephemeral key. The request may also carry `alg`, and nothing else \[spec\].

The host responds with the covered header, a signature under the requested label and parameters, and `Accept-Signature` in `Vary`:

<a id="code-5-4"></a>

```http
Atproto-Space-Commit: ver=1,
  repo="did:plc:p4256dosynj6j6tkypz2q2l3",
  space="at:space/did:plc:ejjl2znzqp3ci25dqaslpkk2/com.example.familyUpdates/our-family",
  rev="3n2gtxdkr232p",
  data=:eVD7vKgDQrLKfOvN3VZJHYX0HGz158ocKa5oRd3kaYw=:
Signature-Input: mac=("atproto-space-commit";sf);
  keyid="did:key:zDnaenqFhbY4sffBMz5ZatBohkr8LNNAe1pWTmG6C88rMc477";
  tag="atproto-space-commit"
Signature: mac=:qcuN1a76R+6Aq9Drm6C0aSYroDZp08eeMcArYT+vd/M=:
Vary: Accept-Signature
```

The covered headers are [Structured Field Dictionaries](https://www.rfc-editor.org/rfc/rfc9651#section-3.2), signed with the `sf` flag, so both sides canonicalize them before signing \[spec\]. The signature base the HMAC runs over is therefore:

<a id="code-5-5"></a>

```text
"atproto-space-commit";sf: ver=1, repo="did:plc:p4256dosynj6j6tkypz2q2l3",
  space="at:space/did:plc:ejjl2znzqp3ci25dqaslpkk2/com.example.familyUpdates/our-family",
  rev="3n2gtxdkr232p", data=:eVD7vKgDQrLKfOvN3VZJHYX0HGz158ocKa5oRd3kaYw=:
"@signature-params": ("atproto-space-commit";sf);
  keyid="did:key:zDnaenqFhbY4sffBMz5ZatBohkr8LNNAe1pWTmG6C88rMc477";
  tag="atproto-space-commit"
```

Each entry is one line in the real base; the breaks are for width.

For `getRecord`, the profile is `atproto-space-record` and the covered header carries the full record URI and CID:

**Reference: A record MAC** \[spec\]

Ruth’s changed RSVP, read with `getRecord`.

```http
Atproto-Space-Record:
  uri="at:space/did:plc:ejjl2znzqp3ci25dqaslpkk2/com.example.familyUpdates/our-family/did:plc:p4256dosynj6j6tkypz2q2l3/community.lexicon.calendar.rsvp/3n2gtxdkr222p",
  cid="bafyreiblr6f6oy3zi426nksahddwp4tgsfgedtqk27fyxqtav66kjvwkgu"
Signature-Input: mac=("atproto-space-record";sf);
  keyid="did:key:zDnaenqFhbY4sffBMz5ZatBohkr8LNNAe1pWTmG6C88rMc477";
  tag="atproto-space-record"
Signature: mac=:bR41y+7bxRG0QywwNj6jb+fsh70sdOMUi0tmN9OsRRw=:
Vary: Accept-Signature
```

**Reference: Host rules**

The host ignores requested signatures with other tags. It answers `InvalidSpaceMac` when `Accept-Signature` is missing or malformed, contains more than one request with the profile’s tag, requests other parameters, or has an invalid key \[spec\].

**Reference: Syncer rules**

The syncer requires exactly one signature with the profile’s tag, covering exactly the profile’s header. If the signature has a `keyid`, it must match the request. Then \[spec\]:

- *Commits:* the `Atproto-Space-Commit` fields match the commit in the body (or the STAR metadata from `getRepo`), and `repo` and `space` match the requested repo.
- *Records:* the `uri` matches the request, and the CID computed from the returned record matches the header’s `cid`.
- *On failure:* refresh the author’s DID document and retry with a new keypair.

<a id="credential-binding-signatures"></a>

## 5.5 Credential binding signatures

> *In the family space.* The family app reads Ruth’s, Nora’s, and Jake’s space repos from one PDS, and Marcus’s and Elena’s from another. Each PDS sees the app’s credential when it answers. What stops one PDS from using that credential to read the repos on the other?

A space credential is good across every repo host in the space. As a bearer token, any repo host that received it could replay it to read repos it should not see. So each credential names a key (`cnf.kid`, per [RFC 7800 §3.4](https://www.rfc-editor.org/rfc/rfc7800#section-3.4)), and every request presenting it carries an RFC 9421 `ecdsa-p256-sha256` signature by that key over exactly two components \[spec\]:

**Reference: The credential signature base** \[spec\]

The family app presents its credential to Ruth’s PDS.

```text
"authorization": Atproto-Space-Credential eyJhbGciOiJFUzI1NksiLCJ0eXAiOi...
"atproto-space-audience": did:plc:p4256dosynj6j6tkypz2q2l3
"@signature-params": ("authorization"
  "atproto-space-audience");tag="atproto-space-credential"
```

The signature value is 64 bytes, `r || s`, each half a zero-padded 32-byte big-endian integer, the same encoding as atproto commit signatures. Unlike commit signatures, low-S normalization is not required, and verifiers must accept both low-S and high-S \[spec\]. Libraries tuned for public atproto often reject high-S by default; turn that off here.

The signature covers neither the HTTP method nor the request path (the `@method` and `@path` components in RFC 9421), so it may be reused with the same credential and audience until the credential expires. [Chapter 10](https://atproto.how/atproto-spaces-field-guide/10-operations.md) explains why that is deliberate. The host-side checks are listed in [Chapter 6](https://atproto.how/atproto-spaces-field-guide/6-access-control.md), under presenting the credential.

<a id="verification-order"></a>

## 5.6 Verification order

A syncer reading a repo runs these checks in order:

1. The host accepts the credential and its signature. If it doesn’t, the host returns an error.
2. The commit’s `repo` and `space` match the request. If they don’t, the syncer rejects the response.
3. The MAC verifies, and the covered header matches the commit. If not, the syncer rejects the response.
4. The running LtHash over the records the syncer holds equals the commit’s `data`. If it doesn’t, the copies have diverged, and the syncer recovers with `getRepo`.

<a id="figure-5-1"></a>

**Figure 5.1.** Verification order (diagram on the web page: https://atproto.how/atproto-spaces-field-guide/5-cryptography#figure-5-1)

Only the last comparison establishes that the syncer holds the complete, current repo.

<a id="common-questions"></a>

## 5.7 Common questions

**Do I have to implement any of this?**

If you use a library such as `@atproto/space` or `atproto-space-client`, it signs your requests and checks the responses for you. This chapter is for people writing a library, a PDS, or a syncer of their own.

**Is the data in a space encrypted?**

No. Spaces control who gets a copy, and the servers that handle a space can read its records. HPKE is here for its secret export, which gives the reader and the repo host a shared secret. Nothing is encrypted with it.

**Can I prove to someone else who wrote a record?**

No, and that is on purpose. A MAC convinces the reader who asked for it. That reader could have made the same MAC, so it proves nothing to anyone else.

**What should my app do when a check fails?**

A failed MAC usually means the author’s `#atproto_kem` key changed, so refresh their DID document and retry with a new ephemeral key. A digest mismatch means your copy and the host’s hold different records, so fetch the repo again with `getRepo`.

**Is this safe against quantum computers?**

Partly. The set hash rests on a lattice problem that is believed to resist quantum attack. The key agreement uses P-256, which is not post-quantum secure, and the spec says a future version may swap in a KEM that is, such as ML-KEM.
