crypto

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 9 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 noteID + fieldName, id first, no separator; 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.
  • An encrypted note may have an empty title (sent as "", not an envelope); content must always be a valid envelope.
Attachments (binary envelope — not yet implemented in the CLI)
"HRBC2"(5 ASCII bytes) ‖ iv(12) ‖ ciphertext ‖ tag(16)   // raw bytes
resources.hash = sha256(the whole binary envelope)

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 note id immediately followed by the field name ("title" or "content"), with no separator, so an envelope cannot be transplanted to another note or field.

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.

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 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 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 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