crypto

package
v0.1.35 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 10 Imported by: 1 module, 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

Harbor client encryption — canonical contract

This package is the reference implementation of Harbor's client-side, end-to-end note encryption. The server is zero-knowledge: it stores opaque ciphertext and an opaque per-user keystore and never holds, derives, or validates any key. All key derivation, wrapping, and field encryption happens in the client.

Two formats must match byte-for-byte across every Harbor client (CLI, iOS, web, …) for notes encrypted on one device to decrypt on another. This is that contract. The server's only crypto behavior is a structural check of the field envelope (internal/notes/crypto.go) and excluding encrypted content from search/OCR/sharing/export.

Key model — envelope encryption

  1. KEK — Argon2id(passphrase, salt) → a 32-byte Key-Encryption-Key.
  2. Master key — a random 32-byte key generated once at setup. Every encrypted note field is encrypted with the master key.
  3. Wrap — the master key is encrypted ("wrapped") with the KEK and stored in the keystore. Changing the passphrase only re-wraps the master key — no note is ever re-encrypted.

HRBK1 keystore (one synced, opaque per-user record)

keystore.blob is UTF-8 JSON, these fields exactly (snake_case is part of the contract):

{
  "version": "HRBK1",
  "kdf": "argon2id",
  "kdf_mem_kib": 65536,
  "kdf_iterations": 3,
  "kdf_parallelism": 1,
  "salt": "<base64url, unpadded, 16 bytes>",
  "wrapped_key": "<base64url, unpadded: iv(12) ‖ AES-256-GCM(KEK, master_key) ‖ tag(16)>"
}
  • Argon2id (RFC 9106), default m = 65536 KiB, t = 3, p = 1, 16-byte salt → 32-byte KEK.
  • Key wrap: AES-256-GCM, key = KEK, nonce = the first 12 bytes of wrapped_key, no AAD.
  • Exactly one live keystore row per user; it syncs like any record (last-write-wins).

HRBC2 field envelope (a note's title and content)

"HRBC2" "." base64url(iv[12]) "." base64url(ciphertext ‖ tag[16])
  • AES-256-GCM under the master key, a fresh random 12-byte nonce per operation (never reuse).
  • base64url is UNPADDED (RawURLEncoding) — matches the server validator.
  • AAD = the UTF-8 bytes of recordID + ":" + fieldName — id first, a literal colon, then the field name; fieldName is the literal "title" or "content". e.g. "9c2e…:title". This binds an envelope to one note and one field; the same AAD must be supplied to decrypt or GCM authentication fails. ⚠️ This byte sequence is the cross-client interop contract, not a local choice. The canonical definition lives in the web client (app.harbor.my → web/src/lib/crypto/envelope.ts); macOS/iOS, Android and Windows all match it byte-for-byte, and so must this CLI. The separator was missing here until #86, which made every CLI-sealed note undecryptable by every other client. The shared known-answer vector is pinned as a literal in crypto_test.go (crossClientVector, asserted in both directions by TestSealField_CrossClientVector and TestOpenField_CrossClientVector) so it cannot drift again.
  • An encrypted note may have an empty title (sent as "", not an envelope); content must always be a valid envelope.
Attachments (binary envelope)
"HRBC2"(5 ASCII bytes) ‖ iv(12) ‖ ciphertext ‖ tag(16)   // raw bytes
resources.hash = sha256(the whole binary envelope)
  • AES-256-GCM under the master key — the same key as note fields. There is no per-note or per-resource key.
  • AAD: NONE. Attachments are sealed with a nil/empty AAD. This is the finalized rule, and it is what web, macOS/iOS, Android and Windows already do; binding AAD here would make files written by the CLI unreadable by all of them. Integrity is instead bound by the content address: the server stores hash = sha256(envelope), computed over the ciphertext.
  • Because the hash covers ciphertext and every seal uses a fresh nonce, dedup only works across identical ciphertext — in practice, never. Accepted.
  • The minimum envelope is 33 bytes (5 + 12 + 16). Anything sniffing for the magic must read at least that many bytes, or every input answers "not encrypted"; that bug has shipped on another client before. Use crypto.BinaryEnvelopeMinBytes.
  • filename and mime stay plaintext on the resource record (an accepted metadata leak, matching the other clients), and size is the envelope size, not the plaintext size.
  • ⚠️ A string envelope begins with the same 5-byte magic, so magic-sniffing cannot distinguish the two. They never mix in practice — string envelopes live in note fields, binary ones in blob bytes.

Go: crypto.SealBytes / crypto.OpenBytes / crypto.IsBinaryEnvelope.

Writing an encrypted note

Encrypted notes must be created with a client-generated id (sent in the create body) because the field AAD binds to it. Send is_encrypted: true with the sealed title/content through the normal REST POST/PATCH /notes endpoints (which structurally validate the envelope). The plaintext shadow must be empty. append is not supported on encrypted notes.

Irreversibility

There is no key escrow and no reset. If the passphrase is lost, the master key — and every encrypted note — is permanently unrecoverable.

See the CLI surface in cmd/crypto.go and the authoritative server spec at docs/encryption.md in the API repo.

Documentation

Overview

Package crypto implements Harbor's client-side, end-to-end note encryption — the part the server never sees. Harbor is zero-knowledge: the server stores opaque ciphertext and an opaque per-user keystore and never holds, derives, or validates any key. All key derivation, wrapping, and field encryption happens here, in the client.

This package is the canonical CLI implementation of the interop contract. Two formats must match byte-for-byte across every Harbor client:

  • HRBK1 keystore — a JSON blob holding the KEK salt, Argon2id parameters, and the wrapped master key. It is synced as one opaque per-user record.
  • HRBC2 field envelope — the per-field ciphertext string stored in a note's title and content: "HRBC2" "." base64url(iv12) "." base64url(ct‖tag16).

Key model (envelope encryption): a single passphrase + a per-user random salt derive a Key-Encryption-Key (KEK) via Argon2id; a random 256-bit master key is generated once and wrapped with the KEK in the keystore; every note field is encrypted with the master key (AES-256-GCM, fresh 12-byte nonce per op). This is why a passphrase change is cheap — re-wrap the master key, no note re-encrypt.

All base64url is UNPADDED (RawURLEncoding), matching the server's structural validator. The AEAD additional-authenticated-data (AAD) for a field is the UTF-8 bytes of "<noteID>:<fieldName>" — the note id, a literal colon, then "title" or "content" — so an envelope cannot be transplanted to another note or field. That exact byte sequence is the cross-client interop contract shared with web, macOS/iOS, Android and Windows; see fieldAAD and crypto/README.md.

Index

Constants

View Source
const (
	// KeystoreVersion tags the HRBK1 keystore blob.
	KeystoreVersion = "HRBK1"
	// EnvelopeVersion tags an HRBC2 per-field ciphertext envelope.
	EnvelopeVersion = "HRBC2"
)

Canonical format constants. These are part of the cross-client wire contract; do not change them without coordinating every Harbor client.

View Source
const BinaryEnvelopeMinBytes = len(EnvelopeVersion) + nonceLen + tagLen

BinaryEnvelopeMinBytes is the smallest possible HRBC2 binary envelope: the 5-byte magic, a 12-byte nonce and a 16-byte GCM tag, wrapping zero bytes of plaintext.

Exported because sniffing fewer bytes than this makes IsBinaryEnvelope answer false for EVERY input, which silently turns "skip the ones already encrypted" into "skip all of them". That exact bug has shipped on another Harbor client before; read at least this many bytes before sniffing.

Variables

View Source
var (
	// ErrBadPassphrase means the wrapped master key would not unwrap — almost
	// always a wrong passphrase (GCM authentication failed).
	ErrBadPassphrase = errors.New("incorrect passphrase: could not unwrap the master key")
	// ErrNotEnvelope means a string is not a structurally-valid HRBC2 envelope.
	ErrNotEnvelope = errors.New("not an HRBC2 ciphertext envelope")
	// ErrDecrypt means an envelope failed to decrypt or authenticate (wrong key,
	// wrong AAD, or corrupt data).
	ErrDecrypt = errors.New("decryption failed: wrong key or corrupt data")
	// ErrBadKeystore means the keystore blob is malformed or an unknown version.
	ErrBadKeystore = errors.New("malformed or unsupported keystore")
)

Sentinel errors callers branch on to render friendly messages.

View Source
var DefaultArgon2Params = Argon2Params{MemKiB: 65536, Iterations: 3, Parallelism: 1}

DefaultArgon2Params is the canonical profile from docs/encryption.md (RFC 9106): m = 64 MiB, t = 3, p = 1.

Functions

func DeriveKEK

func DeriveKEK(passphrase string, salt []byte, p Argon2Params) []byte

DeriveKEK derives the 32-byte Key-Encryption-Key from the passphrase and salt using Argon2id with the given parameters. The same (passphrase, salt, params) always yields the same KEK, which is what lets any device unwrap the keystore.

func IsBinaryEnvelope added in v0.1.28

func IsBinaryEnvelope(b []byte) bool

IsBinaryEnvelope reports whether b begins an HRBC2 binary envelope and is long enough to be one. It never decrypts, so a false positive is possible in principle — arbitrary bytes starting with "HRBC2" — but the magic makes that vanishingly unlikely for real files, and OpenBytes fails closed regardless.

b may be a prefix of the file rather than the whole of it, but it must be at least BinaryEnvelopeMinBytes long or this returns false for everything.

func IsEnvelope

func IsEnvelope(s string) bool

IsEnvelope reports whether s is a structurally well-formed HRBC2 envelope, mirroring the server's looksLikeEnvelope check (3 dot parts, "HRBC2" tag, base64url-decodable, 12-byte IV, ≥16-byte ciphertext). It never decrypts.

func NewKeystore

func NewKeystore(passphrase string, p Argon2Params) (blob string, masterKey []byte, err error)

NewKeystore performs first-time setup: it generates a random master key and a random salt, derives the KEK from the passphrase, wraps the master key, and returns the serialized HRBK1 blob together with the in-memory master key. The master key is the long-lived secret; losing the passphrase that wraps it makes the key (and all ciphertext) unrecoverable — there is no escrow.

func NewUUIDv4

func NewUUIDv4() (string, error)

NewUUIDv4 returns a random RFC 4122 version-4 UUID. Encrypted notes must be created with a client-supplied id because the field AAD binds to that id, so the id has to exist before the title/content are sealed.

func OpenBytes added in v0.1.28

func OpenBytes(masterKey, envelope []byte) ([]byte, error)

OpenBytes reverses SealBytes, returning the original plaintext. It returns ErrNotEnvelope when the input is not structurally an HRBC2 binary envelope (so a caller can tell "this file was never encrypted" apart from "this file will not open"), and ErrDecrypt when authentication fails.

func OpenField

func OpenField(masterKey []byte, recordID, fieldName, envelope string) (string, error)

OpenField decrypts an HRBC2 envelope back to plaintext under the master key, using AAD bound to (recordID, fieldName). It returns ErrNotEnvelope for a non-envelope string and ErrDecrypt when authentication fails (wrong key/AAD or corrupt data).

func RewrapMasterKey

func RewrapMasterKey(k *Keystore, oldPass, newPass string, p Argon2Params) (string, error)

RewrapMasterKey rotates the passphrase: it unwraps the master key with the old passphrase, then re-wraps the SAME master key under a new KEK derived from the new passphrase and a fresh salt. No note is re-encrypted. Returns the new blob.

func SealBytes added in v0.1.28

func SealBytes(masterKey, plaintext []byte) ([]byte, error)

SealBytes encrypts raw bytes into the HRBC2 BINARY envelope used for attachments:

"HRBC2"(5 ASCII) ‖ iv(12) ‖ ciphertext ‖ tag(16)

AES-256-GCM under the master key with a fresh random nonce, and — unlike the string envelope used for note fields — **no AAD**. That is not an oversight: web, macOS/iOS, Android and Windows all pass no AAD here, because an attachment's integrity is bound instead by its content address, which the server computes as sha256 over this whole envelope. Adding AAD would make files written here unreadable everywhere else. See crypto/README.md.

func SealField

func SealField(masterKey []byte, recordID, fieldName, plaintext string) (string, error)

SealField encrypts a note field's plaintext into an HRBC2 envelope under the master key, with a fresh random nonce and AAD bound to (recordID, fieldName). fieldName must be the literal "title" or "content".

func UnwrapMasterKey

func UnwrapMasterKey(k *Keystore, passphrase string) ([]byte, error)

UnwrapMasterKey derives the KEK from the passphrase and the keystore's salt and uses it to unwrap (decrypt) the master key. A wrong passphrase surfaces as ErrBadPassphrase rather than a raw GCM error.

Types

type Argon2Params

type Argon2Params struct {
	MemKiB      uint32 // m — memory in KiB
	Iterations  uint32 // t — passes
	Parallelism uint8  // p — lanes
}

Argon2Params are the Argon2id cost parameters carried in the keystore so every device derives the same KEK from the passphrase.

type Keystore

type Keystore struct {
	Version     string `json:"version"`
	KDF         string `json:"kdf"`
	KDFMemKiB   uint32 `json:"kdf_mem_kib"`
	KDFIter     uint32 `json:"kdf_iterations"`
	KDFParallel uint8  `json:"kdf_parallelism"`
	Salt        string `json:"salt"`
	WrappedKey  string `json:"wrapped_key"`
}

Keystore is the parsed HRBK1 blob. The on-disk/on-wire form is exactly this JSON object (snake_case field names are part of the contract). Salt and WrappedKey are unpadded base64url; WrappedKey decodes to iv(12)‖ct‖tag(16).

func ParseKeystore

func ParseKeystore(blob string) (*Keystore, error)

ParseKeystore decodes and structurally validates an HRBK1 keystore blob, rejecting unknown versions or KDFs so a client never silently mis-derives.

func (*Keystore) Marshal

func (k *Keystore) Marshal() (string, error)

Marshal serializes the keystore to its canonical JSON blob form.

Jump to

Keyboard shortcuts

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