Initial vault: single-binary post-quantum file vault

Strip Fury back to its vault functionality in one `vault` command:
genkey, init, add (file or directory, optional folder inside the vault),
list, get, mv and rm.

The hybrid FrodoKEM-640 + ML-KEM-768 encryption core is kept under
internal/pqcrypt. Signing, policies, profiles, backups, SSH remotes,
FIDO2, agents, provenance and compression are removed.
This commit is contained in:
Andy Dixon
2026-09-26 14:05:10 +01:00
commit d95f2d04a4
26 changed files with 5689 additions and 0 deletions
+405
View File
@@ -0,0 +1,405 @@
// Copyright 2026 The fury Authors.
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Package fury implements post-quantum file encryption. It provides a
// post-quantum-only file format, hybrid KEM key agreement, and a 256-bit file key.
//
// For most use cases, generate a [PQIdentity] with [GeneratePQIdentity], obtain
// its public [PQRecipient] with [PQIdentity.Recipient], and use the [Encrypt]
// and [Decrypt] functions.
//
// fury encrypted files are binary and not malleable. For encoding them as text,
// use the github.com/andydixon/fury/armor package.
//
// # Cryptographic agility
//
// Key agreement is provided by registered suites (see the suite registry).
// Each suite embeds its identifier in the file, so files remain decryptable as
// newer, stronger suites are added and made the default. The default suite is a
// hybrid of FrodoKEM-640 and ML-KEM-768: the file key stays secret unless both
// KEMs are broken.
//
// # Key management
//
// fury does not have a global keyring; generate dedicated keys per task. Public
// recipients are shared as "fury1..." strings (or, being large, as files), or
// referenced by a short "furyfp1..." fingerprint. Private identities are always
// encrypted, with passphrase recovery and optional external unlock slots; there
// is no API to serialise an unencrypted private key.
package pqcrypt
import (
"crypto/hmac"
"crypto/rand"
"errors"
"fmt"
"io"
"runtime"
"slices"
"sort"
"github.com/andydixon/vault/internal/format"
"github.com/andydixon/vault/internal/stream"
)
// An Identity is passed to [Decrypt] to unwrap an opaque file key from a
// recipient stanza. It can be for example a secret key like [HybridIdentity], a
// plugin, or a custom implementation.
type Identity interface {
// Unwrap must return an error wrapping [ErrIncorrectIdentity] if none of
// the recipient stanzas match the identity, any other error will be
// considered fatal.
//
// Most fury API users won't need to interact with this method directly, and
// should instead pass [Identity] implementations to [Decrypt].
Unwrap(stanzas []*Stanza) (fileKey []byte, err error)
}
// ErrIncorrectIdentity is returned by [Identity.Unwrap] if none of the
// recipient stanzas match the identity.
var ErrIncorrectIdentity = errors.New("incorrect identity for recipient block")
// A Recipient is passed to [Encrypt] to wrap an opaque file key to one or more
// recipient stanza(s). It can be for example a public key like [HybridRecipient],
// a plugin, or a custom implementation.
type Recipient interface {
// Most fury API users won't need to interact with this method directly, and
// should instead pass [Recipient] implementations to [Encrypt].
Wrap(fileKey []byte) ([]*Stanza, error)
}
// RecipientWithLabels can be optionally implemented by a [Recipient], in which
// case [Encrypt] will use WrapWithLabels instead of [Recipient.Wrap].
//
// Encrypt will succeed only if the labels returned by all the recipients
// (assuming the empty set for those that don't implement RecipientWithLabels)
// are the same.
//
// This can be used to ensure a recipient is only used with other recipients
// with equivalent properties (for example by setting a "postquantum" label) or
// to ensure a recipient is always used alone (by returning a random label, for
// example to preserve its authentication properties).
type RecipientWithLabels interface {
WrapWithLabels(fileKey []byte) (s []*Stanza, labels []string, err error)
}
// A Stanza is a section of the fury header that encapsulates the file key as
// encrypted to a specific recipient.
//
// Most fury API users won't need to interact with this type directly, and should
// instead pass [Recipient] implementations to [Encrypt] and [Identity]
// implementations to [Decrypt].
type Stanza struct {
Type string
Args []string
Body []byte
}
// fileKeySize is 32 bytes (256-bit) so the symmetric layer's post-quantum
// (Grover) security floor of ~128 bits matches the KEMs, rather than the 64-bit
// floor a 128-bit file key would impose. See suite.go and the payload STREAM.
const fileKeySize = 32
const streamNonceSize = 16
// maxAutoWorkers bounds the automatic worker count for parallel STREAM
// chunk encryption/decryption. ChaCha20-Poly1305 is memory-bandwidth-bound
// past a modest number of cores, so an unbounded runtime.NumCPU() on very
// large machines would just add goroutine/channel overhead for no benefit.
const maxAutoWorkers = 32
// MaxWorkers is the largest value [Options.Workers] will accept.
//
// The limit is set by what a worker actually costs, not by taste. Each worker
// may have two chunks in flight (see the stream package's pipeline depth), and
// a chunk is 64 KiB of plaintext plus its ciphertext buffer, so the pipeline
// holds roughly 256 KiB per worker: about 256 MiB at this limit, plus 1024
// goroutines and channels sized to match. That is already far past the point
// where throughput stops improving, and comfortably above the thread count of
// the largest machines currently shipping. A request beyond it is a
// configuration error rather than a tuning choice, so Fury rejects it instead
// of quietly attempting it or silently substituting another number.
const MaxWorkers = 1024
// Options configures [EncryptWithOptions] and [DecryptWithOptions] beyond
// the defaults used by [Encrypt] and [Decrypt].
type Options struct {
// Workers controls how many goroutines seal or open STREAM chunks in
// parallel. STREAM chunk nonces are a pure counter independent of chunk
// content, so parallelising this work never changes the resulting
// ciphertext or plaintext, only how fast it's produced.
//
// Valid values are 0 to [MaxWorkers]. Zero (the default) means
// automatic: runtime.NumCPU(), capped at a value past which
// ChaCha20-Poly1305 stops getting faster. One forces the sequential
// code path. A negative value, or one above MaxWorkers, is rejected.
Workers int
}
// ErrInvalidWorkers is returned when [Options.Workers] is outside 0 to
// [MaxWorkers].
var ErrInvalidWorkers = errors.New("fury: worker count out of range")
// Validate reports whether the options are usable. Every entry point that
// accepts [Options] calls it, so an out-of-range worker count is refused by
// the library itself and not only by the command-line tool.
func (o Options) Validate() error {
if o.Workers < 0 {
return fmt.Errorf("%w: %d is negative", ErrInvalidWorkers, o.Workers)
}
if o.Workers > MaxWorkers {
return fmt.Errorf("%w: %d exceeds the maximum of %d", ErrInvalidWorkers, o.Workers, MaxWorkers)
}
return nil
}
func (o Options) workers() int {
if o.Workers > 0 {
return o.Workers
}
if n := runtime.NumCPU(); n < maxAutoWorkers {
return n
}
return maxAutoWorkers
}
// encryptHdr wraps a file key to every recipient and authenticates the result.
//
// INVARIANT (no silent downgrade). All recipients must return identical label
// sets. A recipient that does not implement [RecipientWithLabels] contributes
// the empty set, so it can never be mixed with a "postquantum" recipient. Any
// future recipient type with weaker properties fails closed rather than
// quietly lowering the security of the whole file.
func encryptHdr(fileKey []byte, recipients ...Recipient) (*format.Header, error) {
if len(recipients) == 0 {
return nil, errors.New("no recipients specified")
}
hdr := &format.Header{}
var labels []string
for i, r := range recipients {
stanzas, l, err := wrapWithLabels(r, fileKey)
if err != nil {
return nil, fmt.Errorf("failed to wrap key for recipient #%d: %w", i, err)
}
sort.Strings(l)
if i == 0 {
labels = l
} else if !slices.Equal(labels, l) {
return nil, incompatibleLabelsError(labels, l)
}
for _, s := range stanzas {
hdr.Recipients = append(hdr.Recipients, (*format.Stanza)(s))
}
}
if mac, err := headerMAC(fileKey, hdr); err != nil {
return nil, fmt.Errorf("failed to compute header MAC: %v", err)
} else {
hdr.MAC = mac
}
return hdr, nil
}
// Encrypt encrypts a file to one or more recipients. Every recipient will be
// able to decrypt the file.
//
// Writes to the returned WriteCloser are encrypted and written to dst as a fury
// file. The caller must call Close on the WriteCloser when done for the last
// chunk to be encrypted and flushed to dst.
//
// The payload is sealed using multiple goroutines automatically; see
// [EncryptWithOptions] to control that.
func Encrypt(dst io.Writer, recipients ...Recipient) (io.WriteCloser, error) {
return EncryptWithOptions(dst, Options{}, recipients...)
}
// EncryptWithOptions is like [Encrypt], with explicit [Options].
//
// INVARIANT (fresh file key). Every call generates a new 32-byte file key
// from crypto/rand. Nothing derives a file key from the plaintext, the
// recipients or a counter, so no two encryptions share one.
func EncryptWithOptions(dst io.Writer, opts Options, recipients ...Recipient) (io.WriteCloser, error) {
if err := opts.Validate(); err != nil {
return nil, err
}
fileKey := make([]byte, fileKeySize)
if _, err := rand.Read(fileKey); err != nil {
return nil, fmt.Errorf("failed to generate file key: %w", err)
}
defer wipe(fileKey)
hdr, err := encryptHdr(fileKey, recipients...)
if err != nil {
return nil, err
}
if err := hdr.Marshal(dst); err != nil {
return nil, fmt.Errorf("failed to write header: %w", err)
}
nonce := make([]byte, streamNonceSize)
if _, err := rand.Read(nonce); err != nil {
return nil, fmt.Errorf("failed to generate nonce: %w", err)
}
if _, err := dst.Write(nonce); err != nil {
return nil, fmt.Errorf("failed to write nonce: %w", err)
}
key := streamKey(fileKey, nonce)
w, err := stream.NewParallelEncryptWriter(key, dst, opts.workers())
wipe(key)
return w, err
}
func wrapWithLabels(r Recipient, fileKey []byte) (s []*Stanza, labels []string, err error) {
if r, ok := r.(RecipientWithLabels); ok {
return r.WrapWithLabels(fileKey)
}
s, err = r.Wrap(fileKey)
return
}
func incompatibleLabelsError(l1, l2 []string) error {
hasPQ1 := slices.Contains(l1, "postquantum")
hasPQ2 := slices.Contains(l2, "postquantum")
if hasPQ1 != hasPQ2 {
return fmt.Errorf("incompatible recipients: can't mix post-quantum and classic recipients, or the file would be vulnerable to quantum computers")
}
return fmt.Errorf("incompatible recipients: %q and %q can't be mixed", l1, l2)
}
// NoIdentityMatchError is returned by [Decrypt] when none of the supplied
// identities match the encrypted file.
type NoIdentityMatchError struct {
// Errors is a slice of all the errors returned to Decrypt by the Unwrap
// calls it made. They all wrap [ErrIncorrectIdentity].
Errors []error
// StanzaTypes are the first argument of each recipient stanza in the
// encrypted file's header.
StanzaTypes []string
}
func (e *NoIdentityMatchError) Error() string {
if len(e.Errors) == 1 {
return "identity did not match any of the recipients: " + e.Errors[0].Error()
}
return "no identity matched any of the recipients"
}
// Decrypt decrypts a file encrypted to one or more identities.
// All identities will be tried until one successfully decrypts the file.
// Native, non-interactive identities are tried before any other identities.
//
// Decrypt returns a Reader reading the decrypted plaintext of the fury file read
// from src. If no identity matches the encrypted file, the returned error will
// be of type [NoIdentityMatchError].
//
// The payload is opened using multiple goroutines automatically; see
// [DecryptWithOptions] to control that.
func Decrypt(src io.Reader, identities ...Identity) (io.Reader, error) {
return DecryptWithOptions(src, Options{}, identities...)
}
// DecryptWithOptions is like [Decrypt], with explicit [Options].
func DecryptWithOptions(src io.Reader, opts Options, identities ...Identity) (io.Reader, error) {
if err := opts.Validate(); err != nil {
return nil, err
}
hdr, payload, err := format.Parse(src)
if err != nil {
return nil, fmt.Errorf("failed to read header: %w", err)
}
fileKey, err := decryptHdr(hdr, identities...)
if err != nil {
return nil, err
}
defer wipe(fileKey)
nonce := make([]byte, streamNonceSize)
if _, err := io.ReadFull(payload, nonce); err != nil {
return nil, fmt.Errorf("failed to read nonce: %w", err)
}
key := streamKey(fileKey, nonce)
r, err := stream.NewParallelDecryptReader(key, payload, opts.workers())
wipe(key)
return r, err
}
func decryptHdr(hdr *format.Header, identities ...Identity) ([]byte, error) {
if len(identities) == 0 {
return nil, errors.New("no identities specified")
}
slices.SortStableFunc(identities, func(a, b Identity) int {
var aIsNative, bIsNative bool
switch a.(type) {
case *PQIdentity:
aIsNative = true
}
switch b.(type) {
case *PQIdentity:
bIsNative = true
}
if aIsNative && !bIsNative {
return -1
}
if !aIsNative && bIsNative {
return 1
}
return 0
})
stanzas := make([]*Stanza, 0, len(hdr.Recipients))
errNoMatch := &NoIdentityMatchError{}
for _, s := range hdr.Recipients {
errNoMatch.StanzaTypes = append(errNoMatch.StanzaTypes, s.Type)
stanzas = append(stanzas, (*Stanza)(s))
}
var fileKey []byte
// The unwrapped key is copied out below; clear this copy on every exit
// path so it does not outlive the call. A closure is required: fileKey is
// assigned inside the loop, and a bare defer would capture today's nil.
defer func() { wipe(fileKey) }()
for _, id := range identities {
var err error
fileKey, err = id.Unwrap(stanzas)
if errors.Is(err, ErrIncorrectIdentity) {
errNoMatch.Errors = append(errNoMatch.Errors, err)
continue
}
if err != nil {
return nil, err
}
break
}
if fileKey == nil {
return nil, errNoMatch
}
if mac, err := headerMAC(fileKey, hdr); err != nil {
return nil, fmt.Errorf("failed to compute header MAC: %v", err)
} else if !hmac.Equal(mac, hdr.MAC) {
return nil, errors.New("bad header MAC")
}
return append([]byte(nil), fileKey...), nil
}
// multiUnwrap is a helper that implements Identity.Unwrap in terms of a
// function that unwraps a single recipient stanza.
func multiUnwrap(unwrap func(*Stanza) ([]byte, error), stanzas []*Stanza) ([]byte, error) {
for _, s := range stanzas {
fileKey, err := unwrap(s)
if errors.Is(err, ErrIncorrectIdentity) {
// If we ever start returning something interesting wrapping
// ErrIncorrectIdentity, we should let it make its way up through
// Decrypt into NoIdentityMatchError.Errors.
continue
}
if err != nil {
return nil, err
}
return fileKey, nil
}
return nil, ErrIncorrectIdentity
}
+70
View File
@@ -0,0 +1,70 @@
// Copyright 2026 The fury Authors.
// SPDX-License-Identifier: GPL-3.0-or-later
package pqcrypt
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"testing"
)
// TestEncryptWithOptionsRoundTrip exercises the parallel STREAM path end to
// end, at a size spanning many chunks, across a few explicit worker counts
// (including 1, which forces the original sequential code path).
func TestEncryptWithOptionsRoundTrip(t *testing.T) {
id, err := GeneratePQIdentity()
if err != nil {
t.Fatal(err)
}
r := id.Recipient()
plaintext := make([]byte, 4<<20) // 4 MiB: many STREAM chunks
if _, err := rand.Read(plaintext); err != nil {
t.Fatal(err)
}
for _, workers := range []int{1, 2, 8} {
t.Run(fmt.Sprintf("workers=%d", workers), func(t *testing.T) {
buf := &bytes.Buffer{}
w, err := EncryptWithOptions(buf, Options{Workers: workers}, r)
if err != nil {
t.Fatal(err)
}
if _, err := w.Write(plaintext); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
out, err := DecryptWithOptions(bytes.NewReader(buf.Bytes()), Options{Workers: workers}, id)
if err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(out)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, plaintext) {
t.Fatal("round-trip mismatch")
}
})
}
}
func TestOptionsWorkers(t *testing.T) {
if got := (Options{}).workers(); got <= 0 {
t.Fatalf("default workers = %d, want > 0", got)
}
if got := (Options{Workers: 3}).workers(); got != 3 {
t.Fatalf("explicit workers = %d, want 3", got)
}
// An explicit request is honoured even above the automatic cap; only the
// zero-value automatic path is capped.
if got := (Options{Workers: 1000}).workers(); got != 1000 {
t.Fatalf("explicit workers = %d, want 1000", got)
}
}
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package pqcrypt
import (
"crypto/hmac"
"crypto/sha256"
"errors"
"io"
"github.com/andydixon/vault/internal/format"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/hkdf"
)
func wipe(b []byte) {
for i := range b {
b[i] = 0
}
}
// aeadEncrypt encrypts a message with a one-time key.
//
// INVARIANT (fixed nonce). The all-zero nonce below is safe only because
// every key reaching this function is a fresh, unique, single-use derived
// KEK. It is not a shortcut and must not be reused anywhere that condition
// does not hold: repeating a (key, nonce) pair under ChaCha20-Poly1305
// destroys both confidentiality and authenticity.
//
// The condition holds today because aeadEncrypt has exactly one caller, the
// default suite's wrap, whose KEK is
// HKDF-SHA-256(ss1 || ss2, info = label || ct1 || ct2). Both KEM
// encapsulations are performed freshly for each wrap, so ss1, ss2, ct1 and
// ct2 differ for every call even when the same file key is wrapped to the
// same recipient twice. Any new caller must establish the same property, or
// carry its own nonce.
//
// For the code that encrypts the actual payload, which uses a counter nonce
// rather than a fixed one, see the
// github.com/andydixon/vault/internal/stream package.
func aeadEncrypt(key, plaintext []byte) ([]byte, error) {
aead, err := chacha20poly1305.New(key)
if err != nil {
return nil, err
}
nonce := make([]byte, chacha20poly1305.NonceSize)
return aead.Seal(nil, nonce, plaintext, nil), nil
}
var errIncorrectCiphertextSize = errors.New("encrypted value has unexpected length")
// aeadDecrypt decrypts a message of an expected fixed size.
//
// The message size is limited to mitigate multi-key attacks, where a ciphertext
// can be crafted that decrypts successfully under multiple keys. Short
// ciphertexts can only target two keys, which has limited impact.
func aeadDecrypt(key []byte, size int, ciphertext []byte) ([]byte, error) {
aead, err := chacha20poly1305.New(key)
if err != nil {
return nil, err
}
if len(ciphertext) != size+aead.Overhead() {
return nil, errIncorrectCiphertextSize
}
nonce := make([]byte, chacha20poly1305.NonceSize)
return aead.Open(nil, nonce, ciphertext, nil)
}
// headerMAC computes the header authentication tag.
//
// INVARIANT (header authentication). The MAC covers the complete header
// except the MAC line itself: the intro line, every recipient stanza in
// order, and the footer prefix. Nothing that a decryptor acts upon is left
// unauthenticated, so a stanza cannot be added, removed, reordered or edited
// without detection by anyone who can recover the file key.
//
// INVARIANT (domain separation). The MAC key and the payload key are both
// HKDF-SHA-256 expansions of the same file key under distinct info strings
// ("header" and "payload"), so neither can be substituted for the other.
func headerMAC(fileKey []byte, hdr *format.Header) ([]byte, error) {
h := hkdf.New(sha256.New, fileKey, nil, []byte("header"))
hmacKey := make([]byte, 32)
if _, err := io.ReadFull(h, hmacKey); err != nil {
wipe(hmacKey)
return nil, err
}
// The MAC key is derived per call and is of no use once the hash is
// keyed, so it does not need to outlive this function.
defer wipe(hmacKey)
hh := hmac.New(sha256.New, hmacKey)
if err := hdr.MarshalWithoutMAC(hh); err != nil {
return nil, err
}
return hh.Sum(nil), nil
}
// streamKey derives the payload key.
//
// INVARIANT (payload key uniqueness). The 16-byte file nonce is fresh
// randomness written into every file and used here as the HKDF salt, so two
// encryptions never share a payload key even if a file key were somehow
// repeated. Combined with the STREAM counter nonce, no (key, nonce) pair is
// ever reused.
func streamKey(fileKey, nonce []byte) []byte {
h := hkdf.New(sha256.New, fileKey, nonce, []byte("payload"))
streamKey := make([]byte, chacha20poly1305.KeySize)
if _, err := io.ReadFull(h, streamKey); err != nil {
panic("fury: internal error: failed to read from HKDF: " + err.Error())
}
return streamKey
}
+236
View File
@@ -0,0 +1,236 @@
// Copyright 2026 The fury Authors.
// SPDX-License-Identifier: GPL-3.0-or-later
package pqcrypt
import (
"crypto/rand"
"errors"
"fmt"
)
// A pqSuite is a registered post-quantum KEM suite. Each suite wraps the file
// key to a recipient and unwraps it with the corresponding identity. Suites are
// self-describing: their stanza tag is written into the header, so a file made
// with one suite keeps decrypting even after newer suites are added and made the
// default. This is the "use the best now, add better later, still decrypt older"
// property.
//
// Recipient public keys and identity private keys are opaque byte slices whose
// layout is defined by the suite. Identities are derived deterministically from
// a compact master seed so they can be stored and passphrase-wrapped cheaply.
type pqSuite interface {
// id is a stable numeric identifier embedded in recipient encodings.
id() uint16
// tag is the header stanza Type for this suite.
tag() string
// rank orders suites when picking a default; higher wins.
rank() int
// seedSize is the length of the master seed accepted by deriveKeypair.
seedSize() int
// deriveKeypair deterministically expands a master seed into a suite public
// key and private key.
deriveKeypair(seed []byte) (pub, priv []byte, err error)
// wrap encapsulates fileKey to pub, returning one or more header stanzas.
wrap(pub, fileKey []byte) ([]*Stanza, error)
// unwrap recovers fileKey from a stanza using priv. It must return an error
// wrapping ErrIncorrectIdentity if the stanza does not match.
unwrap(priv []byte, s *Stanza) ([]byte, error)
// publicKeySize is the expected length of a suite public key.
publicKeySize() int
}
var (
pqSuitesByTag = map[string]pqSuite{}
pqSuitesByID = map[uint16]pqSuite{}
)
// registerSuite adds a suite to the registry. It is called from suite files'
// init functions.
func registerSuite(s pqSuite) {
if _, ok := pqSuitesByTag[s.tag()]; ok {
panic("fury: duplicate suite tag " + s.tag())
}
if _, ok := pqSuitesByID[s.id()]; ok {
panic(fmt.Sprintf("fury: duplicate suite id %#04x", s.id()))
}
pqSuitesByTag[s.tag()] = s
pqSuitesByID[s.id()] = s
}
// defaultSuite returns the highest-ranked registered suite, used for key
// generation and encryption.
func defaultSuite() pqSuite {
var best pqSuite
for _, s := range pqSuitesByTag {
if best == nil || s.rank() > best.rank() {
best = s
}
}
if best == nil {
panic("fury: no PQ suites registered")
}
return best
}
// PQRecipient is a post-quantum public key. Messages encrypted to it can be
// decrypted with the corresponding [PQIdentity].
//
// It is anonymous: an observer can't tell from a message alone whether it is
// encrypted to a given recipient.
type PQRecipient struct {
suite pqSuite
pub []byte
}
var _ Recipient = &PQRecipient{}
var _ RecipientWithLabels = &PQRecipient{}
func (r *PQRecipient) Wrap(fileKey []byte) ([]*Stanza, error) {
return r.suite.wrap(r.pub, fileKey)
}
// WrapWithLabels returns a "postquantum" label so a PQRecipient can only be
// combined with other post-quantum recipients, never with a recipient type that
// would defeat its security.
func (r *PQRecipient) WrapWithLabels(fileKey []byte) ([]*Stanza, []string, error) {
s, err := r.Wrap(fileKey)
if err != nil {
return nil, nil, err
}
return s, []string{"postquantum"}, nil
}
// SuiteID returns the numeric identifier of the recipient's suite.
func (r *PQRecipient) SuiteID() uint16 { return r.suite.id() }
// Bytes returns the raw suite public key.
func (r *PQRecipient) Bytes() []byte { return append([]byte(nil), r.pub...) }
// PQIdentity is a post-quantum private key, derived from a compact master seed,
// which can decrypt messages encrypted to the corresponding [PQRecipient].
type PQIdentity struct {
suite pqSuite
seed []byte
pub []byte
priv []byte
}
var _ Identity = &PQIdentity{}
// GeneratePQIdentity randomly generates a new identity using the default suite.
func GeneratePQIdentity() (*PQIdentity, error) {
s := defaultSuite()
seed := make([]byte, s.seedSize())
if _, err := rand.Read(seed); err != nil {
return nil, fmt.Errorf("failed to generate seed: %w", err)
}
id, err := newPQIdentityFromSeed(s, seed)
wipe(seed)
return id, err
}
// newPQIdentityFromSeed derives an identity from a suite and master seed.
func newPQIdentityFromSeed(s pqSuite, seed []byte) (*PQIdentity, error) {
if len(seed) != s.seedSize() {
return nil, fmt.Errorf("invalid seed size %d for suite %s", len(seed), s.tag())
}
seed = append([]byte(nil), seed...)
pub, priv, err := s.deriveKeypair(seed)
if err != nil {
return nil, fmt.Errorf("failed to derive keypair: %w", err)
}
return &PQIdentity{suite: s, seed: seed, pub: pub, priv: priv}, nil
}
// usable reports whether the identity still holds its secret material. A
// closed identity, and one that was never fully initialised, both report
// false rather than panicking on a nil slice.
func (i *PQIdentity) usable() bool {
return i != nil && i.suite != nil && len(i.seed) == i.suite.seedSize() && len(i.priv) != 0
}
// ErrIdentityClosed is returned by operations on an identity whose secret
// material has been cleared by Close.
var ErrIdentityClosed = errors.New("fury identity is closed or uninitialised")
// Close overwrites the secret material this identity owns: its master seed
// and its expanded private key. Repeated calls are safe, and a partially
// initialised identity closes without panicking. The public key is retained,
// so [PQIdentity.Recipient] keeps working on a closed identity.
//
// Explicit overwriting shortens the lifetime of buffers Fury knows about. It
// cannot guarantee removal from physical memory: the Go compiler and runtime
// may have copied a value during allocation, garbage collection, stack growth
// or escape analysis, and Fury has no way to find or clear those copies. Treat
// this as defence in depth, not as erasure.
func (i *PQIdentity) Close() {
if i == nil {
return
}
wipe(i.seed)
wipe(i.priv)
i.seed, i.priv = nil, nil
}
func (i *PQIdentity) Unwrap(stanzas []*Stanza) ([]byte, error) {
if !i.usable() {
return nil, ErrIdentityClosed
}
return multiUnwrap(i.unwrap, stanzas)
}
func (i *PQIdentity) unwrap(s *Stanza) ([]byte, error) {
su, ok := pqSuitesByTag[s.Type]
if !ok || su.tag() != i.suite.tag() {
return nil, ErrIncorrectIdentity
}
fileKey, err := su.unwrap(i.priv, s)
if err != nil {
return nil, err
}
// Enforce the file key length centrally, so no future suite can feed a
// wrong-sized key into the payload STREAM by forgetting its own check.
if len(fileKey) != fileKeySize {
return nil, fmt.Errorf("suite %s returned a file key of %d bytes, want %d", su.tag(), len(fileKey), fileKeySize)
}
return fileKey, nil
}
// Recipient returns the public [PQRecipient] corresponding to i. It remains
// valid after [PQIdentity.Close], because a public key is not secret.
func (i *PQIdentity) Recipient() *PQRecipient {
return &PQRecipient{suite: i.suite, pub: append([]byte(nil), i.pub...)}
}
// Seed returns a copy of the compact master seed, or nil if the identity is
// closed.
//
// The returned slice is secret-equivalent: it regenerates both the private and
// the public key, so anything that can read it can decrypt everything the
// identity can. It must never be shared as a recipient, written unencrypted,
// logged, or passed to a subprocess.
//
// The copy is deliberate: it is never an alias into the identity's own buffer,
// so closing the identity does not clear it. From the moment it is returned it
// is the caller's responsibility to wipe it when finished and to keep its
// lifetime short.
func (i *PQIdentity) Seed() []byte {
if !i.usable() {
return nil
}
return append([]byte(nil), i.seed...)
}
// SuiteID returns the numeric identifier of the identity's suite.
func (i *PQIdentity) SuiteID() uint16 { return i.suite.id() }
// NewPQIdentityFromSeed derives an identity of the given suite from its master
// seed, as returned by [PQIdentity.Seed].
func NewPQIdentityFromSeed(suiteID uint16, seed []byte) (*PQIdentity, error) {
s, ok := pqSuitesByID[suiteID]
if !ok {
return nil, fmt.Errorf("unknown suite id %#04x", suiteID)
}
return newPQIdentityFromSeed(s, seed)
}
+215
View File
@@ -0,0 +1,215 @@
// Copyright 2026 The fury Authors.
// SPDX-License-Identifier: GPL-3.0-or-later
package pqcrypt
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"slices"
"github.com/andydixon/vault/internal/format"
"github.com/cloudflare/circl/kem"
"github.com/cloudflare/circl/kem/frodo/frodo640shake"
"github.com/cloudflare/circl/kem/mlkem/mlkem768"
"golang.org/x/crypto/hkdf"
)
// frodoMLKEM768 is the default post-quantum suite: a hybrid of FrodoKEM-640
// (unstructured-lattice) and ML-KEM-768 (module-lattice). The file key stays
// secret unless both KEMs are broken. It is pure Go, so fury keeps building as a
// static binary with no cgo. (A code-based suite such as HQC or Classic McEliece
// via liboqs can be registered later with a higher rank; see suite.go.)
type frodoMLKEM768 struct{}
func init() { registerSuite(frodoMLKEM768{}) }
func (frodoMLKEM768) id() uint16 { return 0x0001 }
func (frodoMLKEM768) tag() string { return "frodo640shake+mlkem768" }
func (frodoMLKEM768) rank() int { return 10 }
func (frodoMLKEM768) seedSize() int { return 32 }
func (frodoMLKEM768) schemes() (frodo, ml kem.Scheme) {
return frodo640shake.Scheme(), mlkem768.Scheme()
}
func (s frodoMLKEM768) publicKeySize() int {
frodo, ml := s.schemes()
return frodo.PublicKeySize() + ml.PublicKeySize()
}
// deriveKeypair expands a 32-byte master seed into per-KEM seeds via HKDF, then
// derives each keypair deterministically. The public key is frodoPub||mlkemPub
// and the private key is frodoPriv||mlkemPriv.
func (s frodoMLKEM768) deriveKeypair(seed []byte) (pub, priv []byte, err error) {
frodo, ml := s.schemes()
r := hkdf.New(sha256.New, seed, nil, []byte("fury/v1 seed-expand "+s.tag()))
frodoSeed := make([]byte, frodo.SeedSize())
mlSeed := make([]byte, ml.SeedSize())
// The per-KEM seeds regenerate the private keys, so they are as sensitive
// as the master seed and are cleared as soon as the keys are derived.
defer wipe(frodoSeed)
defer wipe(mlSeed)
if _, err := io.ReadFull(r, frodoSeed); err != nil {
return nil, nil, err
}
if _, err := io.ReadFull(r, mlSeed); err != nil {
return nil, nil, err
}
fpk, fsk := frodo.DeriveKeyPair(frodoSeed)
mpk, msk := ml.DeriveKeyPair(mlSeed)
fpkb, err := fpk.MarshalBinary()
if err != nil {
return nil, nil, err
}
mpkb, err := mpk.MarshalBinary()
if err != nil {
return nil, nil, err
}
fskb, err := fsk.MarshalBinary()
if err != nil {
return nil, nil, err
}
defer wipe(fskb)
mskb, err := msk.MarshalBinary()
if err != nil {
return nil, nil, err
}
defer wipe(mskb)
// fpkb and mpkb are public key bytes; wiping them would be theatre.
return slices.Concat(fpkb, mpkb), slices.Concat(fskb, mskb), nil
}
// wrap encapsulates to both KEMs and seals the file key under the combined
// KEK.
//
// INVARIANT (fresh encapsulation). Both Encapsulate calls draw fresh
// randomness on every invocation. Wrapping the same file key to the same
// recipient twice therefore produces two independent KEKs, never a repeat.
func (s frodoMLKEM768) wrap(pub, fileKey []byte) ([]*Stanza, error) {
frodo, ml := s.schemes()
if len(pub) != s.publicKeySize() {
return nil, fmt.Errorf("invalid %s public key size", s.tag())
}
fpk, err := frodo.UnmarshalBinaryPublicKey(pub[:frodo.PublicKeySize()])
if err != nil {
return nil, fmt.Errorf("invalid FrodoKEM public key: %v", err)
}
mpk, err := ml.UnmarshalBinaryPublicKey(pub[frodo.PublicKeySize():])
if err != nil {
return nil, fmt.Errorf("invalid ML-KEM public key: %v", err)
}
ct1, ss1, err := frodo.Encapsulate(fpk)
if err != nil {
return nil, fmt.Errorf("FrodoKEM encapsulation failed: %v", err)
}
ct2, ss2, err := ml.Encapsulate(mpk)
if err != nil {
return nil, fmt.Errorf("ML-KEM encapsulation failed: %v", err)
}
kek := s.deriveKEK(ss1, ss2, ct1, ct2)
defer wipe(ss1)
defer wipe(ss2)
defer wipe(kek)
body, err := aeadEncrypt(kek, fileKey)
if err != nil {
return nil, fmt.Errorf("failed to wrap file key: %v", err)
}
return []*Stanza{{
Type: s.tag(),
Args: []string{format.EncodeToString(ct1), format.EncodeToString(ct2)},
Body: body,
}}, nil
}
func (s frodoMLKEM768) unwrap(priv []byte, st *Stanza) ([]byte, error) {
frodo, ml := s.schemes()
if st.Type != s.tag() {
return nil, ErrIncorrectIdentity
}
if len(st.Args) != 2 {
return nil, fmt.Errorf("invalid %s stanza: expected 2 arguments", s.tag())
}
ct1, err := format.DecodeString(st.Args[0])
if err != nil {
return nil, fmt.Errorf("invalid FrodoKEM ciphertext: %v", err)
}
ct2, err := format.DecodeString(st.Args[1])
if err != nil {
return nil, fmt.Errorf("invalid ML-KEM ciphertext: %v", err)
}
if len(ct1) != frodo.CiphertextSize() || len(ct2) != ml.CiphertextSize() {
return nil, errIncorrectCiphertextSize
}
if len(priv) != frodo.PrivateKeySize()+ml.PrivateKeySize() {
return nil, errors.New("invalid private key size")
}
fsk, err := frodo.UnmarshalBinaryPrivateKey(priv[:frodo.PrivateKeySize()])
if err != nil {
return nil, fmt.Errorf("invalid FrodoKEM private key: %v", err)
}
// priv itself belongs to the caller's identity and is cleared by
// PQIdentity.Close; the parsed key objects are owned by CIRCL and expose
// no buffer Fury can clear.
msk, err := ml.UnmarshalBinaryPrivateKey(priv[frodo.PrivateKeySize():])
if err != nil {
return nil, fmt.Errorf("invalid ML-KEM private key: %v", err)
}
ss1, err := frodo.Decapsulate(fsk, ct1)
if err != nil {
return nil, fmt.Errorf("FrodoKEM decapsulation failed: %v", err)
}
ss2, err := ml.Decapsulate(msk, ct2)
if err != nil {
return nil, fmt.Errorf("ML-KEM decapsulation failed: %v", err)
}
// Both KEMs use implicit rejection, so a mismatched key yields a wrong
// shared secret rather than an error; detection happens here at aeadDecrypt.
kek := s.deriveKEK(ss1, ss2, ct1, ct2)
defer wipe(ss1)
defer wipe(ss2)
defer wipe(kek)
fileKey, err := aeadDecrypt(kek, fileKeySize, st.Body)
if err != nil {
return nil, ErrIncorrectIdentity
}
return fileKey, nil
}
// deriveKEK combines the two KEM shared secrets and both ciphertexts into a
// 256-bit key-encryption key.
//
// INVARIANT (both secrets contribute). ss1 and ss2 are concatenated as the
// HKDF input keying material, so the KEK stays unpredictable unless both KEMs
// are broken for the same target. Dropping either would silently reduce the
// construction to a single KEM.
//
// INVARIANT (transcript binding). Both ciphertexts are bound into the HKDF
// info string, preventing a mix-and-match of encapsulations across the two
// KEMs: an attacker cannot pair ct1 from one stanza with ct2 from another and
// obtain a KEK either party would compute.
//
// INVARIANT (single use). Because both encapsulations are performed freshly
// for every wrap, the resulting KEK is unique to that wrap. That is what
// makes the fixed AEAD nonce in aeadEncrypt safe; see primitives.go.
func (s frodoMLKEM768) deriveKEK(ss1, ss2, ct1, ct2 []byte) []byte {
secret := slices.Concat(ss1, ss2)
defer wipe(secret)
info := slices.Concat([]byte("fury/v1 kek "+s.tag()), ct1, ct2)
r := hkdf.New(sha256.New, secret, nil, info)
kek := make([]byte, 32)
if _, err := io.ReadFull(r, kek); err != nil {
panic("fury: internal error: failed to read from HKDF: " + err.Error())
}
return kek
}
+135
View File
@@ -0,0 +1,135 @@
// Copyright 2026 The fury Authors.
// SPDX-License-Identifier: GPL-3.0-or-later
package pqcrypt
import (
"bytes"
"io"
"testing"
)
// TestPQRoundTrip exercises the full Encrypt -> Decrypt path through the default
// post-quantum suite with a 256-bit file key.
func TestPQRoundTrip(t *testing.T) {
id, err := GeneratePQIdentity()
if err != nil {
t.Fatal(err)
}
r := id.Recipient()
plaintext := []byte("fury: post-quantum only, hard g like GIF")
buf := &bytes.Buffer{}
w, err := Encrypt(buf, r)
if err != nil {
t.Fatal(err)
}
if _, err := w.Write(plaintext); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
out, err := Decrypt(bytes.NewReader(buf.Bytes()), id)
if err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(out)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, plaintext) {
t.Fatalf("round-trip mismatch: got %q want %q", got, plaintext)
}
}
func TestPQFileKeyIs256Bit(t *testing.T) {
if fileKeySize != 32 {
t.Fatalf("fileKeySize = %d, want 32 (256-bit)", fileKeySize)
}
}
// TestPQWrongIdentity confirms a different identity cannot decrypt.
func TestPQWrongIdentity(t *testing.T) {
id, _ := GeneratePQIdentity()
other, _ := GeneratePQIdentity()
buf := &bytes.Buffer{}
w, err := Encrypt(buf, id.Recipient())
if err != nil {
t.Fatal(err)
}
w.Write([]byte("secret"))
w.Close()
if _, err := Decrypt(bytes.NewReader(buf.Bytes()), other); err == nil {
t.Fatal("decryption with wrong identity unexpectedly succeeded")
}
}
// TestSuiteRegistry checks the default suite is registered and self-describing.
func TestSuiteRegistry(t *testing.T) {
s := defaultSuite()
if s.tag() != "frodo640shake+mlkem768" {
t.Fatalf("unexpected default suite %q", s.tag())
}
if pqSuitesByID[s.id()] != s {
t.Fatal("suite not registered by id")
}
if pqSuitesByTag[s.tag()] != s {
t.Fatal("suite not registered by tag")
}
}
// TestSeedDeterministic confirms an identity round-trips through its seed, which
// is what makes compact passphrase-wrapped identities possible.
func TestSeedDeterministic(t *testing.T) {
id, err := GeneratePQIdentity()
if err != nil {
t.Fatal(err)
}
id2, err := newPQIdentityFromSeed(defaultSuite(), id.Seed())
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(id.pub, id2.pub) || !bytes.Equal(id.priv, id2.priv) {
t.Fatal("identity not deterministic from seed")
}
}
func TestIdentityAndRecipientAccessorsReturnCopies(t *testing.T) {
id, err := GeneratePQIdentity()
if err != nil {
t.Fatal(err)
}
seed := id.Seed()
seed[0] ^= 0xff
if id.seed[0] == seed[0] {
t.Fatal("Seed returned mutable identity internals")
}
inputSeed := id.Seed()
id2, err := newPQIdentityFromSeed(defaultSuite(), inputSeed)
if err != nil {
t.Fatal(err)
}
inputSeed[0] ^= 0xff
if id2.seed[0] == inputSeed[0] {
t.Fatal("newPQIdentityFromSeed retained caller-owned seed slice")
}
recipient := id.Recipient()
pub := recipient.Bytes()
pub[0] ^= 0xff
if recipient.pub[0] == pub[0] {
t.Fatal("Bytes returned mutable recipient internals")
}
recipient.pub[0] ^= 0xff
if id.pub[0] == recipient.pub[0] {
t.Fatal("Recipient returned mutable identity public-key internals")
}
}