ake

package module
v1.0.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 32 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ake

Hybrid post-quantum asynchronous key exchange for Go.

import "edo.dev/ake"

ake is a Go library for hybrid asynchronous authenticated key exchange with mandatory ML-DSA-87 + Ed25519 composite authentication, independent X25519 identity keys, and X25519 + ML-KEM-1024 one-time prekeys. Its optional record package adds in-memory symmetric ratcheting, replay protection, coordinated rekeying, and link recovery. The root package also offers an optional, stateful service for publicly verifiable application statements: every signature requires ML-DSA-87, Ed25519, and a forward-secure XMSS component.

This is an alpha. It requires Go 1.27 or newer; read its package documentation with go doc -all .. The API and wire format may change before v1.0.0, and the construction has not had an independent security audit.

Why this exists

ake originated as an end-to-end security layer for cluster communication carried over mTLS that could not be treated as the end-to-end trust boundary. TLS may terminate in sidecars, gateways, proxies, or service-mesh infrastructure; ake independently authenticates the application nodes and protects records across those intermediaries. In orchestrated and multi-region deployments, nodes join, restart and are replaced independently, so a sender cannot assume its peer is online when it needs to establish a key. The handshake therefore completes from published prekeys, without a round trip.

mTLS remains useful for transport, routing and access control. ake adds node-to-node authentication, asynchronous first-message protection and hybrid post-quantum confidentiality. It does not prevent denial of service, hide routing metadata or protect a compromised endpoint.

If an existing authenticated transport already provides the required application-to-application boundary, that simpler design is usually preferable.

The suite

ake-pq-v1/ML-DSA-87+Ed25519-SHA512-Signed/X25519-4DH/ML-KEM-1024-OTK/HKDF-SHA384/AES-256-GCM

The suite uses the algorithms and parameter sets selected by CNSA 2.0 for its post-quantum and symmetric components — ML-DSA-87, ML-KEM-1024, SHA-384, SHA-512 and AES-256 — while retaining Ed25519 and X25519 as additional classical hybrid components. SHA-384 is the protocol hash and the basis for HMAC and HKDF. SHA-512 prehashes the signed input for the composite signature. These algorithm choices make no claim of CNSA 2.0 compliance for the protocol. NSA CNSA 2.0 FAQ

The session keeps a 48-byte secret and uses HKDF-Expand for its 32-byte AES keys and exports. Record and Link derivations from a 32-byte root use HKDF-SHA384 with zero-salt Extract and one Expand block.

It combines:

  • long-term identities with independent ML-DSA-87, Ed25519 and X25519 keys;
  • a composite-identity-signed medium-term X25519 responder prekey, the signed prekey (SPK);
  • individually identity-signed, single-use hybrid one-time prekey (OTK) records containing X25519 and ML-KEM-1024 public keys;
  • four X25519 DH contributions and one one-time ML-KEM shared secret;
  • an explicit ML-DSA-87 + Ed25519 composite initiator signature over the complete handshake content;
  • transcript-bound HKDF-SHA384, directional AES-256-GCM keys, and exports.

For initiator A and responder B:

DH1 = X25519(IK_A, SPK_B)
DH2 = X25519(EK_A, IK_B)
DH3 = X25519(EK_A, SPK_B)
DH4 = X25519(EK_A, OTK_B)
(KEM_SS, KEM_CT) = ML-KEM-1024.Encaps(MLKEM_OTK_B)

The signature and transcript bind both identities and party ids, every prekey, the ephemeral key, the ML-KEM ciphertext, the deployment context and the AppInfo application label. The exact byte construction is in SPEC.md.

The signing and X25519 identity keys are generated independently. Every signature uses an ake-specific, unregistered ML-DSA-87 + Ed25519 instantiation of the RFC 10073 construction and requires both components to verify. Trust pins cover the complete 2656-byte public identity. To replace an earlier deployment, generate new identities, distribute their complete public values over the trust channel, and publish fresh signed and one-time prekeys. Persist the matching 96-byte private identity and its authenticated public value together for restoration.

RFC 10073 applies here only to the composite signature. Key exchange is ake's own hybrid construction: four X25519 agreements and one ML-KEM-1024 encapsulation, combined by HKDF-SHA384 in the form of the key combiner in NIST SP 800-227 section 4.6.2.

The hybrid OTK path is mandatory. There is no classical-only or compatibility fallback; an empty OTK inventory is an availability failure. The receiver may be offline when the initiator starts, provided the initiator has a fresh verified bundle and one reserved verified OTK record.

FIPS 140-3

ML-DSA-87, ML-KEM-1024, Ed25519, SHA-384, SHA-512, HKDF-SHA384 and AES-256-GCM are standardized algorithms available through Go's cryptographic module; X25519 is not FIPS-approved. ake assembles its composite signature, hybrid KDF and record derivations outside the module's validated service boundary; it computes its HMAC and HKDF layouts itself over the module's SHA-384, outside the module's validated HMAC and HKDF services. It runs only X25519 operations outside FIPS 140-only enforcement. The ake-specific key exchange combines four X25519 shared secrets and one ML-KEM-1024 shared secret with HKDF-SHA384 in the form described by NIST SP 800-227 §4.6.2. The resulting protocol is not itself FIPS validated.

The frozen GOFIPS140=v1.0.0 module does not implement ML-DSA, so ake fails closed there and never falls back to Ed25519-only authentication. An ML-DSA-capable module such as v1.26.0 can execute the suite under GODEBUG=fips140=only; the tests cover both that positive path and the v1.0.0 refusal. Successful execution is not evidence that the selected module revision is validated. A deployment making a validation claim must pin a Go patch release and module revision covered by the applicable certificate. Through Go 1.27.4, GOFIPS140=certified selects v1.0.0, so ake fails closed there as well. CMVP certificate #5581 covers the Go Cryptographic Module v1.26.0 built from lib/fips140/v1.26.0-cd900eea.zip, which the released toolchains through Go 1.27.4 do not ship: their v1.26.0 is a different archive. A build that relies on that certificate must report GOFIPS140=v1.26.0-cd900eea in go version -m.

Do not combine GODEBUG=cryptocustomrand=1 with FIPS 140-only mode. It asks Go to use the mutable crypto/rand.Reader for key generation where supported and is outside this project's FIPS randomness assumptions. SPEC §17 gives the algorithm-boundary and randomness details.

Security model

Under the assumptions in the specification, the construction is intended to provide:

  • authentication of the responder's published prekeys and the initiator's signed handshake content under the complete pinned identities;
  • confirmation of responder key possession when the initiator opens the responder's first authenticated reply;
  • resistance to initiator impersonation from signed-prekey compromise alone;
  • classical first-message forward secrecy after the one-time X25519 private key is irrecoverably erased, against later compromise of stored identity and prekey keys, not of a running process's memory;
  • post-quantum forward secrecy of each handshake's first record after the one-time ML-KEM private key is irrecoverably erased, under the same compromise model;
  • hybrid confidentiality while either the complete X25519 contribution or ML-KEM-1024 remains secure in the stated model; the quantum result is harvest-now-decrypt-later confidentiality for the initiator's first record: an active classical handshake phase followed by an offline quantum attacker with no further protocol oracles (SPEC §17);
  • no directory-induced downgrade to a weaker handshake.
  • forward security for statement signatures: after an authoritative signing state advances and its superseded copy is irrecoverably erased, later compromise of the current state does not enable signing new statement content at an earlier XMSS position, under the assumptions and storage contract in SPEC section 20. It does not promise unique signature bytes for content already signed there.

Important limits:

  • Identity trust is external. A signature does not decide which identity key belongs to a name.
  • Until the initiator has opened the responder's first reply, it has no proof that the responder is present. Do not release peer-dependent secrets or authority before then.
  • The OTK tombstone store is authoritative security state. Storage rollback can re-enable replay and key reuse.
  • A forgery of new signed content requires defeating both signature components or finding a collision in the signed hashes. Against a quantum attacker the signature assumption rests on ML-DSA-87. If an attacker has the responder's signed and one-time private prekeys, confirmation of the responder's key possession still depends on classical DH2 (SPEC §17).
  • Explicit initiator signatures are transferable evidence; this construction does not provide deniability.
  • The root package is an AKE, not a messaging protocol. The record package adds an in-memory symmetric ratchet, replay window and coordinated rekey, but no automatic DH ratchet, metadata protection, transparency service or durable state. A restarted process performs a fresh handshake.
  • Rekeying restores record confidentiality only when the fresh handshake and the carried rekey secret have not both been compromised. It does not repair a compromised endpoint or identity key; see the record package documentation and SPEC §17.
  • Key erasure is best effort in Go.
  • Statement signatures are transferable notary-style evidence, not trusted time, threshold signing, or a wallet policy. They require a durable, rollback-resistant backend that atomically advances each XMSS position. The service refuses to run in FIPS 140-only mode because its software XMSS implementation is not an approved SP 800-208 service.
  • The ProVerif models, the CryptoVerif games and cross-implementation tests are assurance layers, not a substitute for independent cryptographic review.

Choosing an API

Need Use Survives a receiver restart
One queued message with its own handshake Envelope Yes, while its private prekey state remains durable and its signed prekey is retained
A managed live connection that replaces lost channels record.Link It builds a new channel; undelivered records from the lost channel are gone
An application-managed channel lifecycle record.Driver No; the application establishes a new channel
Custom record framing and rekey coordination record.Channel No; the application establishes a new channel
Publicly verifiable, forward-secure application statements PrepareStatementKey, StatementSigner, and VerifyStatement Yes, through an application backend satisfying StatementBackend

A record channel lives only in memory. Restoring its keys would risk reusing a message key or accepting a replay. A record.Link replaces a lost channel and reports when it did; the application seals again what the peer has not acknowledged (SealNumbered and OpenedAt give each record's position). Do not put a record channel behind a durable queue.

An envelope costs one OTK and opens only while the receiver still holds the signed prekey it names. Keep a queue's retention shorter than the grace period for the previous signed prekey, less the age of bundles senders use. While the OTK is live, compromise of its X25519 and ML-KEM private state removes the post-quantum route, but classical recovery still needs the receiver identity scalar or the sender's ephemeral scalar. Protection against full receiver-key compromise begins only after the OTK is consumed, not while the envelope waits.

This is not a group protocol. Applications that distribute a group key decide how long to retain old keys and how membership changes authorize a rekey. The group example in internal/reference derives its per-sender key with zero-salt HKDF-SHA384 from the 32-byte epoch key. The formal analysis covers the handshake and record stack.

Getting started

The package documentation and SPEC.md are the references. The basic flow is:

  1. The responder creates an identity, a signed prekey and signed hybrid OTK records, stores their private halves durably and publishes the public bundle.
  2. The initiator verifies the bundle and OTK against an identity it already trusts, calls Initiate, and seals the first record with the returned Session.
  3. The responder calls Accept, then opens that first record through the returned PendingSession. The OTK is consumed before a session is released.
  4. The initiator confirms the responder by opening its first reply. For ongoing traffic, both endpoints give their sessions to the same level of the record package.

Statement signing is a separate service. The signer prepares an independent hybrid statement key, publishes its opaque private state through a StatementBackend, and distributes the identity-certified public certificate. Verifiers pin the initial certificate with VerifyStatementKey. Each call to SignStatement uses a durable application operation id; an exact retry returns the same committed signature instead of consuming another XMSS leaf. A rotation uses SignStatementSuccessor, and verifiers accept it with VerifyStatementSuccessor before replacing their durable StatementKeyPin. The signed statement contains whatever timestamp or transaction fields the application chooses, but the signature itself supplies neither trusted time nor transaction semantics.

Complete runnable examples are in example_test.go, example_envelope_test.go, persistence_example_test.go, record/example_test.go, record/example_link_test.go, prekey/example_test.go, and prekey/example_accept_test.go. The complete statement-signature flow and its illustrative in-memory backend are in example_statement_test.go; production statement backends must additionally make the durability, fencing, erasure, and backup promises in StatementBackend and SPEC section 20. The three-member composition of shared group encryption with independent, attributable statement keys is in internal/reference/statement_cluster_example_test.go.

Integration requirements

  • Trust. The application supplies the expected identity key. A bundle signature authenticates a bundle only relative to that trust decision.
  • Rollback. Persist VerifiedBundle.Timestamp() and pass the floor back as VerifyOptions.MinTimestamp. An unset MinTimestamp (the zero time.Time) disables rollback detection.
  • Context. AppInfo is public on the wire; use an opaque channel binding, never a secret or personal data. Handshake Context, party ids and AppInfo are 1 to 255 bytes of valid UTF-8. Envelope application info is 1 to 239 bytes and must not begin with the reserved prefix ake-envelope-v1/.
  • OTK consumption. OneTimePreKeyStore.TakeAndTombstone must be one atomic, durable transaction with at most one winner. A tombstone must survive every restore and replica recovery. This is the integration boundary that carries replay and single-use security.
  • Prekey lifecycle. The prekey package coordinates staged publication, one grace epoch, replenishment and retirement through an application backend. That backend still supplies atomicity, idempotence and durability.
  • Failed first records. Retain a failed PendingSession in a cache bounded by time and by number of entries, and route a retransmission of the same authenticated initial-message content to that entry. Use InitialMessage.Digest, which hashes through the ML-KEM ciphertext and excludes the randomized signature witness. It does not include the external Context, responder identity or reconstructed prekey public keys, so a cache shared across receivers or deployments must also bind its receiver, Context, and trust/prekey scope. Accepting the handshake again finds the OTK tombstoned.
  • Records. A Session supplies authenticated encryption but no ordering or replay protection. Use record.Link unless the application deliberately manages record.Driver or record.Channel itself. Both endpoints use the same level.
  • Errors. The package comments give an action for every sentinel. Drop unauthenticated input without telling the peer which error occurred.
  • Statement state. StatementBackend is authoritative security state, not a cache. It serializes signing, commits the next opaque state and receipt atomically, preserves idempotent operation receipts until retirement, and prevents restoration through journals, replicas, snapshots, and backups. Persist a successor certificate, its operation id, and the transition intent before the irreversible final-leaf authorization. If a provisioning process is lost before activation is reconciled, destroy and tombstone that staged key and provision a fresh one; a recovery worker must not activate it.

For one illustrative type implementing both prekey.Backend and OneTimePreKeyStore, see internal/reference/backend.go. It is reference source to copy and adapt, not an importable or production package.

Repository map

  • ake (root): identities, prekeys, bundles, handshakes, sessions, envelopes, forward-secure statement signatures, wire encoding and persistence.
  • record: authenticated records, replay and ordering, symmetric ratchets, coordinated rekey, Drivers and Links.
  • prekey: checked signed-prekey rotation and OTK replenishment.
  • internal/reference: repository-only illustrative integrations: a managed prekey/store lifecycle, a confirmed record channel, a pair of links with their handshakes and timers, acknowledged in-order delivery over a link, an envelope sent to a managed recipient and a group-control example. It is not public API or a production service.
  • conformance: a separate module that uses CIRCL to reproduce the ML-DSA-87 signature components and compare ML-KEM-1024, and exercises selected public-API refusals and concurrency properties.
  • formal: the computational argument, CryptoVerif games, ProVerif models and bounded TLA+ Link and statement-state models, each with a manifest that identifies its checked sources and recorded results where applicable.

Verification

  • Known-answer vectors cover the handshake, Envelope, initial session records, record channels, Driver frames, Link frames, and the evolving XMSS key and statement framing. Separate Python generators re-derive the classical and record-layer values in CI; the handshake script takes ML-DSA and ML-KEM values from the fixture.
  • The conformance module reconstructs all three handshake signed statements in each of the seven cases. It also reconstructs statement-key certificates, ordinary statement signatures, and successor authorization; CIRCL and the standard library verify their static components, while an independent RFC 8391 verifier checks XMSS.
  • ML-KEM-1024 key generation is checked against one NIST ACVP key-generation case. The independent CIRCL implementation, itself checked against one NIST ACVP encapsulation case, must interoperate with this implementation in both directions.
  • Fixed signature-refusal vectors, malformed-wire tests, persistence models, race tests, fuzz targets and concurrency tests exercise the Go implementation.
  • Twenty-eight CryptoVerif games prove selected handshake, Session-record, ratchet, rekey, Link-derivation and statement-signature steps in the computational model, each with a bound that CryptoVerif derives from the interfaces the game names. Some interfaces are stronger than the computational note's premises, no game sums the routes of a handshake, and none models the Go implementation. See formal/cryptoverif/README.md and formal/cryptoverif/RESULTS.md.
  • Bounded TLA+ models check the Link's offer/answer/echo/ready/confirmation convergence core for two endpoints and any number of attempts, under no message loss, weak fairness for each endpoint's starts and timeouts, weak fairness for each message and progress-sensitive deadline premises; it needs no fairness of expiry. These premises are sufficient, and relaxing any one of them admits a behaviour that never converges. It omits resends, the abandoned record, probes, hints, rebuilds, rekey and numeric timers, is not an unbounded model of all Link rules and is not a refinement of the Go code. See formal/temporal/README.md. A separate bounded statement-state model checks the Stage--erase--Activate order, monotonic position/receipt transitions and tombstones; controls admit orphan activation and rollback and violate their named invariants.
  • Twenty-eight ProVerif models cover the documented authentication, secrecy, compromise, rollback, envelope, statement and record-control boundaries. Some checks are structural or bounded, and the models verify the construction rather than the Go implementation. See formal/proverif/README.md and formal/proverif/RESULTS.md for their exact scope.
  • ProVerif, CryptoVerif and TLC are run manually when the protocol or their models change. CI pins each source manifest and requires its results record to name that exact manifest.

Contributing and security

See CONTRIBUTING.md before proposing a change. Report security issues privately as described in SECURITY.md.

Licensed under the Apache License 2.0.

Development

Development of ake is human-directed, with AI tools supporting design analysis, implementation, testing, formal modeling and documentation. AI-assisted analysis does not constitute an independent security audit. Changes remain subject to human review and verification.

Documentation

Overview

Package ake implements a signed, asynchronous authenticated key exchange with mandatory hybrid X25519 + ML-KEM-1024 one-time prekeys.

It implements exactly one suite:

Suite = "ake-pq-v1/ML-DSA-87+Ed25519-SHA512-Signed/X25519-4DH/ML-KEM-1024-OTK/HKDF-SHA384/AES-256-GCM"

The construction uses complete identities with independent ML-DSA-87, Ed25519 and X25519 keys, a composite-identity-signed medium-term X25519 prekey, and an individually composite-signed hybrid one-time prekey containing X25519 and ML-KEM-1024 public keys. The initiator contributes an ephemeral X25519 key, encapsulates to the one-time ML-KEM key, and signs a commitment to the complete handshake. There is no 3DH, unsigned-OTK, or classical-only fallback.

Construction

For initiator A and responder B, the classical contribution is:

DH1 = X25519(IK_A,  SPK_B)
DH2 = X25519(EK_A,  IK_B)
DH3 = X25519(EK_A,  SPK_B)
DH4 = X25519(EK_A,  OTK_B)

The identity X25519 keys used by DH1/DH2 are independent of the two signature keys. SPK, EK and OTK are native X25519 keys. ML-KEM-1024.Encaps(MLKEM_OTK_B) supplies KEM_SS. The ML-DSA-87, Ed25519 and X25519 identity keys are generated independently; no signing key is converted into a DH key. HKDF-SHA384 derives the session secret from all four DH values and KEM_SS; its info binds Suite, the signing context, application info and transcript hash. See SPEC.md for the exact byte encoding.

The transcript commitment and initiator signature bind both party ids, both raw identity encodings, the signed-prekey id and full public value, the one-time-prekey id and public material, the ephemeral key, the KEM ciphertext, context and application info. Session AEAD and Export bind the resulting transcript hash automatically.

A context, a party id and an application info are text: each is 1 to 255 bytes of valid UTF-8, signed and compared as its bytes with nothing normalized. A value that is not valid UTF-8 is refused wherever it enters: with ErrUsage from the caller, in SignParams, VerifyOptions, InitiateOptions and AcceptOptions and in a value given to Marshal, and with ErrWire or ErrInvalidMessage from a peer, by the Unmarshal functions and by Accept. A Bundle is the exception when it was built in memory and not returned by UnmarshalBundle: Bundle.Verify compares its PartyID with the expected one, which is valid UTF-8, so a PartyID that is not valid UTF-8 is reported as ErrKeyMismatch, another party than the one expected. Accept likewise reports an initiator or responder id that is empty or too long, in a message built in memory, as ErrKeyMismatch.

Trust and publication

A Bundle contains only B's identity and signed medium-term X25519 prekey. OneTimePreKey is a separate signed public record, allowing a directory to reserve one without rewriting the bundle. Unmarshal methods validate only framing. Bundle.Verify requires the caller's expected party id and trusted identity, plus an explicit freshness policy, and returns an immutable VerifiedBundle. OneTimePreKey.Verify returns a VerifiedOneTimePreKey bound to that bundle's signed-prekey epoch. Its public contents are immutable, while its initiation capability is single-use across all copies.

The package does not decide how an identity becomes trusted. Applications need a PKI, transparency system, authenticated directory, or deliberate pinning policy. A self-signature alone does not bind a public key to a name.

Initiation and acceptance

Initiate accepts only verified values and produces a Session plus an InitialMessage carrying public, wire-visible AppInfo. AppInfo must not contain secrets or personal data. Accept requires the caller's expected AppInfo as well as its expected initiator id and trusted identity key. It checks the message's public encodings, looks up the selected OTK record, verifies the initiator's mandatory ML-DSA-87 + Ed25519 composite signature over authenticated content that holds that record, re-verifies the retained signed prekey, verifies the stored OTK record, then asks OneTimePreKeyStore to atomically consume the exact record with a digest compare-and-swap. Only after that durable boundary does it use private OTK material and return PendingSession.

PendingSession means that the initiator's identity signature is valid but possession of the derived session key is not yet confirmed. Open confirms it by authenticating the initiator's first record and promotes the state to a Session. An external record layer can use ExportUnconfirmed once, but must not release secrets or grant authority until its own confirmation succeeds. The initiator may similarly consume its Session into record.NewChannel before it receives a responder reply, but must treat the first authenticated inbound record as key confirmation and withhold peer-dependent authority until then.

Replay and rollback

The receiver's OneTimePreKeyStore is a security boundary. Lookup permits rejecting forged public messages without burning a key. TakeAndTombstone must atomically remove the matching private record and durably record a non-expiring tombstone before returning it. Restoring private material must never override a newer tombstone. If authoritative state is rolled back, replay can derive the same key despite the API's compare-and-swap. Stores should return a nil private pair on error. Accept defensively assumes ownership of, and zeroes, any non-nil pair returned together with an error.

A directory can exhaust or withhold OTKs, causing denial of service, but it cannot make this suite fall back to a weaker exchange. Applications still need message-level replay protection for established sessions and rollback protection for session state and nonce budgets. Lookup also necessarily reveals whether a named OTK id is active; deployments that treat that metadata as sensitive must protect the resulting existence oracle outside this package.

Security properties and limits

Under its stated assumptions, the design is intended to provide asynchronous authentication and forward-secrecy properties analogous to those of Signal X3DH and PQXDH, not interoperability with either. Explicit initiator signatures prevent signed-prekey compromise alone from impersonating an initiator. The one-time X25519 and ML-KEM private keys give classical and post-quantum forward secrecy to each handshake's first record once both are erased and cannot be restored, against a later compromise of stored keys and not of a running process's memory.

The hybrid derivation is designed so the session remains secret if either the full X25519 contribution or ML-KEM-1024 remains secure in the stated model. Its quantum result is harvest-now-decrypt-later confidentiality for the initiator's first record: an active classical handshake phase followed by an offline quantum attacker with no further protocol oracles (SPEC.md section 17). Under the complete pinned identity, forging new signed content requires defeating both signature components or finding a collision in the signed hashes. Against a quantum attacker the signature assumption rests on ML-DSA-87. Responder key possession can still rest on the classical DH2 route under the compromise qualifications in SPEC.md section 17.

This is an AKE, not a messaging protocol. The core package provides no ratchet, post-compromise recovery, identity directory, transparency log, metadata protection, durable store, or group protocol. The record subpackage adds a process-lifetime symmetric ratchet, replay window, and an explicitly coordinated two-input rekey, but no durable replay state or automatic DH ratchet. The construction has ProVerif models, CryptoVerif games and cross-implementation tests, but that is not a substitute for independent cryptographic review. Compromise of responder prekey state is not repaired until the responder publishes a fresh signed prekey and replaces its entire OTK inventory, including retained grace or reserved keys. Identity-key compromise requires out-of-band identity replacement through the application's trust system.

Explicit composite initiator signatures are transferable evidence. Applications that require deniability need a different protocol construction.

The asymmetric keys the package generates, and the nonces of Session.Seal and SealEnvelope, come from the generator of Go's cryptographic module, its SP 800-90A DRBG in FIPS mode and the operating system's generator otherwise: crypto/mldsa draws each ML-DSA identity and statement key and each production signature's hedging randomness; crypto/ed25519 draws each Ed25519 identity and statement key; crypto/ecdh each identity, signed-prekey, one-time-prekey and ephemeral X25519 key, crypto/mlkem each ML-KEM key and the randomness of each encapsulation, and the AES-GCM of cipher.NewGCMWithRandomNonce each nonce, and none of them consults crypto/rand.Reader, whatever that variable holds. The GODEBUG setting cryptocustomrand=1 is the exception: with it, crypto/ed25519 and crypto/ecdh draw the identity and X25519 keys from crypto/rand.Reader as that variable is at the call. The three statement XMSS seeds are filled directly into caller-owned arrays from a separate capture of Go's default cryptographic reader. Statement-key preparation refuses if that reader was replaced before package initialization or its Go 1.27 concrete type is no longer recognized; a later assignment cannot redirect it. The public values the package draws from a reader itself are each one-time-prekey identifier and each statement-key creation identifier, neither of which keys anything: they come from the reader that the variable crypto/rand.Reader held when this package was initialised, which is the operating system's random generator, passed through Go's SP 800-90A DRBG in FIPS mode, unless something replaced it before then. An assignment to crypto/rand.Reader made earlier, by a dependency or by any package initialised before this one, is therefore followed there; one made later is not. The record package takes the reader in the same way, when it is initialised, for public values of its own: a Link's salts and its confirmation, probe and attempt nonces, and the jitter of its timers when LinkOptions.Rand is not given or does not supply the bytes a draw takes with no error or with plain io.EOF on its final read; the IVs of its records are drawn by Go's cryptographic module as a Session's nonces are. A generator that is replaced or weakened for the whole process, a reader put in its place before these packages are initialised, and a reader put in crypto/rand.Reader in a process run with cryptocustomrand=1 are outside what the claims above cover.

Sessions

Session derives distinct AES-256-GCM keys for each direction. Seal draws a random 96-bit nonce and enforces a per-session invocation budget; Open does not enforce ordering or replay. Binding exposes SHA-384 over framed Suite, context, application, party ids and identity keys for constraining fresh-session rekeys. It identifies that peer/application tuple, not one channel instance; parallel channels must use distinct application labels. ConsumeExport atomically transfers one exported root and closes the Session when duplicate initialization would be unsafe. Export is the preferred reusable integration seam for a caller-owned ratchet because it adds explicit label separation and direct Suite/transcript framing. The raw session secret is not exposed. Five labels are reserved for the record package. "ake-record-root-v1", from which record.NewChannel takes its keys, is refused by Export and ExportUnconfirmed and taken by ConsumeExport, which closes the Session. "ake-record-rekey-input-v1", which Channel.StageRekey and Channel.AddRekeyCandidate take, and "ake-record-channel-tag-v1", "ake-record-link-refusal-v1" and "ake-record-link-root-v1", from which a record.Link keys its channels, are refused by Export, ConsumeExport and ExportUnconfirmed alike.

Choosing how to use it

The package authenticates two parties and gives them a key. What is built on that depends on what the traffic looks like.

An Envelope carries one message with its own handshake. It needs nothing in memory on either side, so it is the form for occasional messages, for messages that wait in a queue, and for anything that must reach a party that may restart before reading it.

A Session, and the record package's Channel, Driver and Link built on one, carry sustained traffic between two running processes. Use record.Link unless the application replaces lost channels itself: it keeps one channel toward a peer, carries out the rekeys the application starts, and builds a new channel when that one is lost. All of them exist only in memory: a party that restarts has lost them, cannot read what was sealed for it before, and needs a new handshake, which a Link asks for. They are the wrong form for a durable queue.

A key shared by more than two parties is the application's. This package has no group key, no broadcast encryption and no membership protocol. It can deliver a key the application manages to each member, in an Envelope or over a Channel, and the application decides who holds which key and for how long.

The statement-signature service is independent of a handshake or Session. It certifies an application-scoped public key with an Identity, then signs each statement with ML-DSA-87, Ed25519 and one leaf of an evolving XMSS-SHA2_10_256 key. The result is publicly verifiable and transferable. It is not a threshold signature, a wallet policy, a transparency log or trusted evidence of time. The application defines and canonically encodes the statement whose bytes it gives SignStatement.

A StatementBackend is authoritative security state. PrepareStatementKey generates a key and StatementProvisioning.Publish stages and activates its opaque private state. SignStatement advances that state in one atomic transaction before returning a signature; an exact retry with the same nonzero StatementOperationID returns the stored receipt. A backend must fence every writer and make superseded states inaccessible through its active row, journal, replicas, snapshots and backups. A local checksum detects damage, not rollback. If a provisioning process is lost before activation is reconciled, recovery destroys and tombstones the staged key and provisions a new one; it does not activate the orphan.

VerifyStatementKey accepts only an initial certificate under an independently trusted Identity, context and scope. The application calls Pin on the returned VerifiedStatementKey and stores that StatementKeyPin against rollback. SignStatementSuccessor uses the predecessor's reserved final XMSS leaf to authorize exactly one next certificate; the exact certificate, operation id and transition intent are stored before that irreversible call. VerifyStatementSuccessor verifies the lineage before the application atomically replaces its pin. Verification is otherwise stateless: replay, authorization and monotonic-position policy belong to the application.

After a committed state at position i and irrecoverable erasure of every superseded copy, compromise of the current state permits positions i and later but not a signature on new statement content below i, under the assumptions in SPEC.md section 20. The claim is about signed content, not unique signature bytes for content already signed at that position. Rollback or cloning can reuse an XMSS leaf and voids that property. The statement service refuses while FIPS 140-only enforcement is active because its software XMSS implementation is not an approved SP 800-208 service.

One-shot messages

SealEnvelope and OpenEnvelope carry one message with its own handshake and keep no state on either side afterwards. An Envelope can wait in a queue for a recipient that is offline or restarting, provided the recipient's signed prekey and one-time prekeys are durable, and it opens at most once. Use it for occasional messages, for delivering a key the application manages, and for anything that must survive the recipient losing its memory; a Session, and the record package built on it, live only as long as the two processes do. Each Envelope costs a handshake and one of the recipient's one-time prekeys, so a recipient can have as many waiting for it as it has published one-time prekeys.

The sender's signature covers the Envelope's authenticated content, the handshake and the sealed record, and OpenEnvelope verifies it before it consumes the one-time prekey. Changed authenticated content or an invalid signature is refused with nothing consumed, and the genuine Envelope still opens afterwards. Another valid randomized signature witness over identical content is an equivalent delivery and may consume the one-time prekey first. Only a party able to make the composite signature of an accepted sender can authenticate different content that reaches the durable take.

That holds while every identity the recipient accepts envelopes from has at least one uncompromised signing component. A one-time prekey is not bound to a sender: a second sender that the recipient also accepts, and that has the public record of the one-time prekey, can sign a copy of another sender's envelope in its own name, and a recipient that opens the copy as the second sender's consumes the one-time prekey, after which the genuine Envelope cannot open. A recipient that expects one sender for what it opens refuses such a copy with nothing consumed.

An Envelope does not wait indefinitely. It opens only while the recipient still holds the signed prekey it names: the current one, or the previous one until the recipient retires it. A sender may have built it from a bundle fetched just before the recipient rotated, so a queue's retention has to be shorter than the time the recipient keeps a previous signed prekey, less the age of the bundle the sender used. After that the envelope cannot be opened by anyone: a recipient using the prekey package gets prekey.ErrEpochUnavailable from Manager.WithSignedPreKey, and one that passes another signed prekey gets ErrAuthentication. While it waits, an Envelope has no forward secrecy against a later full compromise of the recipient's identity X25519 key and the named signed- and one-time-prekey private state; that begins when the one-time prekey is consumed. Compromise of the prekeys alone removes the post-quantum route but leaves DH2 against a classical attacker unless the recipient identity scalar or sender ephemeral scalar is compromised too.

An envelope's handshake and the handshake of a Session are kept apart by the library. The application info given to SealEnvelope travels behind a reserved prefix that Initiate and Accept refuse, so neither is accepted in place of the other, even when an application uses one application info for both, and the attempt consumes no one-time prekey. An envelope's application info is therefore at most MaxEnvelopeAppInfoLen bytes, and Envelope.AppInfo returns it from a received envelope. A recipient may read it to select a locally configured route, but authorizes that route independently and passes the route's configured value to OpenEnvelope as ExpectedAppInfo. It does not authorize a sender-selected value by comparing it with itself. An empty result means that this is not an envelope the recipient can open: it refuses it without calling OpenEnvelope, which would report the empty value as the caller's mistake, an error matching ErrUsage.

Persistence and erasure

Identity.Private, SignedPreKeyPair.Private and OneTimePreKeyPair.Private return caller-owned copies for authenticated persistence. Restore methods derive public values from the private material and verify the stored signatures against the expected public records. The authoritative store must additionally enforce tombstones and rollback floors. Exported secret copies are the caller's responsibility to protect and clear. The exported field names of SignParams, Bundle, OneTimePreKey, SignedPreKeyRestoreParams and OneTimePreKeyRestoreParams are part of the current suite's storage contract when a deployment keeps these values with encoding/gob or encoding/json. Stored forms from another suite are not compatibility inputs. The context and the party id in them are valid UTF-8, so both encodings read back the bytes that were signed. A stored JSON form that was damaged, so that one of them is not valid UTF-8 when it is read, is not refused as text: encoding/json puts U+FFFD in place of the bytes it cannot decode, the library is handed another identifier that is valid, and the fault shows as a signature or a key that does not match. A signed prekey is signed, and restored, only for a timestamp within the years 1 to 9999 UTC. encoding/json refuses to write a time.Time of a year before 0 or after 9999, and writes one of the year 0: a Bundle decoded from the wire can carry a second of such a year, and encoding/json then refuses to write that Bundle.

Every fixed-size byte value of a wire, restore or stored form, and every fixed-size public value the API returns, but the signatures, the nonces, IdentityPrivateKey and the ML-KEM seed, which are byte slices (below), is of a type with a text form, its bytes in order as lower-case hexadecimal, which MarshalText writes and UnmarshalText reads back and nothing else: PublicIdentity, X25519PublicKey, X25519PrivateKey, MLKEMEncapsulationKey, MLKEMCiphertext, EnvelopeDigest, InitialMessageDigest, OneTimePreKeyDigest, SessionBinding, StatementKeyID, StatementOperationID, StatementCreationID, StatementDigest and StatementPublicKey, and in package prekey BatchID and in package record ConfirmationTag, ChannelTag and LinkOptionsDigest. SignedPreKeyPair.Private and OneTimePreKeyPair.Private return an X25519PrivateKey and an MLKEMSeed, the types a restore form holds them in, and Session.Binding a SessionBinding, which is a public value. The secrets the API hands out for use at once are bare arrays: the exports of Session.Export, Session.ConsumeExport and PendingSession.ExportUnconfirmed. encoding/json and encoding/json/v2 write each such value as its text, a string, also as the key of a map, so each reads what the other wrote, and each refuses any other string and any value that is not a string, an array of numbers included, except null, which neither refuses. What null and a refused value leave behind differs. encoding/json leaves a value by itself, a field of a struct and an element of a slice within its length as they were, for null and for a refused value alike, but sets the value of a map to zero for null and for a boolean, a number, an array or an object. For a refused string it leaves the value of a map as it was when it is built without GOEXPERIMENT=jsonv2, and sets it to zero when it is built with that experiment, as Go 1.27 builds it by default. encoding/json/v2 sets a value it reads null into to zero, wherever it is, and sets an element of a slice to zero before it reads into it, so a refused element is zero. encoding/json reads the elements of a slice into the memory the slice already holds, past its length as well, up to its capacity, so an element it reads null into there keeps what an earlier value left. A reader that needs a value decodes into a fresh one and checks that it is not zero. A private key is not the key of a map: encoding/json/v2 names the key of a map value it refuses in its error, as text, for a value its UnmarshalText refuses, one its Go type cannot hold, a literal that is not JSON and input that ends within the value alike. encoding/json built with GOEXPERIMENT=jsonv2, as Go 1.27 builds it by default, names it for a value the Go type cannot hold, such as a number where a string belongs, a string where a number belongs, 1.5 for an int or 1000 for an int8, and not for a value its UnmarshalText refuses, a literal that is not JSON or input that ends within the value; built without that experiment it names it for none of these.

The signatures, the nonces, IdentityPrivateKey and the ML-KEM seed, of type MLKEMSeed, are byte slices, which both write as base64. The nonces are Envelope.Nonce and the nonce that Session.Seal, record.SealHandshakePurpose, record.SealLinkPurpose and record.Link.SealPurpose return.

What a deployment relies on is this: for the stored forms whose files the tests of this module hold, encoding/json and encoding/json/v2 write the same bytes, and each reads back what either wrote. Elsewhere the two packages differ in more ways than this documentation lists. The differences below are those that bear on a stored form of this module, and its tests hold each of them; they are not all the differences between the two packages.

In what they write: encoding/json writes a nil slice as null, and encoding/json/v2 as an empty string for a byte slice and an empty array for any other, so the two write different bytes for a value that holds one, a Bundle with no signature or a prekey.PrivateReplenishment with no one-time prekeys among them. encoding/json writes each of the characters <, >, & and U+2028 and U+2029 of a string, such as a context or a party id, which may hold any valid UTF-8, as a JSON escape, a backslash, the letter u and four hexadecimal digits, and encoding/json/v2 writes them as they are. encoding/json/v2 has no form for a time.Duration and does not write the structs that hold one, VerifyOptions, record.DriverOptions and record.LinkOptions; encoding/json writes a duration as its number of nanoseconds.

In what they read: encoding/json reads a duration from its number of nanoseconds, and encoding/json/v2 refuses to read one. encoding/json reads one of these byte slices from a JSON array of numbers, one for each byte, as well as from base64, and encoding/json/v2 refuses the array. encoding/json skips the line breaks, carriage returns and line feeds, in the base64 of one of these byte slices, and encoding/json/v2 refuses them. encoding/json takes a member for a field whose name differs from the member's only in the case of its letters, as the long s, U+017F, differs from s, and encoding/json/v2 ignores such a member. encoding/json reads a member given twice into its field twice, so that the later string replaces the earlier, the members of two objects are merged and a later null leaves the earlier value, and encoding/json/v2 refuses the object. encoding/json reads a string that is not valid UTF-8, or that holds an escaped surrogate that is not one of a pair, with U+FFFD in place of what it cannot decode, as above, and encoding/json/v2 refuses it. encoding/json reads a time whose offset from UTC is +24:00, or whose fraction of a second follows a comma, and encoding/json/v2 refuses both.

encoding/gob does not use the text form and writes the bytes. These encodings are part of the current suite's storage contract. The fmt verbs %v and %s print a value's text form; %x and %X format that text and not the bytes, so print the bytes with v[:]. An X25519PrivateKey prints as "X25519PrivateKey(…)" with every verb but %p and %w, by itself and in an exported field of a struct that holds it, and its String returns the same. An MLKEMSeed prints as "MLKEMSeed(…)" in the same way, and its String and GoString return the same. StatementPrivateState prints as "StatementPrivateState(…)" under the same rules, so no restore or stored form printed whole with a verb other than %p and %w shows a byte of a private value, except where a caller holds the form, a key or a seed in a field that is not exported, or a caller holds a private state there, or fmt reaches a pointer to a struct that holds a key or a seed (all below).

fmt applies %p and %w without consulting the type: it calls no Format, String or other method for them. %p prints the address of a pointer, a slice, a map, a channel or a function, and any other value in fmt's wrong-verb notation, which shows its bytes; %w does the same for a value that is not an error, in fmt.Errorf as elsewhere. So an X25519PrivateKey, an array that holds an MLKEMSeed, and a restore or stored form, print their private bytes with %p and with %w, and an MLKEMSeed with %w; an MLKEMSeed and a pointer print their address with %p. go vet's printf check reports %w with any of these values, and %p with a restore or stored form, and does not report %p with an X25519PrivateKey or an array that holds an MLKEMSeed.

A pointer to a restore or stored form, or to any other struct that holds an X25519PrivateKey or an MLKEMSeed, the caller's own included, that fmt reaches inside the value it prints, as an element of a slice or an array, a key or a value of a map, an element of an []any or an exported field of a struct, fmt prints with %s, %q, %t and every other verb that does not apply to a pointer in its wrong-verb notation, where it calls no method: the private scalars and ML-KEM seeds show byte for byte. With %v, %b, %o, %d, %x or %X, the verbs other than %p that apply to a pointer, it prints the address. A pointer to an X25519PrivateKey or an MLKEMSeed itself shows the mask there, since fmt calls its Format. go vet's printf check reports such a call for a slice of these pointers, and not for an []any. Such a form given to fmt by itself, or through a pointer passed to fmt, shows the masks.

The slog.TextHandler and slog.JSONHandler of log/slog mask these values when the value of an attribute is one of them or a pointer to one, in a group as well: X25519PrivateKey, MLKEMSeed and StatementPrivateState each have a LogValue that returns the same mask, and SignedPreKeyRestoreParams, OneTimePreKeyRestoreParams, prekey.PrivateEpoch, prekey.PrivateOneTimePreKey and prekey.PrivateReplenishment one that returns a group of their fields, the public values as their text forms and the masks in place of the private ones, and reads no private byte. slog takes it before MarshalText and before encoding/json. Give slog a pointer to such a value, not the value: a value given to slog is copied, with each call, into the interface value of its attribute on the heap, a copy that neither LogValue nor the caller can clear; of a pointer only the pointer is copied. fmt copies a value it is given in the same way, and copies the private scalar of a restore or stored form it prints through a pointer as well, as it reads each field into an interface value, so printing one leaves copies that nobody can clear. A nil pointer to one of these eight types makes slog write "LogValue panicked" and a stack in place of the value, which shows no secret. Any other shape, a slice or a map of them or a struct of the caller that holds one, slog.TextHandler formats with fmt and slog.JSONHandler with encoding/json, and their rules hold: fmt masks the private values except where this documentation says it does not, and encoding/json, like any encoder that uses MarshalText or encoding/json, writes a key and a restore or stored form in full, and leaves out a field that is not exported.

The types that hold a private key, or a key derived from one, print as their name and nothing of their state, with every verb but %p and %w: %p prints the pointer's address, and %w the fields one pointer deep, which hold addresses in place of keys. Identity, SignedPreKeyPair, OneTimePreKeyPair, PendingSession and Session print as "Identity(…)", "SignedPreKeyPair(…)" and so on; StatementProvisioning and StatementSigner print as "StatementProvisioning(…)" and "StatementSigner(…)"; record.Channel, record.Driver and record.Link as "Channel(…)", "Driver(…)" and "Link(…)"; prekey.Manager, prekey.Rotation and prekey.Replenishment as "Manager(…)", "Rotation(…)" and "Replenishment(…)". A nil one prints as "<nil>". Their Format reads no field, so printing one never waits for its lock and never races with a call that uses it. Format has a pointer receiver, since these types are used by pointer and hold locks: fmt calls it for the pointer itself and for one held in a slice, a map, an interface or an exported field of a struct.

fmt calls no method of a value it reaches through a field that is not exported of a caller's struct: it prints the fields of that value itself, and follows a pointer there once when the verb does not apply to a pointer, such as %s, %q or %t. Each of the types above keeps every secret it holds two pointers deep: the pointer fmt follows leads to fields that hold addresses in place of keys. Such a field shows at most the fields that hold no secret, such as a Channel's sequence numbers and epochs, and no key; so does a struct value of one of these types, which only a copy gives and go vet's copylocks check reports. The keys, the seeds and the restore and stored forms print raw there: X25519PrivateKey, MLKEMSeed, StatementPrivateState, SignedPreKeyRestoreParams, OneTimePreKeyRestoreParams, prekey.PrivateEpoch, prekey.PrivateOneTimePreKey and prekey.PrivateReplenishment, held by value in such a field, print their private bytes byte for byte with every verb, and with every verb but %p when the struct is printed through a pointer to it, and held by pointer with %s, %q, %t and every other verb that does not apply to a pointer, because the masks of X25519PrivateKey and MLKEMSeed are methods, which fmt does not call there. slog.TextHandler, which formats such a struct with fmt, prints them the same way. A caller that keeps one in such a field does not print the struct, or gives it a Format of its own. The secrets handed out for use at once are bytes, which fmt prints byte for byte, and the caller must not log them: the IdentityPrivateKey byte slice that Identity.Private returns and the exports of Session.Export, Session.ConsumeExport and PendingSession.ExportUnconfirmed.

A field can be added to an exported struct of this module. Every exported struct that has an exported field begins with a blank field, so a composite literal of one compiles in another package only with its fields named, and goes on compiling when a field is added. Those structs are Bundle, OneTimePreKey, InitialMessage, Envelope, SignParams, VerifyOptions, InitiateOptions, AcceptOptions, SignedPreKeyRestoreParams, OneTimePreKeyRestoreParams, StatementKeyParams, StatementKeyPin and StatementKeyCertificate. In package record they are ChannelOptions, RekeyConfirmation, DriverOptions, DriverOutput, LinkOptions, LinkOutput, LinkStatus and RecordPosition, and in package prekey PrivateEpoch, PrivateOneTimePreKey, PrivateReplenishment, PublicEpoch and RestoreState. The blank field is not exported and is in neither stored encoding.

Whether one of those structs can be compared is not part of that promise: the field that is added may be one that is not comparable. A caller does not compare such a struct with ==, use it as a map key, or embed it in a type that is compared or used as a map key. As they are declared, the structs the compiler lets a caller compare are SignParams, VerifyOptions, InitiateOptions, AcceptOptions, StatementKeyParams and StatementKeyPin; in package record, ChannelOptions, RekeyConfirmation, LinkStatus and RecordPosition; in package prekey, RestoreState. Code that compares one of them stops compiling when such a field is added, or panics where the comparison is made through an interface value. Two of them, both in package record, are promised to stay comparable, and any field added to them will be comparable too: RekeyConfirmation, whose fields are its wire form, and RecordPosition, whose fields are what a record's authenticated header and its channel tag say. Beside them, two types of this package that have no exported field are promised to stay comparable: SignedPreKeyID and OneTimePreKeyID, the identifiers a store keys its epochs and its one-time prekeys by. Two identifiers can be compared with ==, and an identifier can key a map.

Zero is best effort. Go and crypto/mlkem do not guarantee complete physical erasure of every compiler, runtime, stack, garbage-collected, or internal library copy. The handshake KDF, directional-key derivations and exports use this package's own fixed-output HKDF-SHA384 implementation, whose outputs are HKDF-SHA384 as RFC 5869 defines it; its tests compare them with crypto/hkdf. It returns no secret-bearing working slice, clears the HMAC pads, inner hashes, pseudorandom key and input-keying-material buffer it owns, and reuses its SHA-384 object for an all-public computation before dropping it. Heap tests with positive controls find no eight consecutive bytes of any of the four DH values, the ML-KEM shared secret, the extracted pseudorandom key or session secret after derivation, and none of the session secret, directional keys or an export after Session.Zero. These are measured best-effort properties, not guarantees made by the Go compiler or runtime. A key this documentation calls scrubbed or erased is cleared in the package's own memory; standard library operations can still retain the copies named below. AES construction can retain expanded key schedules until garbage collection. An ML-KEM encapsulation leaves at least these copies from which its shared secret follows. Some releases of crypto/mlkem return the shared secret as the first half of a 64-byte slice that also holds the encapsulation's randomness, from which, with the ciphertext, the secret can be computed again; this one the package reaches, and the initiator clears the whole slice as soon as it has copied the secret out. The others, as the standard library's source reads, are the encapsulation's message m, which it keeps in a variable on its stack and also encodes as a ring element for the encryption, and the SHA3-512 state the encapsulation hashes m and the hash of the encapsulation key with and then abandons: the sponge holds m as it is, and the shared secret, the first 32 bytes of that hash, follows from m and the public hash of the encapsulation key. This package cannot reach or clear them. An ML-KEM decapsulation, which Accept and OpenEnvelope perform, leaves more, as the standard library's source reads, none of which it clears: the message m it decrypts from the ciphertext, in a 32-byte object of its own; the SHA3-512 state that hashes m with the hash of the encapsulation key; its 64-byte output, the shared secret of a valid ciphertext followed by the randomness of the re-encryption; and the SHAKE256 state that absorbs the decapsulation key's private value z, for the secret of a rejected ciphertext. The shared secret follows from m and the hash of the encapsulation key, which is public. This package cannot reach or clear any of them. crypto/ecdh copies every X25519 private scalar it is given, for each DH and each derivation of a public key, into a key object this package cannot reach, and generates each ephemeral, one-time and signed-prekey scalar in a buffer of its own and in such a key object: the ephemeral, one-time, signed-prekey and independent identity scalars each stay in such an abandoned heap object after the call that used them has returned, also once Zero, or Accept consuming a one-time prekey, has cleared the package's own copy, until the garbage collector reclaims the object and its memory is used again. crypto/ed25519 generates each Ed25519 identity key in memory of its own. For Ed25519, the package clears its owned seed and its 64-byte seed-and-public-key encoding. For ML-DSA-87, it clears its owned seed and overwrites the opaque expanded-key value it owns. The package cannot erase private copies held inside Go's cryptographic module. An Identity signs by handing its private key to crypto/ed25519, which may keep the expanded secret scalar and nonce prefix in memory this package cannot reach: Identity.Zero clears the package's own copy of the key, and no copy crypto/ed25519 keeps. The ML-DSA-87, Ed25519 and X25519 identity inputs are independent. Identity.Zero clears the package's seeds and scalar; no signing-key conversion or derivation of the X25519 scalar from a signing key occurs. Initiate and Accept copy the independent identity scalar, and Accept the signed prekey's, through a pointer into memory they clear on every path out, and Accept runs no hash of the identity's private key. The package's tests scan 262,144 bytes of the stack below the caller of an Accept that refuses a message whose application info is not the expected one, of one that loses the take of the one-time prekey and of one whose context ends during the lookup, on amd64 and on 386, and find there no 8 bytes in a row of the signed prekey scalar, either signing seed or the independent identity X25519 scalar.

Error handling

Drop unauthenticated input reported as ErrAuthentication, ErrInvalidMessage, or ErrWire without reflecting the exact error to the peer. ErrKeyMismatch from Accept belongs with them: Accept compares the message's claimed initiator, identity, responder and application label with the expected values before it checks the signature, so that result is also about unauthenticated input. ErrInvalidSignature from Bundle.Verify or OneTimePreKey.Verify means the directory served a record the trusted identity did not sign for this context: do not use it, fetch again, and check that VerifyOptions.Context is the one the peer signs with. It is not what NewBundle and NewOneTimePreKeys return for a signed prekey that the Identity given with it did not sign: that is the caller's own mistake, and ErrUsage, as it is from Accept and OpenEnvelope, which refuse it before they read the message and without a store call. In peer-verification APIs, ErrSmallOrderKey means a peer-supplied X25519 value was a small-order point: reject that record or message. IdentityFromPrivate documents its distinct local-persistence case. ErrInvalidKey from Bundle.Verify or OneTimePreKey.Verify likewise means the served record carries a malformed key: reject it and fetch again. From Accept it means the message does: drop it. The identity a caller expects, in VerifyOptions or AcceptOptions, is its own input: one that is not a usable identity key, such as the zero value of a field left unset, is ErrUsage. ErrStore is retryable within the request policy but may mean that OTK consumption committed; if the same message then returns ErrAuthentication, restart with a fresh OTK. ErrOneTimePreKeyUnavailable, which the responder sees, means another Accept of the same message won the one-time prekey, or the key's epoch was retired before this one took it: drop this copy. ErrOneTimePreKeySpent, which the initiator sees, means this verified one-time prekey already started a handshake: retransmit the original initial message and first record, or initiate again with a fresh one. Preserve the rollback floor when fetching a new bundle after ErrStaleBundle. ErrKeyMismatch is a binding failure, not a reason to weaken the expected peer or channel. From Bundle.Verify it means the directory served a bundle for another party or identity than the one expected: do not use it. From OneTimePreKey.Verify it means the record belongs to another signed-prekey epoch than the bundle, which is the normal result when a rotation lands between fetching the bundle and reserving the one-time prekey: fetch the bundle again, then reserve a new one-time prekey. The one reserved before is lost to this initiator. Retry a bounded number of times, since a directory that keeps serving mismatched records is faulty or hostile. From Initiate it means the one-time prekey was verified against another bundle than the one passed with it. ErrUsage and ErrZeroed require local caller correction, as does ErrInvalidKey from a call that takes only local key material, such as IdentityFromPrivate or a restore function; ErrSessionClosed and ErrSessionExhausted require a fresh Session.

FIPS 140-3

A handshake, Session and Envelope use ML-DSA-87 (FIPS 204), ML-KEM-1024 (FIPS 203), Ed25519 (FIPS 186-5), SHA-384, SHA-512, HKDF-SHA-384 and AES-256-GCM, and X25519, which is not FIPS-approved. The package assembles its composite signature, hybrid KDF and record derivations outside the module's validated-service boundary. The hybrid key derivation follows NIST SP 800-227 section 4.6.2. The package implements its HKDF and HMAC layouts over the module's SHA-384. Only X25519 operations run inside crypto/fips140.WithoutEnforcement.

The frozen GOFIPS140=v1.0.0 module has no ML-DSA. The package fails closed there and has no Ed25519-only fallback. An ML-DSA-capable module such as v1.26.0 can execute the suite under GODEBUG=fips140=only. The tests cover both that positive path and the v1.0.0 refusal. Successful execution does not establish that the selected module revision is validated; a deployment making a validation claim must pin a Go patch release and module revision covered by the applicable certificate. Through Go 1.27.4, GOFIPS140=certified selects v1.0.0, so the package fails closed there as well. CMVP certificate #5581 covers the Go Cryptographic Module v1.26.0 built from lib/fips140/v1.26.0-cd900eea.zip, which the released toolchains through Go 1.27.4 do not ship: their v1.26.0 is a different archive. A build that relies on that certificate must report GOFIPS140=v1.26.0-cd900eea in go version -m. This package and protocol are not FIPS 140-3 validated.

Do not combine GODEBUG=cryptocustomrand=1 with fips140=only. It explicitly asks Go to use the mutable crypto/rand.Reader for key generation where supported and is outside this package's FIPS randomness assumptions. SPEC.md sections 7 and 17 give the exact algorithm boundary and the security claim attached to each component.

Concurrency

Identity, SignedPreKeyPair and OneTimePreKeyPair are safe for concurrent use, including with Zero: an operation already using private key material completes before Zero scrubs it, or with a working copy it scrubs itself, and later operations that need the private key fail with ErrZeroed. Session methods may run concurrently while live, including with Zero: operations already using key material finish before it is scrubbed, and later operations return ErrSessionClosed. PendingSession is consume-once and must be serialized. Implementations of OneTimePreKeyStore define their own concurrency and durability guarantees; TakeAndTombstone must remain atomic under competing Accept calls.

Nil and zero values

A nil required argument and a nil receiver are caller misuse in this package, record and prekey alike: a function or method with an error result returns an error matching ErrUsage, and never one that says the value was closed or zeroed. The one exception is prekey.Manager.Close, which returns nil for a nil Manager, as the prekey documentation says: closing nothing is not misuse. A context is a required argument like any other: Accept and OpenEnvelope return an error matching ErrUsage for a nil one, before they touch the store. A value whose key material was scrubbed reports its own sentinel instead: ErrZeroed for Identity and the key pairs, ErrSessionClosed for Session and PendingSession, record.ErrClosed for a Channel.

A value that no constructor returned is treated by what it would be used for. As a receiver, a Session, PendingSession, Identity, key pair or record.Channel holds no key material and reports the same sentinel as a scrubbed one. As an argument, such a Session reports ErrSessionClosed and such an Identity reports ErrZeroed, wherever it is used. A key pair, a VerifiedBundle or a VerifiedOneTimePreKey that was never constructed is ErrUsage, like a nil one. The prekey types have no scrubbed state of their own, so a Manager, Rotation or Replenishment that no constructor returned is ErrUsage; prekey.ErrClosed is only for a Manager after Close. prekey.NewManager and prekey.RestoreManager follow the same rule for what they are given: ErrUsage for a signed prekey that was never constructed, ErrZeroed for an Identity that holds no key.

Zero is a no-op on a nil receiver, and an accessor with no error result returns its zero value. No exported method with a pointer receiver panics on a nil receiver. Methods with a value receiver, such as those of SignedPreKeyID and OneTimePreKeyID, cannot be called through a nil pointer, as with any Go value.

Wire format and verification

Bundle, OneTimePreKey, InitialMessage and Envelope have distinct kind bytes (0x01 to 0x04) under wire version 0x01. Decoders reject malformed lengths, trailing data, wrong kinds and unknown versions. Cryptographic verification remains explicit after decoding.

A separate Python standard-library model in testdata/crosscheck re-derives the root KAT's independent X25519 public keys, RFC 10073 representatives, Ed25519 signature components, DH, transcript, KDF, binding and export values and, with an AES-256-GCM of its own, the sealed first records and the Envelope the KAT fixes; it consumes the fixture's ML-DSA and ML-KEM values. ML-KEM key generation is checked against one NIST ACVP case. In the isolated conformance module, CIRCL is checked against one NIST ACVP encapsulation case and then produces a ciphertext that crypto/mlkem must decapsulate to the same secret. In the other direction CIRCL decapsulates ciphertexts that crypto/mlkem encapsulated at random to a one-time prekey of the library, and the ciphertext of a handshake that Initiate made, to the secrets crypto/mlkem holds for them, and the responder then opens the initiator's first record. The library's own encapsulation, given the NIST case's randomness, gives that case's ciphertext and shared secret byte for byte, and CIRCL's for the key-generation case's key. The record package has separate fixed vectors, for a Channel's records and for the frames of a Driver and a Link, generated by a Python script that derives the keys with the standard library and seals with an AES-GCM that is not Go's. Formal models in formal/proverif/ cover secrecy, authentication, forward secrecy, prekey-compromise impersonation resistance and rollback of the handshake, the record layer's rekey procedure, and a Link's new-channel exchange; formal/proverif/README.md says what each is bounded to and what none of them models. CryptoVerif games in formal/cryptoverif/ prove selected steps of the handshake and of a rekey in the computational model, and no game combines the routes of a handshake; formal/cryptoverif/README.md says under which interfaces and what the games leave out. Downgrade is absent by construction and pinned by the single wire suite and KATs.

Example
// SPDX-License-Identifier: Apache-2.0

package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"sync"
	"time"

	"edo.dev/ake"
	"edo.dev/ake/record"
)

// exampleStore keeps one-time prekeys in memory. A tombstone decides: an
// identifier in dead is unavailable to Lookup and to TakeAndTombstone even
// when keys holds a record for it, as it does after a restore that brought
// an older copy of the keys back and kept the tombstones.
type exampleStore struct {
	mu   sync.Mutex
	keys map[ake.OneTimePreKeyID]*ake.OneTimePreKeyPair
	dead map[ake.OneTimePreKeyID]struct{}
	// keyReads and deadReads count the reads of the two maps, for the test
	// that compares the steps of a lookup. recordCopies counts the
	// same-sized record copies made after those reads.
	keyReads, deadReads, recordCopies int
}

var absentExampleOneTimePreKey = ake.OneTimePreKey{Signature: make([]byte, ake.SignatureSize)}

func copyAbsentExampleOneTimePreKey() ake.OneTimePreKey {
	record := absentExampleOneTimePreKey
	record.Signature = bytes.Clone(record.Signature)
	return record
}

// live returns the pair for id, or nil when there is none or id was
// consumed. It reads keys once and dead once before it chooses, so that an
// id that is stored, one that is absent and one that was consumed cost the
// same two reads: Lookup answers a sender that nothing has authenticated
// yet, who could otherwise tell the three apart by the time it takes. The
// caller holds s.mu.
func (s *exampleStore) live(id ake.OneTimePreKeyID) *ake.OneTimePreKeyPair {
	key := s.keys[id]
	s.keyReads++
	_, consumed := s.dead[id]
	s.deadReads++
	if consumed {
		return nil
	}
	return key
}

func (s *exampleStore) Lookup(_ context.Context, id ake.OneTimePreKeyID) (ake.OneTimePreKey, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	key := s.live(id)
	s.recordCopies++
	if key == nil {
		return copyAbsentExampleOneTimePreKey(), ake.ErrOneTimePreKeyUnavailable
	}
	return key.Public(), nil
}

func (s *exampleStore) TakeAndTombstone(_ context.Context, id ake.OneTimePreKeyID, expected ake.OneTimePreKeyDigest) (*ake.OneTimePreKeyPair, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	key := s.live(id)
	if key == nil {
		return nil, ake.ErrOneTimePreKeyUnavailable
	}
	public := key.Public()
	if public.Digest() != expected {
		return nil, errors.New("example: one-time prekey changed before consumption")
	}
	delete(s.keys, id)
	s.dead[id] = struct{}{} // a production store commits this durably first
	return key, nil
}

func main() {
	ctx := context.Background()
	publicationContext := "example-spk-v1"
	sessionInfo := "example-session-v1"
	now := time.Unix(1_800_000_000, 0).UTC()

	alice, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer alice.Zero()
	bob, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer bob.Zero()
	bobSPK, err := bob.NewSignedPreKey(ake.SignParams{
		Context: publicationContext, PartyID: "bob", Timestamp: now,
	})
	if err != nil {
		panic(err)
	}
	defer bobSPK.Zero()
	bobOTKs, err := bob.NewOneTimePreKeys(bobSPK, 2)
	if err != nil {
		panic(err)
	}
	defer func() {
		for _, key := range bobOTKs {
			key.Zero()
		}
	}()
	bobBundle, err := ake.NewBundle(bob, bobSPK)
	if err != nil {
		panic(err)
	}

	// The application already trusts Bob's identity key. Verification also
	// enforces party binding and bundle freshness, then returns an immutable
	// handshake input.
	verifiedBundle, err := bobBundle.Verify(ake.VerifyOptions{
		Context: publicationContext, ExpectedPartyID: "bob",
		ExpectedIdentity: bob.Public(), Now: now.Add(time.Second),
		MaxAge: time.Hour, MaxFutureSkew: time.Minute,
	})
	if err != nil {
		panic(err)
	}
	bobOTK := bobOTKs[0].Public()
	verifiedOTK, err := bobOTK.Verify(verifiedBundle)
	if err != nil {
		panic(err)
	}

	aliceSession, initial, err := ake.Initiate(alice, verifiedBundle, verifiedOTK, ake.InitiateOptions{InitiatorID: "alice", AppInfo: sessionInfo})
	if err != nil {
		panic(err)
	}
	defer aliceSession.Zero()
	store := &exampleStore{
		keys: map[ake.OneTimePreKeyID]*ake.OneTimePreKeyPair{
			bobOTKs[0].ID(): bobOTKs[0],
			bobOTKs[1].ID(): bobOTKs[1],
		},
		dead: make(map[ake.OneTimePreKeyID]struct{}),
	}
	// Bob has independently resolved and trusted Alice's identity key before
	// asking ake to authenticate the initial message against that binding.
	pending, err := ake.Accept(ctx, bob, bobSPK, store, initial, ake.AcceptOptions{
		ExpectedInitiatorID: "alice", ExpectedIdentity: alice.Public(), ExpectedAppInfo: sessionInfo,
	})
	if err != nil {
		panic(err)
	}
	defer pending.Zero()

	nonce, ciphertext, err := aliceSession.Seal([]byte("hello"), []byte("example-first-record-v1"))
	if err != nil {
		panic(err)
	}
	bobSession, plaintext, err := pending.Open(nonce, ciphertext, []byte("example-first-record-v1"))
	if err != nil {
		panic(err)
	}
	defer bobSession.Zero()
	fmt.Println(string(plaintext))

	// Replaying the initial message cannot recover the consumed private key.
	_, replayErr := ake.Accept(ctx, bob, bobSPK, store, initial, ake.AcceptOptions{
		ExpectedInitiatorID: "alice", ExpectedIdentity: alice.Public(), ExpectedAppInfo: sessionInfo,
	})
	fmt.Println(errors.Is(replayErr, ake.ErrAuthentication))

	replyNonce, replyCiphertext, err := bobSession.Seal([]byte("confirmed"), nil)
	if err != nil {
		panic(err)
	}
	reply, err := aliceSession.Open(replyNonce, replyCiphertext, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(bytes.Equal(reply, []byte("confirmed")))

	// A confirmed Session can be consumed by the record layer. Each Seal
	// advances and erases a directional message key. The default receive policy
	// accepts bounded reordering but rejects a record the second time.
	aliceRecords, err := record.NewChannel(aliceSession, record.ChannelOptions{})
	if err != nil {
		panic(err)
	}
	defer aliceRecords.Zero()
	bobRecords, err := record.NewChannel(bobSession, record.ChannelOptions{})
	if err != nil {
		panic(err)
	}
	defer bobRecords.Zero()
	firstRecord, err := aliceRecords.Seal([]byte("one"), []byte("example-record-v1"))
	if err != nil {
		panic(err)
	}
	secondRecord, err := aliceRecords.Seal([]byte("two"), []byte("example-record-v1"))
	if err != nil {
		panic(err)
	}
	second, err := bobRecords.Open(secondRecord, []byte("example-record-v1"))
	if err != nil {
		panic(err)
	}
	first, err := bobRecords.Open(firstRecord, []byte("example-record-v1"))
	if err != nil {
		panic(err)
	}
	_, recordReplayErr := bobRecords.Open(secondRecord, []byte("example-record-v1"))
	fmt.Println(string(second), string(first), errors.Is(recordReplayErr, record.ErrReplay))

	// Rekey starts from a fresh authenticated handshake, which consumes
	// another of Bob's one-time prekeys. The record channel mixes that
	// handshake's export with a secret carried from the current epoch.
	bobOTK2 := bobOTKs[1].Public()
	verifiedOTK2, err := bobOTK2.Verify(verifiedBundle)
	if err != nil {
		panic(err)
	}
	freshAlice, freshInitial, err := ake.Initiate(alice, verifiedBundle, verifiedOTK2, ake.InitiateOptions{InitiatorID: "alice", AppInfo: sessionInfo})
	if err != nil {
		panic(err)
	}
	defer freshAlice.Zero()
	freshPending, err := ake.Accept(ctx, bob, bobSPK, store, freshInitial, ake.AcceptOptions{
		ExpectedInitiatorID: "alice", ExpectedIdentity: alice.Public(), ExpectedAppInfo: sessionInfo,
	})
	if err != nil {
		panic(err)
	}
	defer freshPending.Zero()
	freshNonce, freshCiphertext, err := freshAlice.Seal([]byte("rotate"), []byte("rekey-v1"))
	if err != nil {
		panic(err)
	}
	freshBob, _, err := freshPending.Open(freshNonce, freshCiphertext, []byte("rekey-v1"))
	if err != nil {
		panic(err)
	}
	defer freshBob.Zero()
	confirmNonce, confirmCiphertext, err := freshBob.Seal([]byte("ready"), []byte("rekey-v1"))
	if err != nil {
		panic(err)
	}
	if _, err := freshAlice.Open(confirmNonce, confirmCiphertext, []byte("rekey-v1")); err != nil {
		panic(err)
	}
	aliceStaged, err := aliceRecords.StageRekey(freshAlice)
	if err != nil {
		panic(err)
	}
	if err := bobRecords.AddRekeyCandidate(freshBob); err != nil {
		panic(err)
	}
	// Alice, the channel initiator, decides the rekey. Her confirmation and
	// Bob's reply are public values that prove themselves. This example
	// hands them over directly; a distributed application carries them
	// between the two endpoints, and the record package recommends carrying
	// them outside the record sequence, unsealed, as a Driver does ("Carrying
	// the confirmations" in its documentation). Her confirmation carries the
	// number of this attempt, and his reply repeats it. Bob releases his
	// reply only after checking her confirmation, and she activates only
	// after verifying his reply.
	bobReply, err := bobRecords.AcceptRekeyConfirmation(aliceStaged)
	if err != nil {
		panic(err)
	}
	if err := aliceRecords.VerifyRekeyConfirmation(bobReply); err != nil {
		panic(err)
	}
	aliceEpoch, err := aliceRecords.ActivateRekey()
	if err != nil {
		panic(err)
	}
	// Her first record on the new epoch is what lets Bob follow.
	postRekey, err := aliceRecords.Seal([]byte("new epoch"), nil)
	if err != nil {
		panic(err)
	}
	postRekeyPlaintext, err := bobRecords.Open(postRekey, nil)
	if err != nil {
		panic(err)
	}
	bobEpoch, err := bobRecords.ActivateRekey()
	if err != nil {
		panic(err)
	}
	fmt.Println("rekeyed:", aliceStaged.Epoch == 1 && aliceEpoch == 1 && bobEpoch == 1)
	fmt.Println(string(postRekeyPlaintext))
	postRekeyReply, err := bobRecords.Seal([]byte("new epoch reply"), nil)
	if err != nil {
		panic(err)
	}
	postRekeyReplyPlaintext, err := aliceRecords.Open(postRekeyReply, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(postRekeyReplyPlaintext))

}
Output:
hello
true
true
two one true
rekeyed: true
new epoch
new epoch reply
Example (Persistence)

Example_persistence shows the supported persistence seam for a receiver's identity, signed prekey, and hybrid one-time prekeys. A real application stores the exported private values under authenticated encryption, atomically with their public record, before publishing the bundle. The exported copies are caller-owned secrets and must be scrubbed after the storage or restore operation.

This restores the same signed-prekey epoch after a restart. Rotation is a separate operation: generate and persist a new prekey before publishing it, retain the old one only for a bounded in-flight window, then zero it.

package main

import (
	"fmt"
	"time"

	"edo.dev/ake"
)

func main() {
	identity, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer identity.Zero()

	params := ake.SignParams{
		Context:   "example-bundle-v1",
		PartyID:   "receiver-7",
		Timestamp: time.Unix(1_750_000_000, 0).UTC(),
	}
	prekey, err := identity.NewSignedPreKey(params)
	if err != nil {
		panic(err)
	}
	defer prekey.Zero()

	identityPrivate, err := identity.Private()
	if err != nil {
		panic(err)
	}
	defer func() {
		clear(identityPrivate)
	}()
	x25519Private, err := prekey.Private()
	if err != nil {
		panic(err)
	}
	defer func() {
		clear(x25519Private[:])
	}()

	// Persist these public fields alongside the encrypted private record.
	identityPublic := identity.Public()
	x25519Public, signature := prekey.Public()
	prekeyID := prekey.ID()
	otks, err := identity.NewOneTimePreKeys(prekey, 1)
	if err != nil {
		panic(err)
	}
	defer otks[0].Zero()
	otkRecord := otks[0].Public()
	otkXPrivate, otkKEMSeed, err := otks[0].Private()
	if err != nil {
		panic(err)
	}
	defer func() {
		clear(otkXPrivate[:])
		clear(otkKEMSeed)
	}()

	// After a restart, restore and validate the private material against the
	// exact public record that was published.
	restoredIdentity, err := ake.IdentityFromPrivate(identityPrivate, identityPublic)
	if err != nil {
		panic(err)
	}
	defer restoredIdentity.Zero()
	restoredPrekey, err := restoredIdentity.SignedPreKeyFromPrivate(
		ake.SignedPreKeyRestoreParams{
			SignParams:           params,
			ExpectedX25519Public: x25519Public,
			X25519Private:        x25519Private,
			Signature:            signature,
			ExpectedID:           prekeyID,
		},
	)
	if err != nil {
		panic(err)
	}
	defer restoredPrekey.Zero()
	restoredOTK, err := restoredIdentity.OneTimePreKeyFromPrivate(
		ake.OneTimePreKeyRestoreParams{
			SignParams: params, SignedPreKeyPublic: x25519Public, ID: otkRecord.ID,
			ExpectedX25519Public: otkRecord.X25519,
			ExpectedMLKEMPublic:  otkRecord.MLKEM,
			X25519Private:        otkXPrivate, MLKEMSeed: otkKEMSeed,
			Signature: otkRecord.Signature,
		},
	)
	if err != nil {
		panic(err)
	}
	defer restoredOTK.Zero()

	fmt.Println("restored signed prekey:", restoredPrekey.ID() == prekeyID)
	fmt.Println("restored one-time prekey:", restoredOTK.ID() == otkRecord.ID)
}
Output:
restored signed prekey: true
restored one-time prekey: true
Example (StatementSignatures)
package main

import (
	"bytes"
	"context"
	"crypto/sha512"
	"errors"
	"fmt"
	"sync"

	"edo.dev/ake"
)

type exampleStatementOperation struct {
	key ake.StatementKeyID
	op  ake.StatementOperationID
}

type exampleStatementReceipt struct {
	request ake.StatementDigest
	value   []byte
}

type exampleStatementEntry struct {
	creation ake.StatementCreationID
	initial  ake.StatementDigest
	state    ake.StatementPrivateState
	active   bool
}

// exampleStatementBackend is deliberately in-memory so the example is
// runnable. A production backend must extend the same transitions across its
// journal, replicas, snapshots and backups, as ake.StatementBackend requires.
type exampleStatementBackend struct {
	mu       sync.Mutex
	entries  map[ake.StatementKeyID]*exampleStatementEntry
	receipts map[exampleStatementOperation]exampleStatementReceipt
	retired  map[ake.StatementKeyID]bool
}

func newExampleStatementBackend() *exampleStatementBackend {
	return &exampleStatementBackend{
		entries:  make(map[ake.StatementKeyID]*exampleStatementEntry),
		receipts: make(map[exampleStatementOperation]exampleStatementReceipt),
		retired:  make(map[ake.StatementKeyID]bool),
	}
}

func (b *exampleStatementBackend) Stage(_ context.Context, key ake.StatementKeyID, creation ake.StatementCreationID, state ake.StatementPrivateState) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.retired[key] {
		return ake.ErrStatementConflict
	}
	digest := ake.StatementDigest(sha512.Sum384(state))
	if old := b.entries[key]; old != nil {
		if old.creation != creation || old.initial != digest {
			return ake.ErrStatementConflict
		}
		return nil
	}
	b.entries[key] = &exampleStatementEntry{
		creation: creation,
		initial:  digest,
		state:    state.Clone(),
	}
	return nil
}

func (b *exampleStatementBackend) Activate(_ context.Context, key ake.StatementKeyID, creation ake.StatementCreationID) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	entry := b.entries[key]
	if b.retired[key] || entry == nil || entry.creation != creation {
		return ake.ErrStatementConflict
	}
	entry.active = true
	return nil
}

func (b *exampleStatementBackend) Discard(_ context.Context, key ake.StatementKeyID, creation ake.StatementCreationID) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if entry := b.entries[key]; entry != nil {
		if entry.creation != creation {
			return ake.ErrStatementConflict
		}
		entry.state.Zero()
		delete(b.entries, key)
	}
	b.clearReceipts(key)
	b.retired[key] = true
	return nil
}

func (b *exampleStatementBackend) Transact(ctx context.Context, key ake.StatementKeyID, operation ake.StatementOperationID, request ake.StatementDigest, update ake.StatementStateUpdate) ([]byte, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	b.mu.Lock()
	defer b.mu.Unlock()
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	if b.retired[key] {
		return nil, ake.ErrStatementState
	}
	op := exampleStatementOperation{key: key, op: operation}
	if done, ok := b.receipts[op]; ok {
		if done.request != request {
			return nil, ake.ErrStatementConflict
		}
		return bytes.Clone(done.value), nil
	}
	entry := b.entries[key]
	if entry == nil || !entry.active {
		return nil, ake.ErrStatementState
	}
	next, receipt, err := update(entry.state)
	if err != nil {
		return nil, err
	}
	entry.state.Zero()
	entry.state = next.Clone()
	next.Zero()
	b.receipts[op] = exampleStatementReceipt{request: request, value: bytes.Clone(receipt)}
	return bytes.Clone(receipt), nil
}

func (b *exampleStatementBackend) Retire(_ context.Context, key ake.StatementKeyID) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if entry := b.entries[key]; entry != nil {
		entry.state.Zero()
		delete(b.entries, key)
	}
	b.clearReceipts(key)
	b.retired[key] = true
	return nil
}

func (b *exampleStatementBackend) clearReceipts(key ake.StatementKeyID) {
	for operation, receipt := range b.receipts {
		if operation.key == key {
			clear(receipt.value)
			delete(b.receipts, operation)
		}
	}
}

func exampleStatementOperationID(last byte) (id ake.StatementOperationID) {
	id[len(id)-1] = last
	return id
}

func main() {
	ctx := context.Background()
	identity, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer identity.Zero()

	backend := newExampleStatementBackend()
	provisioning, err := ake.PrepareStatementKey(identity, ake.StatementKeyParams{
		Context: "example-service-v1",
		Scope:   "wallet-transactions-v1",
	}, backend)
	if err != nil {
		panic(err)
	}
	defer provisioning.Zero()
	certificate := provisioning.Certificate()
	key, err := ake.VerifyStatementKey(certificate, identity.Public(), "example-service-v1", "wallet-transactions-v1")
	if err != nil {
		panic(err)
	}
	signer, err := provisioning.Publish(ctx)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := signer.Close(); err != nil && !errors.Is(err, ake.ErrStatementClosed) {
			panic(err)
		}
	}()

	statement := []byte(`{"account":"alice","amount":"10.00","currency":"EUR","nonce":1}`)
	signature, err := signer.SignStatement(ctx, exampleStatementOperationID(1), statement)
	if err != nil {
		panic(err)
	}
	index, err := ake.VerifyStatement(key, statement, signature)
	if err != nil {
		panic(err)
	}
	fmt.Println("statement index:", index)

	nextBackend := newExampleStatementBackend()
	nextProvisioning, err := ake.PrepareStatementKey(identity, ake.StatementKeyParams{
		Context:     key.Context(),
		Scope:       key.Scope(),
		Generation:  key.Generation() + 1,
		Predecessor: key.ID(),
	}, nextBackend)
	if err != nil {
		panic(err)
	}
	defer nextProvisioning.Zero()
	nextCertificate := nextProvisioning.Certificate()
	nextSigner, err := nextProvisioning.Publish(ctx)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := nextSigner.Close(); err != nil && !errors.Is(err, ake.ErrStatementClosed) {
			panic(err)
		}
	}()
	// A production application commits these exact bytes, the operation id and
	// the transition intent durably before consuming the predecessor's final
	// leaf. This in-memory example keeps them in variables only so it remains
	// runnable without an application database.
	successorOperation := exampleStatementOperationID(2)
	successorIntent, err := nextCertificate.Marshal()
	if err != nil {
		panic(err)
	}
	authorization, err := signer.SignStatementSuccessor(ctx, successorOperation, nextCertificate)
	if err != nil {
		panic(err)
	}
	nextKey, err := ake.VerifyStatementSuccessor(key, nextCertificate, authorization)
	if err != nil {
		panic(err)
	}
	fmt.Println("successor generation:", nextKey.Generation())
	_ = successorIntent
	// Production code atomically installs this pin with the delivered
	// certificate and authorization before retiring the predecessor.
	_ = nextKey.Pin()

	if err := signer.Retire(ctx); err != nil {
		panic(err)
	}

}
Output:
statement index: 0
successor generation: 1

Index

Examples

Constants

View Source
const (
	// MLKEMEncapsulationKeySize is the length of an ML-KEM-1024 encapsulation
	// (public) key, as carried in OneTimePreKey.MLKEM.
	MLKEMEncapsulationKeySize = mlkem.EncapsulationKeySize1024
	// MLKEMCiphertextSize is the length of an ML-KEM-1024 ciphertext, as carried
	// in InitialMessage.MLKEMCiphertext.
	MLKEMCiphertextSize = mlkem.CiphertextSize1024
)

Fixed ML-KEM-1024 sizes, per FIPS 203, for the values this package carries in exported types: the encapsulation (public) key carried by a signed hybrid one-time prekey, and the ciphertext carried on an initial message.

View Source
const (
	// MaxPartyIDLen is the maximum byte length of a party identifier. A
	// party identifier is valid UTF-8.
	MaxPartyIDLen = 255
	// MaxOneTimePreKeys is the maximum OTK count generated in one call.
	MaxOneTimePreKeys = 4096
	// MaxContextLen is the maximum byte length of a signing context. A
	// signing context is valid UTF-8.
	MaxContextLen = 255
)
View Source
const (

	// MaxStatementScopeLen is the maximum byte length of the public scope of
	// a statement key. A scope is non-empty valid UTF-8 and tells an
	// application which kinds of statements the key is authorized to sign.
	MaxStatementScopeLen = 255

	// StatementPublicKeySize is the size of an ML-DSA-87 public key, an
	// Ed25519 public key and an XMSS-SHA2_10_256 public key in that order.
	StatementPublicKeySize = mldsa.MLDSA87PublicKeySize + ed25519.PublicKeySize + xmss.PublicKeySize

	// StatementXMSSSignatureSize is the size of an XMSS-SHA2_10_256
	// signature. It is exported to let applications bound wire messages.
	StatementXMSSSignatureSize = xmss.SignatureSize

	// StatementSignatureSize is the size of a canonical statement signature
	// encoding. It contains its key id and leaf index followed by the
	// ML-DSA-87, Ed25519 and XMSS signatures.
	StatementSignatureSize = 4 + 1 + sha512.Size384 + 4 + 1 + SignatureSize + xmss.SignatureSize
)
View Source
const MaxAppInfoLen = 255

MaxAppInfoLen bounds the public application info carried by InitialMessage and used in transcript binding and key derivation. An application info is valid UTF-8.

View Source
const MaxEnvelopeAppInfoLen = 239

MaxEnvelopeAppInfoLen bounds, in bytes, the application info given to SealEnvelope and OpenEnvelope. That application info is also non-empty and valid UTF-8. The bound is shorter than MaxAppInfoLen because the handshake of an envelope carries the application info behind a reserved 16-byte prefix, and the two together have to fit the same wire field.

View Source
const (

	// SignatureSize is the exact size of every authentication signature in
	// this suite: an ML-DSA-87 signature followed by an Ed25519 signature.
	SignatureSize = mldsa.MLDSA87SignatureSize + ed25519.SignatureSize
)
View Source
const Suite = "ake-pq-v1/ML-DSA-87+Ed25519-SHA512-Signed/X25519-4DH/ML-KEM-1024-OTK/HKDF-SHA384/AES-256-GCM"

Suite names the fixed set of primitives this build of the library implements, so a caller (or a future wire message) can pin an exact construction rather than a version number. Every handshake uses four X25519 DH contributions, an individually signed hybrid one-time prekey, an ML-KEM-1024 encapsulation to that one-time prekey, and an ML-DSA-87+Ed25519 composite signature over the complete handshake commitment. The identity's X25519 key is independent of both signing keys. There is no classical-only authentication, 3DH, or algorithm-negotiation fallback. Changing this string changes the construction and wire.

Variables

View Source
var (
	// ErrInvalidKey reports a key or point of the wrong size or encoding.
	ErrInvalidKey = errors.New("ake: invalid key")
	// ErrSmallOrderKey reports a small-order Curve25519 point, rejected to
	// enforce contributory key-agreement behavior.
	ErrSmallOrderKey = errors.New("ake: small-order point rejected")
	// ErrInvalidSignature reports an invalid signed-prekey or one-time-prekey
	// signature. Accept deliberately reports an invalid initiator signature as
	// ErrAuthentication so it cannot be used as an OTK-state oracle.
	ErrInvalidSignature = errors.New("ake: invalid signature")
	// ErrSessionClosed reports use of a Session after Zero, or of a
	// PendingSession that has been zeroed, promoted by Open, or consumed by
	// ExportUnconfirmed.
	ErrSessionClosed = errors.New("ake: session closed")
	// ErrZeroed reports use of an Identity or key pair after Zero.
	ErrZeroed = errors.New("ake: key material zeroed")
	// ErrUsage reports an API-misuse condition (inconsistent arguments).
	ErrUsage = errors.New("ake: invalid usage")
	// ErrWire reports malformed or oversized wire-format input.
	ErrWire = errors.New("ake: malformed wire data")
	// ErrInvalidMessage reports a structurally invalid or unacceptable peer
	// message after decoding. Unlike ErrUsage, it is caused by untrusted
	// protocol input rather than by inconsistent caller arguments.
	ErrInvalidMessage = errors.New("ake: invalid peer message")
	// ErrKeyMismatch reports authenticated key material or identity information
	// that does not match the caller's expected peer, public record, or restored
	// private key.
	ErrKeyMismatch = errors.New("ake: key or authenticated identity mismatch")
	// ErrStaleBundle reports a bundle older than VerifyOptions.MaxAge or below
	// VerifyOptions.MinTimestamp. Fetch a newer bundle; do not lower a durable
	// rollback floor merely to accept it.
	ErrStaleBundle = errors.New("ake: stale bundle")
	// ErrAuthentication reports cryptographic authentication failure. Accept
	// also returns it for a definitely unavailable OTK during its pre-signature
	// lookup. The value and display text do not distinguish OTK state. The
	// early rejection builds a same-shaped transcript around a placeholder
	// record and runs the same verifier over the sender's own key and
	// signature, so the two paths take the same steps, but they are not
	// constant-time: the store behaves differently for a live record, and the
	// verifier's time depends on the bytes it verifies, which differ between
	// the two paths (OneTimePreKeyStore).
	//
	// The record package's ErrAuthentication is a separate value for a failed
	// record; errors.Is does not match one against the other.
	ErrAuthentication = errors.New("ake: authentication failed")
	// ErrStore reports failure of the authoritative one-time-prekey store.
	// Its displayed text never includes the backend's error text. To support
	// request cancellation without exposing backend-specific sentinels,
	// errors.Is matches only context.Canceled or context.DeadlineExceeded from
	// an underlying cause. The text of that context error, and nothing else
	// of the cause, follows the error's own text, as in
	// "ake: one-time-prekey store operation failed: context canceled".
	ErrStore = errors.New("ake: one-time-prekey store operation failed")
	// ErrOneTimePreKeyUnavailable reports that an authenticated initial message
	// lost the atomic race to consume its one-time prekey, to another Accept
	// of the same message or to the retirement of the key's epoch. Before
	// initiator authentication, definite absence is deliberately reported
	// only as ErrAuthentication.
	ErrOneTimePreKeyUnavailable = errors.New("ake: authenticated one-time prekey is unavailable")
	// ErrOneTimePreKeySpent reports a second attempt to initiate with the same
	// verified one-time-prekey capability. Retransmit the original initial
	// message and first record, or fetch and verify a fresh one-time prekey.
	ErrOneTimePreKeySpent = errors.New("ake: verified one-time prekey already used for initiation")
	// ErrSessionExhausted reports that a Session has sealed as many messages
	// as its random-nonce budget safely allows. It is not an error condition
	// in the session's peer or input: re-handshake for a new Session, or use
	// Export to seed a caller-owned ratchet.
	ErrSessionExhausted = errors.New("ake: session seal budget exhausted")
	// ErrStatementUnavailable reports that the statement-signature service is
	// unavailable in the current process. It is returned while FIPS 140-only
	// enforcement is active because ake's software XMSS signer is not an
	// approved SP 800-208 service,
	// and by statement-key provisioning if crypto/rand.Reader was replaced
	// before ake initialized or a future Go toolchain changes the recognized
	// default-reader representation.
	ErrStatementUnavailable = errors.New("ake: statement signatures unavailable in the current process")
	// ErrStatementClosed reports use of a closed StatementSigner or of a
	// published, abandoned or zeroed StatementProvisioning.
	ErrStatementClosed = errors.New("ake: statement signer closed")
	// ErrStatementExhausted reports that no ordinary XMSS leaf remains, or that
	// the reserved final leaf has already authorized a successor. Rotate with
	// SignStatementSuccessor while the reserved leaf remains.
	ErrStatementExhausted = errors.New("ake: statement key exhausted")
	// ErrStatementConflict reports reuse of one StatementOperationID with a
	// different request or an incompatible existing private state.
	ErrStatementConflict = errors.New("ake: statement transaction conflict")
	// ErrStatementState reports damaged or otherwise inconsistent authoritative
	// statement private state or receipt. A well-formed old state is detected
	// only by the backend's monotonic fence, not by the state's checksum.
	ErrStatementState = errors.New("ake: invalid statement private state")
	// ErrStatementBusy reports a conflicting local lifecycle operation: a
	// retirement requested while signing is in flight, a second retirement, or
	// Close while retirement still needs a possible retry. New signing calls
	// are refused after retirement begins; retry Retire after the active call
	// returns.
	ErrStatementBusy = errors.New("ake: statement operation in progress")
)

Functions

func BuildAAD

func BuildAAD(fields ...[]byte) ([]byte, error)

BuildAAD concatenates fields with a big-endian uint32 length prefix per field, making the encoding injective for fields shorter than 4 GiB — no two distinct field sequences produce the same bytes. It returns ErrUsage if a field cannot be represented by the uint32 prefix or the complete encoding cannot fit in an int on the current platform.

For Seal/Open, pass only application context the library does not know — a routing label, a message kind. A Session already binds the authenticated handshake content (both party ids, both identities, both responder prekeys, the ephemeral key and the KEM ciphertext) into every operation, so re-binding that content here is redundant. The randomized composite-signature witness is deliberately not part of the transcript hash.

func Initiate

Initiate creates the only v1 handshake: signed, hybrid 4DH. peer and otk must be immutable verified values; there is no 3DH fallback.

Every error leaves otk unspent except ErrOneTimePreKeySpent, which reports that it already was. Initiate returns:

  • an error matching ErrUsage for a nil id, peer or otk, a peer or otk that Verify did not return, an InitiatorID or AppInfo that is empty, too long or not valid UTF-8, and an AppInfo that begins with the prefix reserved for envelopes;
  • ErrZeroed for an Identity that was scrubbed or that no constructor returned;
  • an error matching ErrKeyMismatch when otk was verified against another bundle than peer;
  • ErrOneTimePreKeySpent when otk already started a handshake, here or in a concurrent call: one verified one-time prekey starts one handshake.

The ephemeral key and the randomness of the encapsulation come from the generator of Go's cryptographic module, which does not fail. With GODEBUG=cryptocustomrand=1, crypto/ecdh draws the ephemeral key from crypto/rand.Reader instead, and Initiate wraps any reader error that crypto/ecdh reports, so that errors.Is finds it. crypto/ecdh uses io.ReadFull, which accepts a full final read accompanied by a non-EOF error. Repeated all-zero draws return an error matching ErrInvalidKey. Apart from that generation error, the key errors of the agreement itself, ErrInvalidKey and ErrSmallOrderKey, are not expected here, because Verify has already checked the keys Initiate uses.

func OpenEnvelope

func OpenEnvelope(ctx context.Context, id *Identity, spk *SignedPreKeyPair, store OneTimePreKeyStore, env *Envelope, opts AcceptOptions, aad []byte) ([]byte, error)

OpenEnvelope authenticates the sender of env and the whole of env, consumes the one-time prekey it names, and returns the plaintext. ctx, id, spk, store and opts are those of Accept: spk must be the signed prekey that env.Message.SignedPreKeyID names, and opts carries the sender the caller expects, which it looks up from env.Message.InitiatorID. aad must equal the value given to SealEnvelope. The session is scrubbed before OpenEnvelope returns.

opts.ExpectedAppInfo is the application info the sender gave to SealEnvelope, without the reserved prefix; Envelope.AppInfo reads it from a received envelope. When Envelope.AppInfo returns the empty string, env is not an envelope this recipient can open: refuse it as peer input without calling OpenEnvelope, which takes an empty ExpectedAppInfo for the caller's mistake and returns an error matching ErrUsage, with nothing consumed. The handshake of an ordinary Session, routed here by mistake or by someone on the path, is refused with ErrKeyMismatch and consumes nothing.

OpenEnvelope keeps no state and needs none. The sender's signature covers the authenticated handshake content, nonce, aad and ciphertext, and it is verified before the store is asked to consume the one-time prekey. An envelope that is forged, that comes from another sender than the one expected, or whose authenticated handshake content, nonce or ciphertext is not what the sender signed, and a call with another aad, are refused with nothing consumed: the genuine envelope, offered afterwards with the right aad, still opens. A wrong nonce, ciphertext or aad returns ErrAuthentication, a nonce of the wrong length included.

That holds while every identity the recipient accepts envelopes from has at least one uncompromised signing component. A caller that looks the expected sender up from env.Message.InitiatorID expects whichever accepted sender the envelope names, and a one-time prekey is not bound to a sender: a second accepted sender that has the public keys of the one-time prekey can sign a copy of another sender's envelope in its own name, and that copy consumes the one-time prekey and returns ErrAuthentication, and the genuine envelope cannot open afterwards. The type Envelope describes what that takes.

What the holder of both sender signing components signed is consumed. A sender that signs a record which does not open under the key of its own handshake gets ErrAuthentication returned to the recipient with the one-time prekey spent; it can do that once for each one-time prekey it was given, as it can by sealing a message nobody wants.

A second copy of an envelope that already opened returns ErrAuthentication, as any spent one-time prekey does. EnvelopeDigest lets a caller recognize a duplicate before calling. A copy that races the first, while that one is still being opened, returns ErrOneTimePreKeyUnavailable or ErrAuthentication, depending on how far the first had come: drop it.

An error matching ErrStore means the store failed. If it failed while consuming the one-time prekey, the consumption may have committed, and then no copy of the envelope opens: a retry that returns ErrAuthentication says so, and the sender has to seal a new one. Such an error matches a context error as well when the store reported one, so test for ErrStore before testing for context.Canceled or context.DeadlineExceeded, as Accept describes.

A directly constructed Envelope whose nonce or ciphertext cannot have the canonical wire form returns ErrAuthentication before any store lookup. The other errors are those listed on Accept, a nil ctx among them. A nil env, or one without a Message, returns an error matching ErrUsage, and so does an aad longer than 2^32 - 24 bytes, or 2^31 - 80 bytes on a platform whose int has 32 bits, which SealEnvelope refuses as well, and an opts.ExpectedAppInfo that is empty, longer than MaxEnvelopeAppInfoLen, not valid UTF-8 or begins with the reserved prefix.

func VerifyStatement

func VerifyStatement(key *VerifiedStatementKey, statement, signature []byte) (uint32, error)

VerifyStatement verifies all three signature components for statement under key and returns its XMSS leaf index. It is stateless: applications enforce their own replay, authorization and monotonic-position policy. An empty statement is valid. Verification is refused while FIPS 140-only enforcement is active.

Types

type AcceptOptions

type AcceptOptions struct {
	ExpectedInitiatorID string
	ExpectedIdentity    PublicIdentity
	ExpectedAppInfo     string
	// contains filtered or unexported fields
}

AcceptOptions supplies the receiver's external trust decision and the application-specific KDF label. A valid initiator signature proves control of a key; ExpectedInitiatorID, ExpectedIdentity, and ExpectedAppInfo pin the handshake to the peer and channel the application intended to authenticate. ExpectedInitiatorID and ExpectedAppInfo must be non-empty, at most 255 bytes and valid UTF-8.

type Bundle

type Bundle struct {

	// PartyID is the responder's party identifier: 1 to MaxPartyIDLen bytes
	// of valid UTF-8.
	PartyID      string
	IdentityKey  PublicIdentity
	SignedPreKey X25519PublicKey
	Signature    []byte
	Timestamp    time.Time
	// contains filtered or unexported fields
}

Bundle is the responder's identity-signed medium-term X25519 prekey. One-time prekeys are separately signed records so a directory can reserve and remove individual records without rewriting a bundle. A composite literal of a Bundle must name its fields.

func NewBundle

func NewBundle(id *Identity, spk *SignedPreKeyPair) (*Bundle, error)

NewBundle constructs the public bundle for a live identity and signed prekey, and verifies their binding before returning it.

It returns an error matching ErrUsage for a nil id or spk, for a signed prekey that no constructor returned, and for a signed prekey that id did not sign: handing over another identity's signed prekey is the caller's mistake, and no record a directory served is in question. It returns ErrZeroed for an Identity or a signed prekey that was scrubbed, and for an Identity that no constructor returned.

func UnmarshalBundle

func UnmarshalBundle(data []byte) (*Bundle, error)

UnmarshalBundle decodes one canonical v1 bundle and rejects trailing bytes. A party identifier that is not valid UTF-8 is refused with an error matching ErrWire, as an empty or overlong one is. The bundle it returns holds copies of what it reads and shares no memory with data, which the caller may change or reuse afterwards.

func (*Bundle) Marshal

func (b *Bundle) Marshal() ([]byte, error)

Marshal encodes the bundle in the canonical v1 wire format. It returns an error matching ErrUsage for a nil bundle, a PartyID that is empty, too long or not valid UTF-8, and a Signature of another size than SignatureSize.

func (*Bundle) Verify

func (b *Bundle) Verify(opts VerifyOptions) (*VerifiedBundle, error)

Verify applies the caller's identity, party, freshness, and rollback policy and returns an immutable bundle snapshot on success. A Context or an ExpectedPartyID that is empty, too long or not valid UTF-8 returns an error matching ErrUsage. The bundle's own PartyID is compared with the expected one and not examined otherwise: with valid options, a Bundle built in memory whose PartyID is empty, too long or not valid UTF-8 returns an error matching ErrKeyMismatch, as any other party id than the expected one does.

A bundle whose Timestamp is the zero time, the Unix second -62135596800, returns an error matching ErrInvalidMessage at any Now that is not zero and whatever MaxAge and MaxFutureSkew allow, when the options are valid and the bundle's party id and identity key are the expected ones: no signed prekey can be signed for that second, so the record is malformed, and the error is never the ErrUsage that an unset SignParams.Timestamp of the caller's gets. The checks before it come first: invalid options, a zero Now among them, return an error matching ErrUsage, and another party id or identity key than the expected one ErrKeyMismatch. The age and skew bounds are inclusive: a timestamp exactly MaxAge before Now, or exactly MaxFutureSkew after it, is accepted, and so is one equal to MinTimestamp.

type Envelope

type Envelope struct {

	// Message is the handshake. Its InitiatorID, IdentityKey and
	// SignedPreKeyID are what the recipient reads, before any
	// authentication, to find the sender it expects and the signed prekey to
	// open with. Its InitiatorSignature is made over the handshake and over
	// Nonce, the associated data and Ciphertext.
	Message *InitialMessage
	// Nonce and Ciphertext are the sealed record.
	Nonce      []byte
	Ciphertext []byte
	// contains filtered or unexported fields
}

Envelope is one self-contained message: a handshake and a single record sealed under the key that handshake derives. The recipient needs nothing from the sender beforehand and keeps nothing afterwards, so an Envelope can wait in a queue while the recipient is offline, or while it restarts, as long as the recipient's signed prekey and one-time prekeys are durable.

It cannot wait indefinitely. An Envelope opens only while the recipient still holds the signed prekey that Message.SignedPreKeyID names, the current one or the previous one until it is retired, and the sender may have used a bundle fetched just before a rotation. Keep queue retention shorter than the time the recipient keeps a previous signed prekey, less the age of the bundle the sender used. An Envelope that outlives its signed prekey is lost. Until the recipient consumes the one-time prekey, a later full compromise of the recipient's identity X25519 key and the named signed- and one-time-prekey private state exposes the plaintext. Compromise of the prekeys alone removes the post-quantum route but leaves DH2 against a classical attacker unless the recipient identity scalar or sender ephemeral scalar is compromised too.

Use an Envelope for occasional messages and for anything that has to survive the recipient restarting. Each one costs a full handshake and one of the recipient's one-time prekeys, which the sender has to obtain first; sustained traffic between two running processes belongs on a record Channel instead.

An Envelope authenticates its sender to the recipient and is opened at most once: the one-time prekey it names is destroyed on first use, so a second copy fails. The sender learns nothing about delivery. A recipient that answers confirms the key to the sender only by that answer.

The sender's signature covers the Envelope's authenticated content: the handshake commitment, nonce, associated data and ciphertext. OpenEnvelope checks it before it consumes anything, so a copy whose authenticated content someone unable to make the sender's composite signature changed, or put together from parts of several envelopes, consumes no OTK and leaves the genuine Envelope able to open. It can still cost a lookup, hashing and composite verification. Another valid randomized composite signature over identical content is an equivalent delivery and may consume the same one-time prekey first. A queue that others can add to, but not remove from, is therefore enough to carry one, as long as the others are not senders the recipient also opens envelopes from: a one-time prekey is not bound to a sender, so any accepted sender can have the recipient consume one, with an Envelope of its own or with a copy of another's that it signed in its own name. For the copy it needs more than the Envelope: the signature covers the one-time prekey's X25519 and ML-KEM public keys, and an Envelope carries only their identifier. An accepted sender that does not have those public keys cannot sign a copy the recipient verifies; its attempt returns ErrAuthentication and consumes nothing.

A composite literal of an Envelope must name its fields.

func SealEnvelope

func SealEnvelope(id *Identity, peer *VerifiedBundle, otk *VerifiedOneTimePreKey, opts InitiateOptions, plaintext, aad []byte) (*Envelope, error)

SealEnvelope performs a handshake toward a verified peer, seals plaintext as its only record, and signs the two together. id, peer, otk and opts are those of Initiate; aad is associated data the recipient must supply unchanged, and may be nil. The session the handshake derives is scrubbed before SealEnvelope returns: nothing further can be sent under it.

The signature is made with id over the handshake, the nonce, aad and the ciphertext. The recipient refuses changed authenticated content before it consumes its one-time prekey unless the sender authenticated that content. Another valid randomized composite-signature witness over the same content is an equivalent delivery; whichever equivalent delivery opens first is the one durable take of the one-time prekey. OpenEnvelope describes the exception for another identity the recipient also accepts.

opts.AppInfo is 1 to MaxEnvelopeAppInfoLen bytes. The handshake carries it behind a reserved prefix, so an envelope is never accepted as an ordinary handshake and an ordinary handshake is never opened as an envelope, even where an application uses one application info for both; either mistake is refused before the recipient's one-time prekey is touched. An application info that is empty, too long, not valid UTF-8, or already carries the prefix returns an error matching ErrUsage.

plaintext is at most 2^32 - 17 bytes, so that the ciphertext, 16 bytes longer, fits the 32-bit length the wire gives it, and aad at most 2^32 - 24 bytes, so that aad under the envelope's label, 23 bytes longer, fits a field of BuildAAD as the session that seals the record frames it. On a platform whose int has 32 bits the bounds are lower, 2^31 - 9827 and 2^31 - 80 bytes, so that the Envelope's encoding, the ciphertext with the longest handshake and the rest of its framing, and the associated data the record is sealed under are lengths an int holds there. A longer plaintext or aad returns an error matching ErrUsage before any part of the handshake is done.

otk is consumed as Initiate consumes it. A verified one-time prekey that already started a handshake returns ErrOneTimePreKeySpent; obtain a fresh one for every Envelope. The other errors are those listed on Initiate. A SealEnvelope that returns an error for its arguments leaves otk unspent.

Example

One message to a recipient that is not running: the sender needs only the recipient's published bundle and one of its one-time prekeys, and the envelope waits in a queue as bytes.

// SPDX-License-Identifier: Apache-2.0

package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"sync"
	"time"

	"edo.dev/ake"
)

// queueStore is the recipient's one-time prekey store. A production store is
// durable: it commits the tombstone before it returns the private key, and
// never lets a restore bring a consumed key back. The mutex serializes access
// to the maps and keeps the digest check, deletion and tombstone insertion
// atomic.
type queueStore struct {
	mu   sync.Mutex
	keys map[ake.OneTimePreKeyID]*ake.OneTimePreKeyPair
	dead map[ake.OneTimePreKeyID]struct{}
}

var absentQueueOneTimePreKey = ake.OneTimePreKey{Signature: make([]byte, ake.SignatureSize)}

func copyAbsentQueueOneTimePreKey() ake.OneTimePreKey {
	record := absentQueueOneTimePreKey
	record.Signature = bytes.Clone(record.Signature)
	return record
}

func (s *queueStore) Lookup(_ context.Context, id ake.OneTimePreKeyID) (ake.OneTimePreKey, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	key := s.keys[id]
	_, consumed := s.dead[id]
	if key == nil || consumed {
		return copyAbsentQueueOneTimePreKey(), ake.ErrOneTimePreKeyUnavailable
	}
	return key.Public(), nil
}

func (s *queueStore) TakeAndTombstone(_ context.Context, id ake.OneTimePreKeyID, expected ake.OneTimePreKeyDigest) (*ake.OneTimePreKeyPair, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	key := s.keys[id]
	_, consumed := s.dead[id]
	if key == nil || consumed {
		return nil, ake.ErrOneTimePreKeyUnavailable
	}
	if public := key.Public(); public.Digest() != expected {
		return nil, errors.New("one-time prekey changed before consumption")
	}
	delete(s.keys, id)
	s.dead[id] = struct{}{} // a production store commits this durably first
	return key, nil
}

// One message to a recipient that is not running: the sender needs only the
// recipient's published bundle and one of its one-time prekeys, and the
// envelope waits in a queue as bytes.
func main() {
	ctx := context.Background()
	now := time.Unix(1_800_000_000, 0).UTC()
	const expectedAppInfo = "example-notices-v1"
	alice, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer alice.Zero()
	bob, err := ake.NewIdentity()
	if err != nil {
		panic(err)
	}
	defer bob.Zero()

	// Bob published these before he stopped.
	bobSPK, err := bob.NewSignedPreKey(ake.SignParams{Context: "example-spk-v1", PartyID: "bob", Timestamp: now})
	if err != nil {
		panic(err)
	}
	defer bobSPK.Zero()
	bobOTKs, err := bob.NewOneTimePreKeys(bobSPK, 1)
	if err != nil {
		panic(err)
	}
	bobBundle, err := ake.NewBundle(bob, bobSPK)
	if err != nil {
		panic(err)
	}
	store := &queueStore{
		keys: map[ake.OneTimePreKeyID]*ake.OneTimePreKeyPair{bobOTKs[0].ID(): bobOTKs[0]},
		dead: make(map[ake.OneTimePreKeyID]struct{}),
	}

	// Alice verifies what she fetched against the identity she trusts.
	peer, err := bobBundle.Verify(ake.VerifyOptions{
		Context: "example-spk-v1", ExpectedPartyID: "bob", ExpectedIdentity: bob.Public(),
		Now: now.Add(time.Minute), MaxAge: time.Hour, MaxFutureSkew: time.Minute,
	})
	if err != nil {
		panic(err)
	}
	record := bobOTKs[0].Public()
	otk, err := record.Verify(peer)
	if err != nil {
		panic(err)
	}

	// The second argument of the sealed record is associated data: Bob has
	// to supply the same value, here the name of the queue.
	envelope, err := ake.SealEnvelope(alice, peer, otk,
		ake.InitiateOptions{InitiatorID: "alice", AppInfo: expectedAppInfo},
		[]byte("config changed"), []byte("queue-7"))
	if err != nil {
		panic(err)
	}
	queued, err := envelope.Marshal()
	if err != nil {
		panic(err)
	}

	// Later, Bob is back. He reads who the envelope claims to be from and
	// which application info it carries, looks up the identity key he trusts
	// for that name, and selects the signed prekey the message names. None
	// of what he read is authenticated until OpenEnvelope succeeds.
	received, err := ake.UnmarshalEnvelope(queued)
	if err != nil {
		panic(err)
	}
	fmt.Println("claims to be from:", received.Message.InitiatorID)
	// Bob compares the unauthenticated route value with his locally configured
	// value. He never authorizes a sender-selected application info merely
	// because it came from the envelope.
	appInfo := received.AppInfo()
	if appInfo != expectedAppInfo {
		fmt.Println("not an envelope: refused")
		return
	}
	fmt.Println("application info:", appInfo)
	fmt.Println("names Bob's signed prekey:", received.Message.SignedPreKeyID == bobSPK.ID())
	open := func() ([]byte, error) {
		return ake.OpenEnvelope(ctx, bob, bobSPK, store, received, ake.AcceptOptions{
			ExpectedInitiatorID: "alice", ExpectedIdentity: alice.Public(), ExpectedAppInfo: expectedAppInfo,
		}, []byte("queue-7"))
	}
	plaintext, err := open()
	if err != nil {
		panic(err)
	}
	fmt.Printf("opened: %s\n", plaintext)

	// A second delivery of the same bytes does not open.
	_, err = open()
	fmt.Println("second copy refused:", errors.Is(err, ake.ErrAuthentication))

}
Output:
claims to be from: alice
application info: example-notices-v1
names Bob's signed prekey: true
opened: config changed
second copy refused: true

func UnmarshalEnvelope

func UnmarshalEnvelope(data []byte) (*Envelope, error)

UnmarshalEnvelope decodes one canonical v1 envelope and rejects trailing bytes. It checks the framing and decodes the handshake message; it authenticates nothing. The returned Envelope does not alias data.

A handshake message that is not an envelope's is refused with an error matching ErrInvalidMessage: one whose application info lacks the reserved prefix, has nothing behind it, or has the prefix twice. What AppInfo returns for a decoded Envelope is therefore always a value OpenEnvelope takes as ExpectedAppInfo.

func (*Envelope) AppInfo

func (e *Envelope) AppInfo() string

AppInfo returns the unauthenticated application info the sender gave to SealEnvelope. A recipient may use it to select a locally configured route, but authorizes that route independently and passes the route's configured value to OpenEnvelope as ExpectedAppInfo; it does not trust this result by comparing it with itself. On the wire, Message.AppInfo carries it behind a reserved prefix that marks the handshake as an envelope's; AppInfo returns it without the prefix. It returns the empty string for a nil envelope, one without a Message, and a Message that is not an envelope's handshake: one whose application info lacks the prefix, or has behind it anything SealEnvelope would refuse, which is nothing at all, more than MaxEnvelopeAppInfoLen bytes, bytes that are not valid UTF-8, or the prefix again. A value AppInfo returns that is not empty is therefore syntactically valid as ExpectedAppInfo, whether the Envelope was decoded or built as a struct.

An empty result means that this is not an envelope the recipient can open: refuse it without calling OpenEnvelope. The empty string is not a valid ExpectedAppInfo, and OpenEnvelope reports it with an error matching ErrUsage, the caller's mistake, although the envelope came from a peer. UnmarshalEnvelope refuses such a handshake, so a decoded Envelope does not give the empty result; one assembled as a struct from fields the application received in another form can.

The value is public and unauthenticated until OpenEnvelope succeeds: use it to choose what to expect, not as a fact about the sender.

func (*Envelope) Digest

func (e *Envelope) Digest() (EnvelopeDigest, error)

Digest returns SHA-384 over the canonical wire encoding of e, the bytes Marshal returns; for an envelope UnmarshalEnvelope accepted it equals SHA-384 of the bytes it was decoded from. It covers the handshake and the record, so it identifies these exact bytes; another valid signature over the same content gives another digest, which the spent one-time prekey refuses. A recipient that remembers the digests of envelopes it opened, for a bounded time, can drop a duplicate without a store lookup, composite verification or decryption; forgetting one is safe, because the spent one-time prekey still refuses it. Digest encodes and hashes every byte, so its time and temporary memory are linear in the envelope's size.

The digest is public and unauthenticated. Digest returns the errors of Marshal.

func (*Envelope) Marshal

func (e *Envelope) Marshal() ([]byte, error)

Marshal encodes the envelope in the canonical v1 wire format. It returns an error matching ErrUsage for a nil envelope, a missing or invalid Message, a Message that is not an envelope's handshake, a Nonce that is not 12 bytes, a Ciphertext shorter than the 16-byte authentication tag or longer than its 32-bit length holds, and an encoding longer than an int holds, which only a platform whose int has 32 bits can be given: an Envelope that SealEnvelope returns there always encodes.

type EnvelopeDigest

type EnvelopeDigest [sha512.Size384]byte

EnvelopeDigest identifies one complete Envelope. Its text form is lower-case hexadecimal, 96 characters.

func (EnvelopeDigest) MarshalText

func (d EnvelopeDigest) MarshalText() ([]byte, error)

MarshalText returns the digest as String gives it.

func (EnvelopeDigest) String

func (d EnvelopeDigest) String() string

String returns the digest as 96 lower-case hexadecimal characters, two for each byte in order.

func (*EnvelopeDigest) UnmarshalText

func (d *EnvelopeDigest) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

type Identity

type Identity struct {
	// contains filtered or unexported fields
}

Identity holds three independent long-term private keys: ML-DSA-87 and Ed25519 authenticate every signed statement together, while X25519 contributes the identity terms of 4DH. There is no single-signature or signing-key-to-DH conversion path.

Identity is safe for concurrent use, including with Zero, and must not be copied; always pass *Identity. New operations fail with ErrZeroed after Zero. Private exports the compact seeds and scalar for durable storage; the caller must protect and clear that copy.

func IdentityFromPrivate

func IdentityFromPrivate(private IdentityPrivateKey, expected PublicIdentity) (*Identity, error)

IdentityFromPrivate restores a private identity and verifies it against expected. The private encoding is copied; the caller retains ownership of it. All three public components are re-derived and compared. A nil private key is ErrUsage; malformed stored private or public material is ErrInvalidKey, and a low-order expected X25519 component is ErrSmallOrderKey. A usable expected identity that differs from the one the private material derives is ErrKeyMismatch. These errors require repairing local persistence or its public pin, not rejecting a peer message. If the selected Go cryptographic module lacks ML-DSA, its module error is returned.

func NewIdentity

func NewIdentity() (*Identity, error)

NewIdentity generates independent ML-DSA-87, Ed25519, and X25519 keys. If any generator is unavailable or fails, no partial Identity is returned.

func (*Identity) Format

func (id *Identity) Format(f fmt.State, _ rune)

Format writes "Identity(…)" for every verb fmt calls it with, %s, %x, %q and %#v included, and nothing of the identity's state, and "<nil>" for a nil Identity. fmt calls it for no %p, which prints the address, and no %w, which prints the fields one pointer deep, an address in place of the key. The private key that Private returns is bytes that fmt prints in full.

func (*Identity) NewOneTimePreKeys

func (id *Identity) NewOneTimePreKeys(spk *SignedPreKeyPair, n int) ([]*OneTimePreKeyPair, error)

NewOneTimePreKeys generates n signed hybrid one-time-prekey pairs bound to spk. If generation fails, every private key generated so far is zeroed.

n is 0 to MaxOneTimePreKeys; for 0 it returns an empty slice and no error. It returns an error matching ErrUsage for a nil Identity or spk, for a signed prekey that no constructor returned, for an n that is negative or above MaxOneTimePreKeys, and for a signed prekey that this identity did not sign: handing over another identity's signed prekey is the caller's mistake. It returns ErrZeroed for an Identity or a signed prekey that was scrubbed, and for an Identity that no constructor returned. The keys come from the generator of Go's cryptographic module, which does not fail, and each identifier from the reader the package documentation names for it, which fails only when it is a reader assigned to crypto/rand.Reader before this package was initialised. NewOneTimePreKeys returns an error that wraps an error of that reader, so that errors.Is finds it, and one that wraps io.ErrUnexpectedEOF for a reader that ends before it has filled an identifier. With GODEBUG=cryptocustomrand=1, crypto/ecdh draws the X25519 keys from crypto/rand.Reader as it is at the call, and an error that crypto/ecdh reports from that reader is returned wrapped as well. crypto/ecdh uses io.ReadFull, which accepts a full final read accompanied by a non-EOF error. Repeated all-zero X25519 draws return an error matching ErrInvalidKey.

func (*Identity) NewSignedPreKey

func (id *Identity) NewSignedPreKey(p SignParams) (*SignedPreKeyPair, error)

NewSignedPreKey generates an identity-signed medium-term X25519 prekey for the supplied context, party, and canonicalized timestamp. A Context or a PartyID that is empty, too long or not valid UTF-8, and a Timestamp that is zero, falls within the first second of the year 1 or falls outside the years 1 to 9999 UTC, return an error matching ErrUsage. The pair keeps the public identity key of id, which signed it: Accept and OpenEnvelope refuse it with another Identity. With GODEBUG=cryptocustomrand=1, repeated all-zero X25519 draws return an error matching ErrInvalidKey instead of producing a persisted scalar that restoration treats as erased.

func (*Identity) OneTimePreKeyFromPrivate

func (id *Identity) OneTimePreKeyFromPrivate(restore OneTimePreKeyRestoreParams) (*OneTimePreKeyPair, error)

OneTimePreKeyFromPrivate restores and validates both one-time private halves, the full signed-prekey epoch binding, and the identity signature. It cannot determine whether a tombstone already consumed this record; the authoritative store must refuse such a restore.

Everything it is given is local input, and its errors say which part is at fault. The checks run in the order of this list, and the first that fails gives the error:

  • ErrUsage: a nil Identity.
  • ErrZeroed: the Identity was zeroed.
  • ErrUsage: a SignParams that NewSignedPreKey would refuse, with a Context or a PartyID that is empty, too long or not valid UTF-8, or a Timestamp that is zero, falls within the first second of the year 1 or falls outside the years 1 to 9999 UTC; then an ID that is unset.
  • ErrInvalidKey: an X25519 private scalar of all zero bytes.
  • ErrKeyMismatch: an X25519 private scalar that does not give ExpectedX25519Public. No scalar gives a value of small order or one that is not canonically encoded, so such an expected value is reported as this mismatch and not as ErrSmallOrderKey or ErrInvalidKey.
  • ErrInvalidKey: an MLKEMSeed that is not a 64-byte ML-KEM-1024 seed.
  • ErrKeyMismatch: a seed that does not give ExpectedMLKEMPublic, an expected encapsulation key that ML-KEM refuses included.
  • ErrInvalidKey: a SignedPreKeyPublic that is not canonically encoded.
  • ErrSmallOrderKey: a SignedPreKeyPublic of small order.
  • ErrInvalidSignature: a Signature that is not SignatureSize bytes, or that the Identity did not make over this record for this SignParams and signed prekey.

The parameters arrive by value, so the function holds its own copy of the X25519 private scalar: it clears that copy before it returns. The caller's value and the MLKEMSeed slice are the caller's to clear.

func (*Identity) Private

func (id *Identity) Private() (IdentityPrivateKey, error)

Private returns the compact ML-DSA seed, Ed25519 seed, and independent X25519 private scalar for durable storage. The caller owns and must clear the returned bytes. The result is not for a log.

func (*Identity) Public

func (id *Identity) Public() PublicIdentity

Public returns the complete hybrid public identity. It returns the zero value after Zero.

func (*Identity) SignedPreKeyFromPrivate

func (id *Identity) SignedPreKeyFromPrivate(restore SignedPreKeyRestoreParams) (*SignedPreKeyPair, error)

SignedPreKeyFromPrivate restores a signed-prekey pair after re-deriving its public key and validating its identity signature and expected identifier. The pair keeps the public identity key of id, whose signature it checked: Accept and OpenEnvelope refuse it with another Identity.

Everything it is given is local input, and its errors say which part is at fault. The checks run in the order of this list, and the first that fails gives the error:

  • ErrUsage: a nil Identity.
  • ErrZeroed: the Identity was zeroed.
  • ErrUsage: a SignParams that NewSignedPreKey would refuse, with a Context or a PartyID that is empty, too long or not valid UTF-8, or a Timestamp that is zero, falls within the first second of the year 1 or falls outside the years 1 to 9999 UTC; then an ExpectedID that is unset.
  • ErrInvalidKey: an X25519 private scalar of all zero bytes.
  • ErrKeyMismatch: an X25519 private scalar that does not give ExpectedX25519Public. No scalar gives a value of small order or one that is not canonically encoded, so such an expected value is reported as this mismatch and not as ErrSmallOrderKey or ErrInvalidKey.
  • ErrInvalidSignature: a Signature that is not SignatureSize bytes, or that the Identity did not make over ExpectedX25519Public for this SignParams.
  • ErrKeyMismatch: an ExpectedID that is not the identifier of this Identity, SignParams and ExpectedX25519Public.

The parameters arrive by value, so the function holds its own copy of the private scalar: it clears that copy before it returns. The caller's value is the caller's to clear.

func (*Identity) Zero

func (id *Identity) Zero()

Zero clears package-owned seeds and scalars and overwrites the opaque ML-DSA key value held by the Identity. The Identity is unusable afterwards. Go's cryptographic module does not expose inaccessible temporary copies made while generating or expanding the ML-DSA key.

type IdentityPrivateKey

type IdentityPrivateKey []byte

IdentityPrivateKey is the persisted private identity encoding. Its 96 bytes are, in order, the ML-DSA-87 seed, the Ed25519 seed, and the independent X25519 private scalar. It is a byte slice without a text form, so encoding/json and encoding/json/v2 write it as base64. The caller owns and must clear it. IdentityFromPrivate also requires the expected complete public identity, so a component change that alters the rederived public identity is refused. Two canonically clamped X25519 scalar encodings that rederive the same pinned base-point public value are both accepted. That restoration check does not claim that they act identically on every peer input.

func (IdentityPrivateKey) Zero

func (k IdentityPrivateKey) Zero()

Zero clears k. It is safe on nil and on a key of any length.

type InitialMessage

type InitialMessage struct {
	InitiatorID        string
	ResponderID        string
	AppInfo            string
	IdentityKey        PublicIdentity
	EphemeralKey       X25519PublicKey
	OneTimePreKeyID    OneTimePreKeyID
	SignedPreKeyID     SignedPreKeyID
	MLKEMCiphertext    MLKEMCiphertext
	InitiatorSignature []byte
	// contains filtered or unexported fields
}

InitialMessage is the authenticated 4DH handshake message. AppInfo is public application/channel metadata carried on the wire. Both party ids, AppInfo, both identity keys, the selected signed and one-time prekeys, the ephemeral key and the ML-KEM ciphertext are covered by InitiatorSignature. In the handshake of an Envelope that signature covers the sealed record as well, under a label of its own, and verifies only there.

InitiatorID, ResponderID and AppInfo are text: each is valid UTF-8, and a message in which one is not is refused by Marshal, by UnmarshalInitialMessage and by Accept. A composite literal of an InitialMessage must name its fields.

func UnmarshalInitialMessage

func UnmarshalInitialMessage(data []byte) (*InitialMessage, error)

UnmarshalInitialMessage decodes one canonical v1 initial handshake message and rejects trailing bytes. A party identifier or an application info that is not valid UTF-8 is refused with an error matching ErrWire, as an empty or overlong one is. The message it returns holds copies of what it reads and shares no memory with data, which the caller may change or reuse afterwards.

func (*InitialMessage) Digest

func (m *InitialMessage) Digest() (InitialMessageDigest, error)

Digest returns SHA-384 over the canonical wire encoding of m through the ML-KEM ciphertext, excluding only InitiatorSignature, which is the final fixed-size field. It therefore covers every signed-content field carried by InitialMessage while assigning every valid signature witness for those bytes the same digest. Context, the responder identity, and the signed- and one-time-prekey public keys are also authenticated but reconstructed outside this wire value, so they are not represented by Digest.

The digest is public and unauthenticated. It says that two messages carry the same wire content, never that either is genuine. A cache shared across responders or deployments must include and validate its receiver, Context, and trust/prekey scope as part of the cache key or retained state.

Digest returns an error matching ErrUsage for a nil message or one Marshal rejects.

func (*InitialMessage) Marshal

func (m *InitialMessage) Marshal() ([]byte, error)

Marshal encodes the initial handshake message in the canonical v1 wire format. It returns an error matching ErrUsage for a nil message, an InitiatorID, ResponderID or AppInfo that is empty, too long or not valid UTF-8, a prekey identifier that is not canonical, and an InitiatorSignature that is not SignatureSize bytes.

type InitialMessageDigest

type InitialMessageDigest [sha512.Size384]byte

InitialMessageDigest identifies the canonical wire-carried content of an InitialMessage. It is the key a responder indexes handshake state by to recognize a retransmission, including one carrying another valid randomized composite-signature witness for the same content. Its text form is lower-case hexadecimal, 96 characters.

func (InitialMessageDigest) MarshalText

func (d InitialMessageDigest) MarshalText() ([]byte, error)

MarshalText returns the digest as String gives it.

func (InitialMessageDigest) String

func (d InitialMessageDigest) String() string

String returns the digest as 96 lower-case hexadecimal characters, two for each byte in order.

func (*InitialMessageDigest) UnmarshalText

func (d *InitialMessageDigest) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

type InitiateOptions

type InitiateOptions struct {
	InitiatorID string
	AppInfo     string
	// contains filtered or unexported fields
}

InitiateOptions supplies the initiator's local party identifier and the public application/channel binding carried in and authenticated by the initial message. Both fields must be non-empty, at most 255 bytes and valid UTF-8.

type MLKEMCiphertext

type MLKEMCiphertext [MLKEMCiphertextSize]byte

MLKEMCiphertext is the ML-KEM-1024 ciphertext of an InitialMessage, of MLKEMCiphertextSize bytes. Its text form is lower-case hexadecimal, 3136 characters.

func (MLKEMCiphertext) MarshalText

func (c MLKEMCiphertext) MarshalText() ([]byte, error)

MarshalText returns the ciphertext as String gives it.

func (MLKEMCiphertext) String

func (c MLKEMCiphertext) String() string

String returns the ciphertext as 3136 lower-case hexadecimal characters, two for each byte in order.

func (*MLKEMCiphertext) UnmarshalText

func (c *MLKEMCiphertext) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

type MLKEMEncapsulationKey

type MLKEMEncapsulationKey [MLKEMEncapsulationKeySize]byte

MLKEMEncapsulationKey is an ML-KEM-1024 encapsulation key, the public half of a one-time prekey's ML-KEM key pair, of MLKEMEncapsulationKeySize bytes. Its text form is lower-case hexadecimal, 3136 characters.

func (MLKEMEncapsulationKey) MarshalText

func (k MLKEMEncapsulationKey) MarshalText() ([]byte, error)

MarshalText returns the encapsulation key as String gives it.

func (MLKEMEncapsulationKey) String

func (k MLKEMEncapsulationKey) String() string

String returns the encapsulation key as 3136 lower-case hexadecimal characters, two for each byte in order.

func (*MLKEMEncapsulationKey) UnmarshalText

func (k *MLKEMEncapsulationKey) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

type MLKEMSeed

type MLKEMSeed []byte

MLKEMSeed is the seed of an ML-KEM-1024 decapsulation key, the private half of a one-time prekey's ML-KEM key pair, as a stored or restored one-time prekey holds it: 64 bytes, from which the decapsulation key is derived. It is a byte slice with no text form of its own, so encoding/json and encoding/json/v2 write it as base64 and encoding/gob writes its bytes. String, GoString, log/slog and fmt with every verb but %w show none of it; %p prints its address. fmt prints its bytes where it calls no method: in a field that is not exported of a caller's struct, and inside a value it prints in its wrong-verb notation (see the package documentation). The value is the caller's to protect and clear, in every form it is kept in.

func (MLKEMSeed) Format

func (s MLKEMSeed) Format(f fmt.State, _ rune)

Format writes "MLKEMSeed(…)" for every verb fmt calls it with, %x, %X, %d, %q and %#v included, and no byte of the seed: fmt prints a struct that holds the seed, such as OneTimePreKeyRestoreParams or prekey.PrivateOneTimePreKey, with that in place of the seed, except where fmt calls no method, as for X25519PrivateKey: for %p and %w, in a field that is not exported and in its wrong-verb notation. A nil seed prints the same.

func (MLKEMSeed) GoString

func (s MLKEMSeed) GoString() string

GoString returns "MLKEMSeed(…)", as String does.

func (MLKEMSeed) LogValue

func (s MLKEMSeed) LogValue() slog.Value

LogValue returns "MLKEMSeed(…)" as a string, which log/slog writes in place of the seed, as X25519PrivateKey.LogValue does for a key.

func (MLKEMSeed) String

func (s MLKEMSeed) String() string

String returns "MLKEMSeed(…)" and no byte of the seed, so that a value written to a log by mistake shows none.

type OneTimePreKey

type OneTimePreKey struct {
	ID             OneTimePreKeyID
	X25519         X25519PublicKey
	MLKEM          MLKEMEncapsulationKey
	Signature      []byte
	SignedPreKeyID SignedPreKeyID
	// contains filtered or unexported fields
}

OneTimePreKey is the signed public one-time record selected for exactly one handshake. Its signature binds it to one identity, context, party and signed-prekey epoch. Its methods use pointer receivers because the record contains a full ML-KEM public key; callers should avoid unnecessary copies. A composite literal of a OneTimePreKey must name its fields.

func UnmarshalOneTimePreKey

func UnmarshalOneTimePreKey(data []byte) (*OneTimePreKey, error)

UnmarshalOneTimePreKey decodes one canonical v1 one-time-prekey record and rejects trailing bytes. Data that is not one such record, with another version or kind, a field cut short, an identifier that is not canonical or bytes after the record, is refused with an error matching ErrWire. The record it returns holds copies of what it reads and shares no memory with data, which the caller may change or reuse afterwards.

func (*OneTimePreKey) Digest

func (k *OneTimePreKey) Digest() OneTimePreKeyDigest

Digest returns the stable digest a OneTimePreKeyStore uses as the TakeAndTombstone compare-and-swap guard. It returns the zero digest for a nil receiver or a manually assembled record containing a field too large for the canonical uint32 length prefix.

func (*OneTimePreKey) Marshal

func (k *OneTimePreKey) Marshal() ([]byte, error)

Marshal encodes the one-time prekey in the canonical v1 wire format. It returns an error matching ErrUsage for a nil record, an ID or SignedPreKeyID that is not canonical, the zero value included, and a Signature that is not SignatureSize bytes.

func (*OneTimePreKey) Verify

Verify checks the one-time prekey's signature and epoch binding against an already verified bundle. A nil record, a nil bundle and a VerifiedBundle that Bundle.Verify did not return are the caller's mistake and return an error matching ErrUsage.

Each call returns a separate single-use capability: two calls on one record return two values that can each be consumed once, and the second does not know that the first was used. Do not verify one record twice; verify each record the directory reserved once, and initiate with it once.

type OneTimePreKeyDigest

type OneTimePreKeyDigest [sha512.Size384]byte

OneTimePreKeyDigest identifies one complete OneTimePreKey: its signed-prekey id, its own id, both public keys and the signature. It is the value a OneTimePreKeyStore compares in TakeAndTombstone before it hands a pair over. Its text form is lower-case hexadecimal, 96 characters.

func (OneTimePreKeyDigest) MarshalText

func (d OneTimePreKeyDigest) MarshalText() ([]byte, error)

MarshalText returns the digest as String gives it.

func (OneTimePreKeyDigest) String

func (d OneTimePreKeyDigest) String() string

String returns the digest as 96 lower-case hexadecimal characters, two for each byte in order.

func (*OneTimePreKeyDigest) UnmarshalText

func (d *OneTimePreKeyDigest) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

type OneTimePreKeyID

type OneTimePreKeyID struct {
	// contains filtered or unexported fields
}

OneTimePreKeyID is a canonical identifier for one hybrid one-time prekey. Its zero value is invalid. Parse values loaded from storage with ParseOneTimePreKeyID; values returned by this package are already valid.

OneTimePreKeyID is promised to stay comparable: two identifiers can be compared with ==, equal exactly when their text forms are, and an identifier can key a map, as a OneTimePreKeyStore that keeps each key pair under its identifier does.

func ParseOneTimePreKeyID

func ParseOneTimePreKeyID(value string) (OneTimePreKeyID, error)

ParseOneTimePreKeyID validates and returns a one-time-prekey identifier. A malformed value is reported as ErrWire, like any other malformed encoding; the empty string is malformed here, although UnmarshalText accepts empty text as the zero value.

func (OneTimePreKeyID) IsZero

func (id OneTimePreKeyID) IsZero() bool

IsZero reports whether id is the invalid zero value.

func (OneTimePreKeyID) MarshalBinary

func (id OneTimePreKeyID) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler, which is what encoding/gob uses to store an identifier and any value that contains one. The bytes are those of MarshalText: the canonical lowercase hexadecimal form, or none for the zero value.

func (OneTimePreKeyID) MarshalText

func (id OneTimePreKeyID) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (OneTimePreKeyID) String

func (id OneTimePreKeyID) String() string

String returns the canonical lowercase hexadecimal representation, or an empty string for the invalid zero value.

func (*OneTimePreKeyID) UnmarshalBinary

func (id *OneTimePreKeyID) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler. It accepts what UnmarshalText accepts and refuses the rest in the same way: empty data gives the zero value, data that is not a canonical identifier returns an error matching ErrWire, and a nil receiver an error matching ErrUsage.

func (*OneTimePreKeyID) UnmarshalText

func (id *OneTimePreKeyID) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler. Empty text gives the zero value. Any other text is read as ParseOneTimePreKeyID reads it: text that is not a canonical identifier returns an error matching ErrWire. A nil receiver returns an error matching ErrUsage. On an error the receiver is left as it was.

type OneTimePreKeyPair

type OneTimePreKeyPair struct {
	// contains filtered or unexported fields
}

OneTimePreKeyPair owns the one-time X25519 scalar and ML-KEM decapsulation key. Accept consumes and zeroes it after one use.

func (*OneTimePreKeyPair) Format

func (k *OneTimePreKeyPair) Format(f fmt.State, _ rune)

Format writes "OneTimePreKeyPair(…)" for every verb fmt calls it with, as Identity.Format writes its name, and nothing of the pair's state. The scalar and the seed that Private returns are an X25519PrivateKey and an MLKEMSeed, which print as their masks.

func (*OneTimePreKeyPair) ID

ID returns the one-time-prekey identifier.

func (*OneTimePreKeyPair) Private

func (k *OneTimePreKeyPair) Private() (x25519 X25519PrivateKey, kemSeed MLKEMSeed, err error)

Private returns copies of both one-time private contributions, of the types OneTimePreKeyRestoreParams holds them in. The caller owns and must clear the returned scalar and ML-KEM seed. String, log/slog and fmt with every verb but %p and %w show none of their bytes; MarshalText writes the scalar, and encoding/json the seed as base64, for a store.

func (*OneTimePreKeyPair) Public

func (k *OneTimePreKeyPair) Public() OneTimePreKey

Public returns an independent copy of the signed public one-time record.

func (*OneTimePreKeyPair) Zero

func (k *OneTimePreKeyPair) Zero()

Zero destroys both one-time private contributions. It is safe to call more than once.

type OneTimePreKeyRestoreParams

type OneTimePreKeyRestoreParams struct {
	SignParams           SignParams
	SignedPreKeyPublic   X25519PublicKey
	ID                   OneTimePreKeyID
	ExpectedX25519Public X25519PublicKey
	ExpectedMLKEMPublic  MLKEMEncapsulationKey
	X25519Private        X25519PrivateKey
	MLKEMSeed            MLKEMSeed
	Signature            []byte
	// contains filtered or unexported fields
}

OneTimePreKeyRestoreParams contains both persisted one-time private contributions and the public values required for fail-closed restoration.

func (OneTimePreKeyRestoreParams) LogValue

func (p OneTimePreKeyRestoreParams) LogValue() slog.Value

LogValue returns the parameters as a group of their fields, as SignedPreKeyRestoreParams.LogValue does, the ML-KEM seed shown as "MLKEMSeed(…)". Log a pointer to the parameters, for the reason given there.

type OneTimePreKeyStore

type OneTimePreKeyStore interface {
	Lookup(ctx context.Context, id OneTimePreKeyID) (OneTimePreKey, error)
	TakeAndTombstone(ctx context.Context, id OneTimePreKeyID, expectedDigest OneTimePreKeyDigest) (*OneTimePreKeyPair, error)
}

OneTimePreKeyStore is the receiver's rollback-sensitive persistence boundary. Lookup returns public material without consuming it, allowing ake to reject forged messages without burning keys. TakeAndTombstone atomically removes the matching private key and durably records its non-expiring tombstone before returning ownership of the pair. expectedDigest is a CAS guard against replacing the record between the two calls. A store should return a nil pair with every error. Accept defensively takes ownership of and zeroes a non-nil pair returned together with an error. Lookup and TakeAndTombstone must wrap ErrOneTimePreKeyUnavailable only when the named record is definitely absent or tombstoned. Other errors are backend failures; Accept reports ErrStore without exposing their text or sentinels, except for context.Canceled and context.DeadlineExceeded. A digest mismatch is a backend consistency failure and must return a backend-private error that does not wrap ErrKeyMismatch or another ake sentinel. A TakeAndTombstone error can be ambiguous: if the tombstone committed before the result was lost, retrying Accept finds it and returns ErrAuthentication. A consumed pair, returned or tombstoned without being returned, must leave no readable copy in any backup, replica, log or snapshot of the store, and across every replica of one store a pair goes to at most one caller: the forward secrecy of a first message depends on both (SPEC.md section 16).

Lookup runs before the sender is authenticated. As far as the store can make it so, it must cost the same whether or not the record exists, and it must do no work that depends on what the record holds: it returns the record as it is kept and does not verify it against the identity (OneTimePreKey.Verify), parse its keys or rebuild a private key. For a message it refuses, Accept takes the same steps whether the named prekey is stored or absent: it builds the transcript around the stored record, or around a placeholder of the same size, and verifies the sender's signature over it once. A Lookup that verified what it read would take two signature verifications and an ML-KEM parse longer for a stored prekey than for an absent one, and tell an unauthenticated sender which prekeys are stored. The steps are not guaranteed to take equal time: component signature verification can depend on the public bytes it verifies, and the stored record's public keys and the placeholder's differ. Rate-limit this unauthenticated operation even when the store follows this contract.

A store detects damage to what it keeps by its own integrity protection at rest, for example a checksum it verifies when it loads its state, or a verification of every record when it is restored, and not for each message. Where a store returns a damaged record as it is, an honest initiator's message that names it fails with ErrAuthentication when the damage is to the record's X25519 or ML-KEM public key, which the initiator's signature covers, and with an error matching ErrStore when it is to the record's own signature alone, which Accept verifies after the initiator's.

Accept calls Lookup once and then, only for a message whose initiator signature verified, TakeAndTombstone once. It makes both calls on the caller's goroutine, with the caller's context and with no lock of this package held, so a method may block for as long as that context allows and may use the Identity, the signed prekey and any other value of this package.

The context is the caller's limit on how long the call may take. A method that waits, for a lock, a disk or a network peer, is expected to stop waiting when the context is done and to return an error that wraps ctx.Err(), having changed nothing where it can still choose. Accept does not rely on that: it checks the context itself before each of the two calls and makes neither with a context that was done when the call began. A TakeAndTombstone that has committed returns the pair even when the context ended meanwhile; one that returns the context's error after committing is the ambiguous case above.

What Accept returns for each answer of the store:

  • Lookup returns an error that wraps ErrOneTimePreKeyUnavailable, or a record of another signed-prekey epoch than the message names: ErrAuthentication. The sender is not authenticated at that point, and the answer does not tell it whether the key exists;
  • TakeAndTombstone returns an error that wraps ErrOneTimePreKeyUnavailable: ErrOneTimePreKeyUnavailable itself, without the store's text. The message was authenticated and lost the take, to another Accept of the same message or to the retirement of the key's epoch;
  • either method returns any other error: an error matching ErrStore, which also matches context.Canceled or context.DeadlineExceeded when the store's error did, and nothing else of it;
  • Lookup returns a record with another id than the one asked for; or, for a message whose initiator signature verified, Lookup returned a record that the responder's identity did not sign, or TakeAndTombstone returns no pair, a pair that is not the record's, or a pair whose private keys were scrubbed: an error matching ErrStore.

This interface will not gain methods. A capability added to the package later is a separate optional interface that a store may also implement and that Accept looks for with a type assertion, as prekey.Backend describes for its own additions, so an implementation of these two methods keeps compiling and keeps its behaviour.

type PendingSession

type PendingSession struct {
	// contains filtered or unexported fields
}

PendingSession is the result of Accept. Accept has already matched the initiator against the caller's trusted identity and authenticated its signature over the complete handshake, but the receiver has not yet confirmed that the peer possesses the derived session key. PendingSession makes that state explicit: it has no Seal or raw-key access, so a caller cannot send secrets or grant session authority before the first authenticated record opens.

Call Open with the initiator's first ciphertext to authenticate it and obtain a full Session. An integration whose external record layer performs key confirmation may instead call ExportUnconfirmed once, before any failed Open, to obtain one transcript-bound key and consume the pending state. The external protocol must confirm possession before acting on that key.

A PendingSession must not be copied; always pass the *PendingSession. Its mutable state lives behind a pointer, so a value copy aliases the same consume-once slot, and go vet flags the copy. A PendingSession is not safe for concurrent use; serialize Open, ExportUnconfirmed, and Zero because each can transition or consume the pending state.

func Accept

Accept verifies every public input and the initiator signature before it asks the store to durably consume the selected one-time prekey. The returned PendingSession still requires first-record key confirmation through Open.

spk must be the signed prekey that msg.SignedPreKeyID names, which is not always the newest one: after a rotation, messages built from the previous bundle are still in flight and name the previous key. Select by that id. A responder that manages rotation with the prekey package calls Manager.WithSignedPreKey(msg.SignedPreKeyID, ...) and calls Accept inside the callback. Accept cannot tell a signed prekey chosen wrongly by its caller from a forged message: both return ErrAuthentication.

The caller's mistakes, the first two items below, are looked for before anything the message holds: what the message holds does not change the error that a call making one of them returns, and the store is not called. Accept returns:

  • an error matching ErrUsage for a nil ctx, id, spk, store or msg, a signed prekey that no constructor returned, a signed prekey that another identity than id signed, an ExpectedAppInfo or ExpectedInitiatorID that is empty, too long or not valid UTF-8, an ExpectedAppInfo that begins with the prefix reserved for envelopes, and an ExpectedIdentity that is not a usable identity key;
  • ErrZeroed for an Identity or signed prekey that was scrubbed, and for an Identity that no constructor returned;
  • an error matching ErrInvalidMessage for a message whose application info is empty, longer than MaxAppInfoLen or not valid UTF-8, whose initiator or responder id is not valid UTF-8, or whose prekey identifiers are not well formed;
  • an error matching ErrKeyMismatch when the message's application info, initiator id, initiator identity or responder id is not the expected one. A message built in memory whose initiator or responder id is empty or longer than MaxPartyIDLen is among these: no expected value is either, so it is refused as naming another party and not as a malformed message. This is decided before the signature is checked;
  • ErrAuthentication for everything else a sender can cause: a signature that does not verify, a one-time prekey that is unknown, already consumed or of another signed-prekey epoch, and a signed-prekey id that is not spk's;
  • ErrSmallOrderKey, or an error matching ErrInvalidKey, for a signed message whose ephemeral key is a small-order point or is not canonically encoded;
  • an error matching ErrInvalidSignature when the retained signed prekey does not verify under id, which would mean local state is inconsistent. Through this package's API it does not happen: a signed prekey that another identity signed is the ErrUsage above, and one that id signed keeps its signature;
  • an error matching ErrStore when the store fails, returns a record or key pair that is not the one asked for, or returns a key pair whose private keys were scrubbed. Where the store reported a context error, the result matches that as well;
  • ErrOneTimePreKeyUnavailable when the message authenticated and another Accept of the same message took the one-time prekey first, or the key's epoch was retired before this call took it;
  • ctx.Err() as it is, context.Canceled or context.DeadlineExceeded, when ctx is done before the store is asked for the record or before it is asked to consume it. The store is not called with such a context, nothing is consumed, and the same message is accepted by a later call with a live context. This error does not match ErrStore.

Nothing is consumed by a call that fails before the store's TakeAndTombstone. An error from TakeAndTombstone itself, reported as ErrStore, leaves it unknown whether the one-time prekey was consumed: a retry then returns ErrAuthentication if it was. Such an error matches context.Canceled or context.DeadlineExceeded as well when the store reported the end of the context, so a caller that handles the two apart tests for ErrStore before it tests for a context error: only a context error that does not match ErrStore says that nothing was consumed.

func (*PendingSession) ExportUnconfirmed

func (p *PendingSession) ExportUnconfirmed(label string) ([32]byte, error)

ExportUnconfirmed derives one transcript-bound 32-byte key for a caller-owned external record layer, then scrubs and consumes the pending session. It is the narrow alternative for integrations that perform key confirmation outside Session.Open. Accept has authenticated the expected peer's identity signature, but the external protocol must still confirm possession before releasing secrets or granting authority.

ExportUnconfirmed is unavailable after any failed Open, preventing a caller from treating failed built-in authentication as permission to fall back to an unauthenticated path. label is neither empty nor longer than Session.Export takes. External integrations must choose their own domain label; "ake-record-root-v1" is reserved for the package's record integration and is rejected here, and so are the labels of a record.Link and the rekey input listed at ConsumeExport. A label error does not consume the pending session. On success, every copy of this PendingSession is spent and the caller owns zeroization of the returned array.

The error matches ErrUsage after a failed Open, for a nil PendingSession and for a label that is empty, longer than Session.Export takes or reserved, and is ErrSessionClosed for a PendingSession that Open promoted, that an earlier export spent or that was zeroed.

Example

ExamplePendingSession_ExportUnconfirmed shows the consume-once handoff for an external protocol that performs its own possession confirmation.

// examplePendingPair runs the handshake shown in the package example up to
// Accept, leaving the responder unconfirmed.
alice, bobPending, cleanup, err := examplePendingPair("method-example/external")
if err != nil {
	panic(err)
}
defer cleanup()
aliceKey, err := alice.ConsumeExport("example-external-root-v1")
if err != nil {
	panic(err)
}
defer clear(aliceKey[:])
bobKey, err := bobPending.ExportUnconfirmed("example-external-root-v1")
if err != nil {
	panic(err)
}
defer clear(bobKey[:])
fmt.Println(aliceKey == bobKey)
Output:
true

func (*PendingSession) Format

func (p *PendingSession) Format(f fmt.State, _ rune)

Format writes "PendingSession(…)" for every verb fmt calls it with, as Identity.Format writes its name, and nothing of the session's state. The key that ExportUnconfirmed returns is bytes that fmt prints in full.

func (*PendingSession) Open

func (p *PendingSession) Open(nonce, ciphertext, aad []byte) (*Session, []byte, error)

Open authenticates the initiator by opening its first ciphertext under the derived key, and on success promotes to a full Session (returned alongside the plaintext). The caller then owns the returned Session: after a successful Open, Zero on this PendingSession is a no-op, so scrub the returned Session, not the pending one.

A failed Open does not consume the PendingSession, but the only sound responses are to retry Open with valid input, or to Zero and discard. A transport that supports retransmission must retain this PendingSession under a bounded lifetime and route the same authenticated InitialMessage content back to it; calling Accept again finds the OTK tombstone and cannot reconstruct this state. Index by InitialMessage.Digest, which covers the wire-carried signed-content prefix but not the randomized composite-signature witness, not by its OTK id. A cache shared across receivers or deployments must also bind and validate its receiver, Context, and trust/prekey scope. Keep the entry for its bounded lifetime after a failed Open, neither dropping it nor extending it, so that replaying the message with a damaged record gains nothing. A PendingSession is not safe for concurrent use: when copies of one message can arrive on two paths, serialize Open on the held state. After any failed Open, ExportUnconfirmed is permanently disabled for this pending state: falling back to an unconfirmed external path would be an authentication bypass, not error handling.

A failed Open is one in which the record was refused, with any of the errors of Session.Open: ErrAuthentication for a record that did not authenticate under this derivation, an error matching ErrWire for a nonce that is not 12 bytes, and one matching ErrUsage for an aad longer than BuildAAD accepts as the field after the 48-byte transcript hash, 2^32 - 1 bytes, or 2^31 - 57 bytes on a platform whose int has 32 bits. Each of them ends the unconfirmed export. A record that arrives malformed is as much a sign of interference as one that fails to authenticate, and whoever can alter a record in transit must not be able to choose, by how they alter it, whether the caller is left with the unconfirmed path.

A retransmission can also arrive after Open succeeded, when the responder's reply was lost. Accept then returns ErrAuthentication for it, as for any spent one-time prekey, and an initiator that hears nothing starts a new handshake. A responder that wants the initiator to recover without one remembers, for a bounded time, the digest of each confirmed InitialMessage together with a digest of the first record that confirmed it, and resends its original sealed reply only when both match. Matching both identifies the exchange the reply belongs to. It does not stop a replay: the first record is as public as the InitialMessage, so anyone who recorded the two can present them again and draw the same ciphertext, which tells them nothing new. The limit on how often such a reply is resent, for each message and overall, is therefore required, not optional. A different first record under a confirmed message is not a forgery; it is ordinary traffic for the established Session, which authenticates it.

func (*PendingSession) Zero

func (p *PendingSession) Zero()

Zero scrubs the pending session's key material.

type PublicIdentity

type PublicIdentity [publicIdentitySize]byte

PublicIdentity is the fixed hybrid public identity. Its bytes are, in order, an ML-DSA-87 public key, an Ed25519 public key, and an independent X25519 public key. Its text form is lower-case hexadecimal.

func (PublicIdentity) MarshalText

func (k PublicIdentity) MarshalText() ([]byte, error)

MarshalText returns the identity key as String gives it.

func (PublicIdentity) String

func (k PublicIdentity) String() string

String returns the identity key as lower-case hexadecimal characters, two for each byte in order.

func (*PublicIdentity) UnmarshalText

func (k *PublicIdentity) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote as exactly two hexadecimal characters per identity byte. Each character is a digit or a letter from a to f in lower case. It returns an error matching ErrWire for anything else, which includes upper-case letters, a prefix, spaces, the empty text and every other length, and one matching ErrUsage for a nil receiver, and leaves the key as it was. The error states the length of the text it refuses and quotes its first 32 bytes at most.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is the authenticated channel established by a handshake. It holds the raw shared secret plus two directional AES-256-GCM keys derived from it — one this endpoint seals with, one it opens with — so the two peers never encrypt under the same key or share a nonce space. Every Seal/Open also binds the transcript hash TH (both party ids and identity keys, both prekey identifiers and public keys, the ephemeral and the KEM ciphertext) into the AEAD, so misbinding, reflection and substitution are prevented even when the caller passes no additional AAD. The composite signature authenticates that content during the handshake; its randomized signature witness is deliberately not part of TH.

A Session must not be copied; always pass the *Session. Its mutable state lives behind a pointer, so a value copy would alias that state rather than duplicate it, and go vet flags the copy. Multiple Seal and Open calls may run concurrently on a live Session, including with each other. Zero may also run concurrently: operations already holding the session complete before its keys are scrubbed, and later operations return ErrSessionClosed. Seal takes a fresh random 96-bit nonce per message, drawn by Go's cryptographic module, and enforces a budget of 2^32 messages, after which it returns ErrSessionExhausted rather than risk a nonce collision; a long-lived, very-high-volume channel should layer a ratchet (see Export) rather than reuse one Session indefinitely.

func (*Session) Binding

func (s *Session) Binding() (SessionBinding, error)

Binding returns the stable channel binding authenticated by this handshake: SHA-384 over the suite, context, application label, both party ids, and both raw identity keys. It is identical at both endpoints and across fresh handshakes for the same logical channel, but excludes ephemeral/prekey state. Record rekeying uses it to reject a valid Session for another peer or use. It is a public value, which may be logged and printed; a closed Session returns ErrSessionClosed and the zero value.

func (*Session) ConsumeExport

func (s *Session) ConsumeExport(label string) ([32]byte, error)

ConsumeExport atomically derives the same key as Export and then scrubs and closes the Session before returning it. Exactly one concurrent caller can succeed. Use it when the exported key initializes state whose counters or nonces would be unsafe to restart from the same Session; record.NewChannel uses this ownership-transfer operation.

Four labels are reserved and are refused by Export, ConsumeExport and ExportUnconfirmed alike, with an error matching ErrUsage: three for a record.Link, "ake-record-channel-tag-v1", "ake-record-link-refusal-v1" and "ake-record-link-root-v1", and "ake-record-rekey-input-v1" for a Channel's rekey. A Link's channels and a rekey's keys are derived from them, and an application that could export under those labels would hold the same keys. A Link, Channel.StageRekey and Channel.AddRekeyCandidate take them in one step of their own that closes the Session.

The fifth reserved label, "ake-record-root-v1", is refused by Export and ExportUnconfirmed and accepted here: only record.NewChannel takes its key from it through this call, which closes the Session, so no second Channel is keyed from one Session.

Validation or derivation failure leaves the Session live. On success the returned [32]byte is the caller's key material and must be cleared when no longer needed.

func (*Session) Export

func (s *Session) Export(label string) ([32]byte, error)

Export derives a 32-byte key from the session for a caller-named purpose (a ratchet root, a channel-binding value, an application subkey):

Export(label) = HKDF-Expand(SK, BuildAAD("ake-export-v1", Suite, TH, label))

The derivation binds the session transcript hash TH (which itself binds both complete identities, both responder prekeys, the ephemeral, and the KEM contribution, but not the randomized signature witness) together with the suite and the caller's label in a framing that is injective, so the derivation separates exports by transcript, suite and label: keys exported under different peers or labels are independent, and equal only with negligible probability. Export is the integration seam for building on top of a session; the raw session secret is not exposed. label must not be empty, and it is at most 2^32 - 1 bytes, the longest field BuildAAD frames, or 2^31 - 170 bytes on a platform whose int has 32 bits, so that the label and the 169 bytes framed before it are a length there. Export, ConsumeExport and ExportUnconfirmed refuse an empty or a longer label with an error matching ErrUsage. The result is a [32]byte value, so the caller owns zeroization: clear it in place when done, and avoid passing it around by value, since each copy is separate key material to scrub. The label "ake-record-root-v1" is reserved for the consuming record-layer integration and is rejected here so a reusable export cannot duplicate that record root. ConsumeExport accepts it because success closes the Session. The labels of a record.Link and the rekey input listed at ConsumeExport are rejected here too.

Example

ExampleSession_Export shows a reusable, transcript-bound application key. Both authenticated endpoints derive the same value under the same label.

// exampleConfirmedPair runs the handshake shown in the package example.
alice, bob, cleanup, err := exampleConfirmedPair("method-example/export")
if err != nil {
	panic(err)
}
defer cleanup()
aliceKey, err := alice.Export("example-file-key-v1")
if err != nil {
	panic(err)
}
defer clear(aliceKey[:])
bobKey, err := bob.Export("example-file-key-v1")
if err != nil {
	panic(err)
}
defer clear(bobKey[:])
fmt.Println(aliceKey == bobKey)
Output:
true

func (*Session) Format

func (s *Session) Format(f fmt.State, _ rune)

Format writes "Session(…)" for every verb fmt calls it with, as Identity.Format writes its name, and nothing of the session's state. The exports it returns are bytes that fmt prints in full; its binding is a SessionBinding, a public value, which prints as its text form.

func (*Session) Open

func (s *Session) Open(nonce, ciphertext, aad []byte) ([]byte, error)

Open decrypts and authenticates ciphertext under this endpoint's recv key. A message this endpoint sealed itself will not open (wrong directional key), so reflection is rejected. Cryptographic failure returns ErrAuthentication without exposing the underlying cipher error. So does a ciphertext longer than AES-GCM opens, more than 2^36 - 16 bytes, or more than 2^31 - 13 bytes on a platform whose int has 32 bits, which Open refuses by its length before it copies any of it.

Two errors say that the record was not tried at all. A nonce that is not 12 bytes returns an error matching ErrWire: the nonce arrives with the record, and one of another length is a malformed record. An aad longer than BuildAAD accepts as the field after the 48-byte transcript hash, 2^32 - 1 bytes, or 2^31 - 57 bytes on a platform whose int has 32 bits, returns an error matching ErrUsage. On a PendingSession each of the two, like ErrAuthentication, is a failed Open and ends the unconfirmed export (see PendingSession.Open). Open checks the record before the aad: it returns the error for an aad only when the nonce is 12 bytes and the ciphertext is not longer than AES-GCM opens, and otherwise the error for the record, whatever the aad. A nil Session returns an error matching ErrUsage, and a Session that was scrubbed, or that no handshake returned, ErrSessionClosed.

func (*Session) Role

func (s *Session) Role() (SessionRole, error)

Role returns this endpoint's role from the authenticated handshake that created the Session. Callers cannot override it when constructing a record channel, because doing so could collapse directional key and nonce domains.

func (*Session) Seal

func (s *Session) Seal(plaintext, aad []byte) (nonce, ciphertext []byte, err error)

Seal encrypts plaintext with a fresh random nonce under this endpoint's send key, binding the transcript and the caller's aad. The nonce is drawn by Go's cryptographic module, as cipher.NewGCMWithRandomNonce draws it (from its SP 800-90A DRBG in FIPS mode, from the operating system's generator otherwise), and not from crypto/rand.Reader or another source this package or its caller supplies.

A Session may Seal at most 2^32 messages; beyond that Seal returns ErrSessionExhausted without encrypting, because the random-nonce collision risk stops being negligible. The budget is per session state and bounds a single directional key only when that key lives in exactly one session: NIST SP 800-38D caps random-nonce use at 2^32 invocations per key, so the caller must also prevent re-deriving or resuming the same key through OTK reuse or state rollback. Re-handshake for a fresh Session, or use Export to seed a caller-owned ratchet.

Seal refuses a plaintext longer than AES-GCM seals, more than 2^36 - 32 bytes, or more than 2^31 - 29 bytes on a platform whose int has 32 bits, with an error matching ErrUsage. It refuses it by its length, before it counts the seal against the budget, and the Session seals on as before. An aad longer than BuildAAD accepts as the field after the 48-byte transcript hash, 2^32 - 1 bytes, or 2^31 - 57 bytes on a platform whose int has 32 bits, returns an error matching ErrUsage, also before the seal is counted against the budget.

func (*Session) Zero

func (s *Session) Zero()

Zero scrubs the shared secret and both directional keys. The Session is unusable afterwards. Because the state is shared, Zero through any copy of a Session closes every copy.

type SessionBinding

type SessionBinding [48]byte

SessionBinding is the channel binding of a Session, which Session.Binding returns: SHA-384 over the suite, the context, the application label, both party ids and both identity keys, as SPEC.md section 9 defines it. It is a public value, the same at both endpoints and for every handshake of the same two parties under the same context and label. Its text form is lower-case hexadecimal, 96 characters.

func (SessionBinding) MarshalText

func (b SessionBinding) MarshalText() ([]byte, error)

MarshalText returns the binding as String gives it.

func (SessionBinding) String

func (b SessionBinding) String() string

String returns the binding as 96 lower-case hexadecimal characters, two for each byte in order.

func (*SessionBinding) UnmarshalText

func (b *SessionBinding) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

type SessionRole

type SessionRole uint8

SessionRole is this endpoint's authenticated role in a Session.

Each role has a name, which String returns and MarshalText writes, and the names are part of what a stored or logged SessionRole holds, so they stay as they are: "unknown" for RoleUnknown, "initiator" for RoleInitiator and "responder" for RoleResponder.

const (
	// RoleUnknown is the invalid zero value of SessionRole.
	RoleUnknown SessionRole = iota
	// RoleInitiator identifies the endpoint that created the initial message.
	RoleInitiator
	// RoleResponder identifies the endpoint that accepted the initial message.
	RoleResponder
)

func (SessionRole) MarshalText

func (r SessionRole) MarshalText() ([]byte, error)

MarshalText returns the role as String gives it, so that a value holding a SessionRole encodes it as a name: encoding/json writes a string. A value that has no name is written as SessionRole(n).

func (SessionRole) String

func (r SessionRole) String() string

String returns the authenticated role name. Unknown numeric values are formatted as SessionRole(n) so logs do not silently collapse corrupted or future values into RoleUnknown.

func (*SessionRole) UnmarshalText

func (r *SessionRole) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote: a role's name, or SessionRole(n) for any n from 0 to 255, also one that has a name. It returns an error matching ErrWire for anything else, and one matching ErrUsage for a nil receiver, and leaves the role as it was. The error for a refused text gives its length and quotes at most its first 32 bytes, so that an error is not as long as whatever the caller was given to decode.

type SignParams

type SignParams struct {

	// Context is the deployment's signing context: 1 to MaxContextLen bytes
	// of valid UTF-8.
	Context string
	// PartyID is the party the prekey is signed for: 1 to MaxPartyIDLen
	// bytes of valid UTF-8.
	PartyID string
	// Timestamp is the time of the signed-prekey epoch. It must not be zero,
	// nor fall within the first second of the year 1: it is signed as a
	// whole second, and that one is the second of the zero time. A signed
	// prekey is signed, and restored, only for a second within the years 1
	// to 9999 UTC, a range within the years 0 to 9999 for which encoding/json
	// writes a time.Time.
	Timestamp time.Time
	// contains filtered or unexported fields
}

SignParams are the signed-prekey domain parameters. Timestamp is canonicalized to a whole UTC second.

type SignedPreKeyID

type SignedPreKeyID struct {
	// contains filtered or unexported fields
}

SignedPreKeyID is a canonical identifier for one signed-prekey epoch. Its zero value is invalid. Parse values loaded from storage with ParseSignedPreKeyID; values returned by this package are already valid.

SignedPreKeyID is promised to stay comparable: two identifiers can be compared with ==, equal exactly when their text forms are, and an identifier can key a map, as a store that keeps each epoch under its identifier does.

func ParseSignedPreKeyID

func ParseSignedPreKeyID(value string) (SignedPreKeyID, error)

ParseSignedPreKeyID validates and returns a signed-prekey identifier. A malformed value is reported as ErrWire, like any other malformed encoding; the empty string is malformed here, although UnmarshalText accepts empty text as the zero value.

func (SignedPreKeyID) IsZero

func (id SignedPreKeyID) IsZero() bool

IsZero reports whether id is the invalid zero value.

func (SignedPreKeyID) MarshalBinary

func (id SignedPreKeyID) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler, which is what encoding/gob uses to store an identifier and any value that contains one. The bytes are those of MarshalText: the canonical lowercase hexadecimal form, or none for the zero value.

func (SignedPreKeyID) MarshalText

func (id SignedPreKeyID) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (SignedPreKeyID) String

func (id SignedPreKeyID) String() string

String returns the canonical lowercase hexadecimal representation, or an empty string for the invalid zero value.

func (*SignedPreKeyID) UnmarshalBinary

func (id *SignedPreKeyID) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler. It accepts what UnmarshalText accepts and refuses the rest in the same way: empty data gives the zero value, data that is not a canonical identifier returns an error matching ErrWire, and a nil receiver an error matching ErrUsage.

func (*SignedPreKeyID) UnmarshalText

func (id *SignedPreKeyID) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler. Empty text gives the zero value. Any other text is read as ParseSignedPreKeyID reads it: text that is not a canonical identifier returns an error matching ErrWire. A nil receiver returns an error matching ErrUsage. On an error the receiver is left as it was.

type SignedPreKeyPair

type SignedPreKeyPair struct {
	// contains filtered or unexported fields
}

SignedPreKeyPair is the medium-term, identity-signed X25519 prekey. It authenticates the responder and contributes DH1 and DH3. ML-KEM material is deliberately one-time and lives in OneTimePreKeyPair instead.

func (*SignedPreKeyPair) Format

func (k *SignedPreKeyPair) Format(f fmt.State, _ rune)

Format writes "SignedPreKeyPair(…)" for every verb fmt calls it with, as Identity.Format writes its name, and nothing of the pair's state. The scalar that Private returns is an X25519PrivateKey, which prints as its mask.

func (*SignedPreKeyPair) ID

ID returns the stable identifier derived from the signing identity, the signed prekey and its signing parameters.

func (*SignedPreKeyPair) Params

func (k *SignedPreKeyPair) Params() SignParams

Params returns the context, party, and canonical timestamp signed into the prekey.

func (*SignedPreKeyPair) Private

func (k *SignedPreKeyPair) Private() (X25519PrivateKey, error)

Private returns a copy of the signed prekey's X25519 private scalar, of the type SignedPreKeyRestoreParams holds it in. The caller owns and must clear the returned value. String, log/slog and fmt with every verb but %p and %w show none of its bytes; MarshalText writes them, for a store.

func (*SignedPreKeyPair) Public

func (k *SignedPreKeyPair) Public() (x25519 X25519PublicKey, sig []byte)

Public returns the signed prekey's public X25519 value and an independent copy of its identity signature.

func (*SignedPreKeyPair) Zero

func (k *SignedPreKeyPair) Zero()

Zero destroys the signed prekey's private scalar. It is safe to call more than once.

type SignedPreKeyRestoreParams

type SignedPreKeyRestoreParams struct {
	SignParams           SignParams
	ExpectedX25519Public X25519PublicKey
	X25519Private        X25519PrivateKey
	Signature            []byte
	ExpectedID           SignedPreKeyID
	// contains filtered or unexported fields
}

SignedPreKeyRestoreParams contains the persisted signed-prekey material and expected public values required for fail-closed restoration.

func (SignedPreKeyRestoreParams) LogValue

func (p SignedPreKeyRestoreParams) LogValue() slog.Value

LogValue returns the parameters as a group of their fields, by their names, for log/slog to write in place of the encoding/json form that its JSONHandler would write in full: each public value as its text form, the signature as lower-case hexadecimal, and the private scalar as "X25519PrivateKey(…)". It reads no byte of the scalar, so what it returns holds no copy of it; the receiver is a value, so that slog finds the method on the parameters by value as well as by pointer, and the method clears that copy before it returns. Log a pointer to the parameters, not the parameters: a value given to slog is copied into the interface value of its attribute on the heap, a copy that neither this method nor the caller can clear.

type StatementBackend

type StatementBackend interface {
	Stage(ctx context.Context, keyID StatementKeyID, creationID StatementCreationID, state StatementPrivateState) error
	Activate(ctx context.Context, keyID StatementKeyID, creationID StatementCreationID) error
	Discard(ctx context.Context, keyID StatementKeyID, creationID StatementCreationID) error
	Transact(ctx context.Context, keyID StatementKeyID, operationID StatementOperationID, request StatementDigest, update StatementStateUpdate) ([]byte, error)
	Retire(ctx context.Context, keyID StatementKeyID) error
}

StatementBackend is the authoritative persistence and serialization boundary for forward-secure statement signing. Stage durably copies its borrowed state but keeps it unavailable to Transact. An exact retry of the same key id, creation id and state returns nil, even after Activate; every different existing value and every retired key id is ErrStatementConflict. Activate makes the staged state available and is idempotent. Discard destroys an absent, staged or active record for the matching creation id, writes the same permanent key-id tombstone as Retire, and is idempotent. Thus it also resolves an Activate that committed but reported an error. Stage, Activate, Discard, Transact and Retire are ordered by one authority across every process.

Transact serializes and fences operations for keyID. Before invoking update it checks for a completed operationID within keyID: an exact request-digest retry returns the committed receipt without invoking update, while a different digest is ErrStatementConflict. Otherwise it invokes update exactly once, then atomically replaces the state and durably stores operationID, request and receipt before returning the receipt. It clears the superseded state after commit. If commit succeeded but reporting it did not, a retry with the same operation id and digest returns the stored receipt. It must never restore a superseded private state. Retire irreversibly destroys the live state and writes a durable key-id tombstone; it is idempotent. Tombstones and creation records outlive receipt cleanup and prevent an old Stage retry from resurrecting a key. Operation IDs are scoped to one key. Their request digests and receipts remain available until retirement; after retirement an old operation retry fails instead of producing another signature. The public signing methods reject a context that is already done on entry and check it again immediately before calling Transact. The backend MUST check it once more before beginning its transaction. Cancellation that races dispatch or arrives after the transaction begins is an ambiguous outcome: the operation may have committed, and the caller retries the exact operation id and content to recover its stored receipt.

Stage copies its borrowed state before returning and retains no reference to its slice. Transact lends current to update for that synchronous call; update does not modify it. On success the backend takes ownership of next and receipt, atomically commits independent copies, clears superseded and aborted secret states, and returns an independent receipt. A failed update commits and exposes nothing. Generated but uncommitted receipts are secret because exposing two signatures from one leaf breaks XMSS. The signer authenticates the receipt's key, kind, content and leaf index. An ordinary statement must use a leaf before the reserved final leaf. On an ordinary retry the signer has no independently expected index. Successor authorization always uses the reserved final leaf, and the signer checks that index on every successor receipt. For either kind the backend must return the exact receipt committed for that key, operation id and request digest.

Forward security additionally requires every superseded state to become unreadable in journals, replicas, snapshots and backups, not merely absent from the active row. Deployments normally need cryptographic erasure plus an independently protected monotonic fence. Go's clear is only best effort.

Activate is permitted only for the originating StatementProvisioning after its Stage call returned and it erased both its Stage loan and local period- zero state. A backend must not independently activate a staged record during recovery: the original process may be suspended rather than dead. If that provisioning handle is lost before activation is reconciled, the backend destroys and tombstones the staged record and the application provisions a fresh key. Backend-specific recovery metadata may locate such records, but recovery never turns them into signing keys.

type StatementCreationID

type StatementCreationID [32]byte

StatementCreationID identifies one attempt to provision a statement key. It is public transaction metadata, not a cryptographic nonce.

func (StatementCreationID) MarshalText

func (id StatementCreationID) MarshalText() ([]byte, error)

MarshalText returns the statement creation id as String gives it.

func (StatementCreationID) String

func (id StatementCreationID) String() string

String returns the statement creation id as 64 lower-case hexadecimal characters, two for each byte in order.

func (*StatementCreationID) UnmarshalText

func (id *StatementCreationID) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote and refuses everything else as PublicIdentity.UnmarshalText does.

type StatementDigest

type StatementDigest [sha512.Size384]byte

StatementDigest is the SHA-384 request digest of a statement key id, its ordinary-or-successor kind and the statement bytes. It deliberately omits the leaf index, which is allocated inside the backend transaction. A StatementBackend uses it to distinguish an exact idempotent retry from reuse of an operation id for different content.

func (StatementDigest) MarshalText

func (d StatementDigest) MarshalText() ([]byte, error)

MarshalText returns the statement digest as String gives it.

func (StatementDigest) String

func (d StatementDigest) String() string

String returns the statement digest as 96 lower-case hexadecimal characters, two for each byte in order.

func (*StatementDigest) UnmarshalText

func (d *StatementDigest) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote and refuses everything else as PublicIdentity.UnmarshalText does.

type StatementKeyCertificate

type StatementKeyCertificate struct {
	Identity    PublicIdentity
	Context     string
	Scope       string
	Generation  uint64
	Predecessor StatementKeyID
	PublicKey   StatementPublicKey
	Signature   []byte
	// contains filtered or unexported fields
}

StatementKeyCertificate binds a statement public key and its rotation position to an ake identity. Signature is the identity's ML-DSA-87 AND Ed25519 signature over the canonical certificate body. A certificate does not by itself prove that its root was pinned before a later compromise; applications persist the verified initial id and verify successor certificates through statements signed by the predecessor.

func UnmarshalStatementKeyCertificate

func UnmarshalStatementKeyCertificate(data []byte) (*StatementKeyCertificate, error)

UnmarshalStatementKeyCertificate decodes one canonical statement key certificate and rejects trailing data. The returned value owns every byte.

func (*StatementKeyCertificate) Marshal

func (c *StatementKeyCertificate) Marshal() ([]byte, error)

Marshal encodes c in the canonical statement-certificate format.

type StatementKeyID

type StatementKeyID [sha512.Size384]byte

StatementKeyID identifies a certified statement public key. It is the SHA-384 digest of the canonical certificate body, excluding its randomized identity signature. Its text form is lower-case hexadecimal.

func (StatementKeyID) MarshalText

func (id StatementKeyID) MarshalText() ([]byte, error)

MarshalText returns the statement key id as String gives it.

func (StatementKeyID) String

func (id StatementKeyID) String() string

String returns the statement key id as 96 lower-case hexadecimal characters, two for each byte in order.

func (*StatementKeyID) UnmarshalText

func (id *StatementKeyID) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote and refuses everything else as PublicIdentity.UnmarshalText does.

type StatementKeyParams

type StatementKeyParams struct {

	// Context is the deployment context: 1 to MaxContextLen bytes of valid
	// UTF-8. It should be the same stable context used for ake handshakes.
	Context string
	// Scope is the application-defined authorization scope: 1 to
	// MaxStatementScopeLen bytes of valid UTF-8.
	Scope string
	// Generation is zero for an initial key and increases by exactly one for
	// each successor.
	Generation uint64
	// Predecessor is zero for generation zero and the predecessor's key id
	// for every later generation.
	Predecessor StatementKeyID
	// contains filtered or unexported fields
}

StatementKeyParams are the public authorization parameters certified by an ake Identity for a statement key.

type StatementKeyPin

type StatementKeyPin struct {
	ID          StatementKeyID
	Identity    PublicIdentity
	Context     string
	Scope       string
	Generation  uint64
	Predecessor StatementKeyID
	// contains filtered or unexported fields
}

StatementKeyPin is the durable public trust state for one verified statement-key generation. Persist it atomically when accepting an initial key or successor. Its exact key id prevents an identity compromise from substituting a sibling certificate after restart.

type StatementOperationID

type StatementOperationID [32]byte

StatementOperationID identifies one signing operation within one statement key at its authoritative backend. It is not a cryptographic nonce. Applications assign a fresh, durable, nonzero value before the first attempt and reuse that exact value only to retry the same statement. The same value may independently be used under another statement key.

func (StatementOperationID) MarshalText

func (id StatementOperationID) MarshalText() ([]byte, error)

MarshalText returns the statement operation id as String gives it.

func (StatementOperationID) String

func (id StatementOperationID) String() string

String returns the statement operation id as 64 lower-case hexadecimal characters, two for each byte in order.

func (*StatementOperationID) UnmarshalText

func (id *StatementOperationID) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote and refuses everything else as PublicIdentity.UnmarshalText does.

type StatementPrivateState

type StatementPrivateState []byte

StatementPrivateState is the opaque persisted private state of one statement key. A backend must treat its bytes as secret, never log them, and clear superseded copies after an atomic replacement. Its String, GoString, Format and LogValue methods disclose no byte. The caller owns every value it receives and must call Zero when it no longer needs it.

func (StatementPrivateState) Clone

Clone returns an independent copy of s. It returns nil for nil.

func (StatementPrivateState) Format

func (s StatementPrivateState) Format(f fmt.State, _ rune)

Format writes "StatementPrivateState(…)" for every verb fmt calls it with.

func (StatementPrivateState) GoString

func (s StatementPrivateState) GoString() string

GoString returns "StatementPrivateState(…)" and no state byte.

func (StatementPrivateState) LogValue

func (s StatementPrivateState) LogValue() slog.Value

LogValue returns a masked value for log/slog.

func (StatementPrivateState) String

func (s StatementPrivateState) String() string

String returns "StatementPrivateState(…)" and no state byte.

func (StatementPrivateState) Zero

func (s StatementPrivateState) Zero()

Zero clears s. It is safe on nil and on a value of any length.

type StatementProvisioning

type StatementProvisioning struct {
	// contains filtered or unexported fields
}

StatementProvisioning holds a newly generated private key until its state has been durably created in a StatementBackend. It is not safe for concurrent use. Publish may be retried after an ambiguous backend error with the same object. Zero clears a key only before Publish has begun; after that, Abort is the operation that also destroys any possibly persisted copy.

func PrepareStatementKey

func PrepareStatementKey(identity *Identity, params StatementKeyParams, backend StatementBackend) (*StatementProvisioning, error)

PrepareStatementKey generates independent ML-DSA-87, Ed25519 and XMSS-SHA2_10_256 statement keys, builds the complete XMSS public tree and certifies the public key with identity. It refuses while FIPS 140-only enforcement is active: the software XMSS signer is not an approved SP 800-208 signing service. It also refuses if ake did not capture the recognized Go 1.27 default cryptographic reader at package initialization. It does not call backend; Publish performs the persistence protocol, and a Publish that returns an error may have left a staged or active backend record.

func (*StatementProvisioning) Abort

Abort destroys an unpublished private state locally and asks the bound backend to discard any staged copy. It is idempotent at the backend. An error may be ambiguous; retain p and retry Abort. Abort of a published key is ErrStatementClosed; retire its signer instead.

func (*StatementProvisioning) Certificate

Certificate returns an independent copy of the certified public key.

func (*StatementProvisioning) Format

func (p *StatementProvisioning) Format(f fmt.State, _ rune)

Format writes "StatementProvisioning(…)" for every verb fmt calls it with and reads no field. The unpublished private state stays behind two pointers so that formatting a copied or nested handle also reaches no secret byte.

func (*StatementProvisioning) Publish

Publish stages the private state at the backend bound by PrepareStatementKey, clears the local state after Stage is acknowledged, then activates it and returns a signer. Either backend call may have committed before returning an error; retain p and call Publish again. The immutable creation id makes each retry idempotent. No Transact may start before activation, so an ambiguous Stage can never overlap a signer with the retained period-zero state. A second successful call is ErrStatementClosed.

func (*StatementProvisioning) Zero

func (p *StatementProvisioning) Zero()

Zero clears only a key for which no Stage call has begun. It is idempotent. Once Publish has begun it does nothing: use Abort so a possibly staged backend copy is also destroyed and tombstoned. Zero never changes backend state.

type StatementPublicKey

type StatementPublicKey [StatementPublicKeySize]byte

StatementPublicKey is the fixed hybrid statement public key. Its bytes are, in order, an ML-DSA-87 public key, an Ed25519 public key and the RFC 8391 public encoding of an XMSS-SHA2_10_256 key.

func (StatementPublicKey) MarshalText

func (k StatementPublicKey) MarshalText() ([]byte, error)

MarshalText returns the statement public key as String gives it.

func (StatementPublicKey) String

func (k StatementPublicKey) String() string

String returns the statement public key as lower-case hexadecimal, two characters for each byte in order.

func (*StatementPublicKey) UnmarshalText

func (k *StatementPublicKey) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote and refuses everything else as PublicIdentity.UnmarshalText does.

type StatementSigner

type StatementSigner struct {
	// contains filtered or unexported fields
}

StatementSigner signs through an authoritative StatementBackend. It keeps no private key locally between calls. It is safe for concurrent use; the backend serializes calls for its key. Close only closes this handle and does not retire or delete backend state.

func RestoreStatementSigner

func RestoreStatementSigner(key *VerifiedStatementKey, backend StatementBackend) (*StatementSigner, error)

RestoreStatementSigner binds a verified public key to a backend that already holds its private state. The first operation that requires a new signature validates that state against key; an exact retry may return a stored receipt without reading the current private state.

func (*StatementSigner) Close

func (s *StatementSigner) Close() error

Close closes this signer handle. It is idempotent and does not modify the backend's durable state. Once Retire has begun, Close returns ErrStatementBusy so an ambiguous retirement can still be retried through this handle.

func (*StatementSigner) Format

func (s *StatementSigner) Format(f fmt.State, _ rune)

Format writes "StatementSigner(…)" for every verb fmt calls it with and reads no field, so formatting never calls or races with its backend.

func (*StatementSigner) Key

Key returns the signer's verified public key, or nil after Close.

func (*StatementSigner) Retire

func (s *StatementSigner) Retire(ctx context.Context) error

Retire asks the backend to durably destroy this key's current private state and then closes the signer. Backend retirement is idempotent. An error may be ambiguous; the signer remains open only so Retire can be retried, and applications must not call SignStatement after beginning retirement. The backend must serialize Retire against Transact so that either a transaction commits first or retirement prevents it from starting.

func (*StatementSigner) SignStatement

func (s *StatementSigner) SignStatement(ctx context.Context, operationID StatementOperationID, statement []byte) ([]byte, error)

SignStatement signs statement with ML-DSA-87, Ed25519 and the next XMSS leaf. All three components cover the same canonical input. operationID must be nonzero and durable before the first call. An exact retry returns the backend's stored signature. State is advanced and durably committed before a new signature is returned. The content may be empty.

func (*StatementSigner) SignStatementSuccessor

func (s *StatementSigner) SignStatementSuccessor(ctx context.Context, operationID StatementOperationID, successor *StatementKeyCertificate) ([]byte, error)

SignStatementSuccessor authorizes successor with this key's reserved final XMSS leaf. It verifies that successor is the identity-certified next generation with this key as predecessor, burns every unused ordinary leaf inside the atomic transaction, and leaves this key exhausted. Before this call, publish and durably store the exact successor certificate together with the operation id and transition intent. Retain them until the exact retry has returned its authorization and the transition is delivered and durably pinned. Then retire this signer. Losing the certificate after this call commits can strand the lineage because no other successor can be authorized. An exact operation retry returns the same authorization.

type StatementStateUpdate

type StatementStateUpdate func(current StatementPrivateState) (next StatementPrivateState, receipt []byte, err error)

StatementStateUpdate is invoked synchronously by StatementBackend.Transact while that backend has exclusive, fenced authority over keyID. It receives the current private state and returns its successor plus the exact receipt to commit with it. The callback is single-use and becomes invalid when Transact returns.

type VerifiedBundle

type VerifiedBundle struct {
	// contains filtered or unexported fields
}

VerifiedBundle is an immutable snapshot of a bundle that passed signature, identity, party and freshness validation.

func (*VerifiedBundle) IdentityKey

func (b *VerifiedBundle) IdentityKey() PublicIdentity

IdentityKey returns the verified responder identity key.

func (*VerifiedBundle) PartyID

func (b *VerifiedBundle) PartyID() string

PartyID returns the verified responder party identifier.

func (*VerifiedBundle) SignedPreKeyID

func (b *VerifiedBundle) SignedPreKeyID() SignedPreKeyID

SignedPreKeyID returns the stable identifier of the verified signed-prekey epoch.

func (*VerifiedBundle) Timestamp

func (b *VerifiedBundle) Timestamp() time.Time

Timestamp returns the verified bundle timestamp, canonicalized to a whole UTC second. A nil VerifiedBundle returns the zero time.

type VerifiedOneTimePreKey

type VerifiedOneTimePreKey struct {
	// contains filtered or unexported fields
}

VerifiedOneTimePreKey is a signature-checked hybrid one-time prekey bound to a VerifiedBundle's signed-prekey epoch. Its verified public contents are immutable, but it is a single-use initiation capability: at most one Initiate call can successfully consume it, even through copied values.

func (*VerifiedOneTimePreKey) ID

ID returns the verified one-time-prekey identifier.

type VerifiedStatementKey

type VerifiedStatementKey struct {
	// contains filtered or unexported fields
}

VerifiedStatementKey is a validated, immutable copy of a statement key certificate. It contains public material only and is safe for concurrent use.

func VerifyPinnedStatementKey

func VerifyPinnedStatementKey(certificate *StatementKeyCertificate, pin StatementKeyPin) (*VerifiedStatementKey, error)

VerifyPinnedStatementKey recreates a verified key from a certificate and a caller-authenticated durable pin. It is the restart path for every generation. A pin is a trust decision, not peer input; applications protect it from rollback and replacement.

func VerifyStatementKey

func VerifyStatementKey(certificate *StatementKeyCertificate, expectedIdentity PublicIdentity, context, scope string) (*VerifiedStatementKey, error)

VerifyStatementKey verifies an initial generation-zero certificate against the caller's pinned identity, context and scope. It never accepts a successor certificate; use VerifyStatementSuccessor so the predecessor's reserved XMSS leaf authorizes the transition. It refuses while FIPS 140-only enforcement is active, for the same reason as PrepareStatementKey.

func VerifyStatementSuccessor

func VerifyStatementSuccessor(current *VerifiedStatementKey, successor *StatementKeyCertificate, authorization []byte) (*VerifiedStatementKey, error)

VerifyStatementSuccessor verifies successor as the next certified generation of current and verifies authorization as current's domain-separated final-leaf statement over the canonical successor body. On success the returned key is suitable for replacing the caller's durable pin. The caller performs that replacement atomically with recording the transition, and never accepts a sibling successor for the same generation.

func (*VerifiedStatementKey) Context

func (k *VerifiedStatementKey) Context() string

Context returns the key's certified deployment context.

func (*VerifiedStatementKey) Generation

func (k *VerifiedStatementKey) Generation() uint64

Generation returns the key's certified rotation generation.

func (*VerifiedStatementKey) ID

ID returns the key's certificate-body digest.

func (*VerifiedStatementKey) Identity

func (k *VerifiedStatementKey) Identity() PublicIdentity

Identity returns the ake identity that certified the key.

func (*VerifiedStatementKey) Pin

Pin returns the complete public trust state needed to restore this verified key without replaying its certificate chain. The caller protects it from rollback and replacement.

func (*VerifiedStatementKey) Predecessor

func (k *VerifiedStatementKey) Predecessor() StatementKeyID

Predecessor returns the certified predecessor id, or zero for an initial key.

func (*VerifiedStatementKey) PublicKey

PublicKey returns the complete hybrid statement public key.

func (*VerifiedStatementKey) Scope

func (k *VerifiedStatementKey) Scope() string

Scope returns the key's certified authorization scope.

type VerifyOptions

type VerifyOptions struct {

	// Context is the signing context the bundle must have been signed for.
	// It must be non-empty, at most MaxContextLen bytes and valid UTF-8.
	Context string
	// ExpectedPartyID is the responder party id the caller intends to reach.
	// It must be non-empty, at most MaxPartyIDLen bytes and valid UTF-8.
	ExpectedPartyID string
	// ExpectedIdentity is the already trusted responder identity key.
	ExpectedIdentity PublicIdentity
	// Now is the verification time. It must not be zero.
	Now time.Time
	// MaxAge is the largest accepted bundle age relative to Now. It must be
	// positive.
	MaxAge time.Duration
	// MaxFutureSkew is how far the bundle timestamp may lead Now. It must not
	// be negative; zero rejects any future timestamp. A bundle further ahead
	// is rejected with ErrInvalidMessage before its signature is checked; if
	// that persists across fresh fetches, suspect the local clock rather than
	// the peer.
	MaxFutureSkew time.Duration
	// MinTimestamp is the rollback floor, floored to a whole second toward
	// the earlier one, before 1970 as after it: a bundle timestamp before it
	// is rejected. The zero value disables the floor.
	MinTimestamp time.Time
	// contains filtered or unexported fields
}

VerifyOptions is the caller's trust and freshness policy. Verification requires an already trusted identity key and party id; a self-signed bundle is not an identity directory.

type X25519PrivateKey

type X25519PrivateKey [32]byte

X25519PrivateKey is an X25519 private scalar of 32 bytes, as a stored signed or one-time prekey holds it. Its text form is lower-case hexadecimal, 64 characters, which MarshalText writes for a store; String, log/slog and fmt with every verb but %p and %w show none of it, except where fmt calls no method: in a field that is not exported of a caller's struct, and inside a value fmt prints in its wrong-verb notation (see the package documentation). It is not a map key: encoding/json/v2 names the key of a map value it refuses in its error, as text, and so does encoding/json built with GOEXPERIMENT=jsonv2, as Go 1.27 builds it by default, for a value the Go type cannot hold, though not for one its UnmarshalText refuses (the package documentation has the cases). Give log/slog a pointer to the key, not the key: a value given to it is copied into an interface value on the heap, which nobody can clear. The value is the caller's to protect and clear, in every form it is kept in.

func (X25519PrivateKey) Format

func (k X25519PrivateKey) Format(f fmt.State, _ rune)

Format writes "X25519PrivateKey(…)" for every verb fmt calls it with, %x, %X, %q and %#v included, and no byte of the scalar: fmt prints a struct that holds the key, such as SignedPreKeyRestoreParams or prekey.PrivateEpoch, with that in place of the key. fmt calls it for no %p and no %w, and those print the key's bytes. The receiver is a value because fmt reaches a field of a struct as a value, whose methods are those of the value receiver alone. fmt calls no method of a value it reaches through a field that is not exported, nor in its wrong-verb notation, so such a struct held there by a caller prints the key's bytes (see the package documentation).

func (X25519PrivateKey) LogValue

func (k X25519PrivateKey) LogValue() slog.Value

LogValue returns "X25519PrivateKey(…)" as a string, which log/slog writes in place of the key: its handlers take a value's LogValue before its MarshalText, for the key by itself and by pointer. The receiver is a value for the reason Format's is.

func (X25519PrivateKey) MarshalText

func (k X25519PrivateKey) MarshalText() ([]byte, error)

MarshalText returns the private scalar as lower-case hexadecimal, 64 characters, two for each byte in order, in a slice the caller owns and should clear. The receiver is a value because encoding/json calls a method of the pointer receiver only for a value it can address: a struct marshalled by value, and every value of a map, would be written as an array of numbers, which no decoder of this module reads back. Calling it copies the scalar, as passing the key by value does.

func (X25519PrivateKey) String

func (k X25519PrivateKey) String() string

String returns "X25519PrivateKey(…)" and no byte of the scalar, so that a value written to a log by mistake shows none. MarshalText returns the text form.

func (*X25519PrivateKey) UnmarshalText

func (k *X25519PrivateKey) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, and refuses everything else, as PublicIdentity.UnmarshalText does, except that the error states only the length of the text it refuses and quotes none of it: a text close to the form, such as one in upper case, holds the scalar.

type X25519PublicKey

type X25519PublicKey [32]byte

X25519PublicKey is an X25519 public key of 32 bytes: a signed prekey, the X25519 half of a one-time prekey, or an initiator's ephemeral key. Its text form is lower-case hexadecimal, 64 characters.

func (X25519PublicKey) MarshalText

func (k X25519PublicKey) MarshalText() ([]byte, error)

MarshalText returns the key as String gives it.

func (X25519PublicKey) String

func (k X25519PublicKey) String() string

String returns the key as 64 lower-case hexadecimal characters, two for each byte in order.

func (*X25519PublicKey) UnmarshalText

func (k *X25519PublicKey) UnmarshalText(text []byte) error

UnmarshalText reads what MarshalText wrote, as PublicIdentity.UnmarshalText reads a key, and refuses everything else in the same way.

Directories

Path Synopsis
internal
hextext
Package hextext is the text form of the module's fixed-size byte values: their bytes in order as lower-case hexadecimal, two characters for each byte, and nothing else.
Package hextext is the text form of the module's fixed-size byte values: their bytes in order as lower-case hexadecimal, two characters for each byte, and nothing else.
hkdf32
Package hkdf32 implements the fixed-output HKDF-SHA384 forms used by ake.
Package hkdf32 implements the fixed-output HKDF-SHA384 forms used by ake.
labels
Package labels holds domain-separation labels shared by packages in this module.
Package labels holds domain-separation labels shared by packages in this module.
linkseam
Package linkseam is the seam between package ake and package record.
Package linkseam is the seam between package ake and package record.
reference
Package reference is an executable integration example for ake.
Package reference is an executable integration example for ake.
xmss
Package xmss implements the one fixed XMSS profile used by ake statements.
Package xmss implements the one fixed XMSS profile used by ake statements.
Package prekey coordinates checked publication and retirement of ake signed-prekey epochs.
Package prekey coordinates checked publication and retirement of ake signed-prekey epochs.
Package record provides a Channel, which gives an authenticated ake Session authenticated framing, a directional symmetric-key ratchet, sequence numbers, replay rejection, and bounded out-of-order delivery; on that Channel a Driver, which runs the rekeys of one channel; and a Link, which keeps one channel toward a peer and replaces it when it is lost.
Package record provides a Channel, which gives an authenticated ake Session authenticated framing, a directional symmetric-key ratchet, sequence numbers, replay rejection, and bounded out-of-order delivery; on that Channel a Driver, which runs the rekeys of one channel; and a Link, which keeps one channel toward a peer and replaces it when it is lost.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL