Inside Piko2fa: Cryptography, Fail-Safe Storage, and Dependency-Free Go

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

In the previous article, we explored what Piko2fa does, why I decided to store my 2FA keys in an encrypted file under my control, and its threat model. Now it’s time to truly look under the hood.

This is the fifth installment in the Go series. We’re not going to examine a toy example, but a real-world tool with about 2,900 lines of production code, backed by over 4,450 lines of tests, and compiled without CGO (CGO_ENABLED=0) for Windows, Linux, and macOS. Furthermore, while preparing this walkthrough, I took the opportunity to critically review the core and apply five concrete improvements in commit 69a9d80.

In this first part, we’ll focus on the core: how the project is organized, why it uses this on-disk format, how it saves data without rendering the vault unusable during a power cut or crash, and how to test failures that are typically hard to reproduce.

Project Structure and Why There’s No SQLite or CGO

The code is split between a minimal entry point and private packages under internal/:

piko2fa/
├── cmd/piko2fa/main.go        # 19 líneas: arranque y salida con código de error
└── internal/
    ├── totp/                  # RFC 6238 / RFC 4226 puro
    ├── model/                 # Entry, validaciones y deduplicación por secreto
    ├── otpauth/               # parseo y formato de URIs otpauth://
    ├── gamigration/           # importador de Google Authenticator (protowire)
    ├── qrimage/               # decodificación de QR desde PNG o JPEG
    ├── vault/                 # KDF, formato binario, cifrado y guardado atómico
    ├── tui/                   # interfaz interactiva de solo lectura (Bubble Tea)
    └── cli/                   # comandos (cobra), consola, portapapeles y tests

In Go, everything residing inside internal/ can only be imported from within the module itself. This avoids having to stabilize a public API for a command-line binary and allows for complete freedom when refactoring internal packages.

One of the earliest architectural decisions was ruling out SQLite in favor of a single fully encrypted JSON file (vault.bin): it is decrypted entirely into memory upon opening, modified in-memory, and re-encrypted in its entirety when saved. Three clear reasons led to this choice:

  1. CGO breaks effortless cross-compilation. SQLCipher depends on C. Without CGO, building binaries for Windows, Linux, and macOS from any machine is just a single go build command.
  2. Field-level encryption leaks metadata. Even if you encrypt the secret in each row, a database still exposes how many accounts you have, their relative sizes, or which rows have changed. With a single encrypted blob, all of that disappears.
  3. No decrypted temporary files on disk. Decrypting a database to a temporary file opens the door to unencrypted artifacts lingering after a crash or on an SSD (where secure deletion is trickier than it seems).

For a password manager holding tens of thousands of entries and binary attachments, this approach wouldn’t scale. For ~300 2FA accounts—a few dozen kilobytes of JSON—it’s simple, fast, and easy to audit.

The Vault Format: Authenticated Encryption and Pre-KDF Defenses

Every time Piko2fa saves the vault, it generates a binary file with this big-endian structure (internal/vault/format.go):

magic (4: "PK2F") | versión (1) | tiempo (4) | memoria en KiB (4) | hilos (1) | sal (16) | nonce (24) | texto cifrado + tag (16)

The first 30 bytes (from PK2F up to the 16-byte salt) make up the header. The 32-byte encryption key is derived using Argon2id (t=3, 64 MiB, 4 threads) from the master password and that salt. Then, the JSON payload is encrypted with XChaCha20-Poly1305, using a fresh salt and a random 24-byte nonce on every save.

There are two important details in the seal and unseal functions:

  1. The header is authenticated as AAD (Additional Authenticated Data). It isn’t encrypted—the salt and Argon2id parameters need to be readable to derive the key—but it is passed into aead.Seal and aead.Open. If anyone flips a single bit in the version, parameters, or salt, Poly1305 rejects decryption.
  2. Argon2id parameters are validated before deriving the key. This detail is easy to overlook: since the header cannot be authenticated until the key is derived, an attacker or a corrupted file could specify 4 GiB of memory or 0 threads in the header. Without upfront bounds checks, the program would exhaust RAM or panic before even reaching aead.Open.

Here is how it looks in internal/vault/format.go:

const (
	minTime      = 1
	maxTime      = 10
	minThreads   = 1
	maxThreads   = 16
	minMemoryKiB = 32 * 1024
	maxMemoryKiB = 1024 * 1024
)

func unseal(password, data []byte) ([]byte, error) {
	if len(data) <= len(magic) || !bytes.HasPrefix(data, []byte(magic)) {
		return nil, ErrInvalid
	}
	if data[len(magic)] != formatVersion {
		return nil, ErrUnsupportedVersion
	}
	if len(data) < minSize {
		return nil, ErrInvalid
	}

	rest := data[len(magic)+1:]
	p := kdfParams{
		time:      binary.BigEndian.Uint32(rest[0:4]),
		memoryKiB: binary.BigEndian.Uint32(rest[4:8]),
		threads:   rest[8],
	}
	if !p.valid() {
		return nil, ErrInvalid
	}
	salt := rest[9 : 9+saltSize]

	key := deriveKey(password, salt, p)
	defer clear(key)
	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, ErrInvalid
	}

	header := data[:headerSize]
	nonce := data[headerSize : headerSize+chacha20poly1305.NonceSizeX]
	plaintext, err := aead.Open(nil, nonce, data[headerSize+chacha20poly1305.NonceSizeX:], header)
	if err != nil {
		return nil, ErrInvalid
	}
	return plaintext, nil
}

Notice also the error handling: an incorrect password, an out-of-range header, and an authentication failure all return the exact same ErrInvalid, offering zero clues as to what went wrong. Only an unsupported future version returns ErrUnsupportedVersion, because the version byte is public and it helps to let the user know they need a newer release of the tool.

Saving Without Breaking Anything (Even on Windows)

An intact encrypted file is of little use if a sudden power loss or a write error leaves it truncated. The vault package wraps every write operation in multiple layers of defense (internal/vault/vault.go):

  1. Inter-process locking via a dedicated file (vault.bin.lock). Acquired using gofrs/flock from Open to Close, covering the full read-modify-write cycle. We don’t lock vault.bin directly because saving replaces the file via rename. In addition, the CLI always prompts for the password before calling Open, avoiding holding the lock while the user is typing.
  2. Verifying the current file before touching .bak. Before overwriting vault.bin.bak and vault.bin, Save verifies that the vault.bin currently on disk can be decrypted with the provided password:
func (s *FileStore) Save(password []byte) error {
	if s.closed {
		return ErrClosed
	}
	if !s.loaded {
		return ErrNotLoaded
	}
	if len(password) == 0 {
		return ErrEmptyPassword
	}

	current, err := s.readVault()
	if err != nil {
		return err
	}
	plaintext, err := unseal(password, current)
	if err != nil {
		return err
	}
	clear(plaintext)

	if err := s.writeAtomic(s.path+backupSuffix, current, "backup"); err != nil {
		return err
	}
	return s.writeVault(password)
}

This verification costs an extra Argon2id key derivation (a few hundred milliseconds) each time you add or delete an account. It is a deliberate tradeoff: it prevents a damaged file from clobbering the only healthy .bak and keeps users from accidentally re-encrypting the vault with a different password. To change the password, there is a dedicated method: ChangePassword (internal/vault/maintenance.go).

  1. Atomic writes and OS-specific quirks. writeAtomic creates a hidden temporary file in the destination directory (.piko2fa-*.tmp), writes the bytes, calls tmp.Sync(), closes the file descriptor, renames over the target, and, on Linux and macOS, syncs the parent directory (syncDir) to make the directory entry durable.

Two specific quirks arise on Windows:

  • You cannot call Sync() on a directory, so syncDir is a no-op on Windows (and on Unix, it ignores syscall.EINVAL for filesystems that don’t support it either).
  • An antivirus or indexer might briefly hold vault.bin open right as you attempt to replace it, causing os.Rename to fail. That’s why rename performs up to 10 retries spaced 100 ms apart, exclusively on Windows.
  1. Crash-tolerant password changes. ChangePassword (internal/vault/maintenance.go) re-encrypts vault.bin.bak first, followed by vault.bin. If a crash happens in between, vault.bin still opens with the old password, allowing the user to simply re-run piko2fa passwd. On retry, reencryptBackup checks whether the .bak already opens with newPassword: if so, it assumes it came from an interrupted attempt and proceeds. If the .bak cannot be opened with either password, it returns ErrBackupUnreadable without touching the primary vault.

Testing the Hard Stuff: Fault Injection and Concurrent Processes

Trivial round-trip tests don’t prove that a save operation is truly atomic. The real risk lies in partial failures and concurrent writes by multiple processes.

To test partial failures without building mock filesystems or giant mock suites, FileStore contains a single-line private field:

step func(name string) error

In production, it is nil, and runStep does nothing. In writeAtomic, before each critical step (create, write, sync, close, rename, syncdir), s.runStep(label + ":...") is called. This enables TestSaveFailureAtEveryStepKeepsVaultReadable (internal/vault/vault_test.go) to inject an error at each of the 12 stages of the save process (6 for .bak and 6 for vault.bin) and verify that:

  • vault.bin on disk remains openable (either in its previous state, or in the new state if only vault:syncdir failed post-rename), and
  • no orphaned .tmp files are left behind in the directory.

To test inter-process locking, TestConcurrentProcessesLoseNoUpdates uses a very idiomatic Go pattern: it spawns 6 subprocesses of the test binary itself (os.Args[0]), filtering for a single helper test:

cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcessAddEntry$", "-test.count=1")
cmd.Env = append(os.Environ(), "PIKO2FA_TEST_VAULT="+path, "PIKO2FA_TEST_NAME="+name)

Each process opens the same vault.bin, waits for the lock on vault.bin.lock, adds its entry, and saves. Once all 6 complete in parallel, the test asserts that all 6 accounts exist and no updates were lost.

Two Small Pieces Without Heavy Libraries: TOTP and Manual Protobuf

Generating a TOTP code per RFC 6238 and RFC 4226 requires no external libraries: it’s simply HMAC over a 64-bit counter followed by dynamic 4-byte truncation:

TOTP in 86 Lines (internal/totp/totp.go)

Generating a TOTP code per RFC 6238 and RFC 4226 requires no external libraries: it’s simply HMAC over a 64-bit counter followed by dynamic 4-byte truncation:

counter := uint64(t.Unix()) / uint64(period)

mac := hmac.New(newHash, secret)
mac.Write(binary.BigEndian.AppendUint64(nil, counter))
sum := mac.Sum(nil)

// Truncamiento dinámico de RFC 4226, sección 5.3.
offset := sum[len(sum)-1] & 0x0f
value := binary.BigEndian.Uint32(sum[offset:]) & 0x7fffffff

return fmt.Sprintf("%0*d", digits, value%modulus), nil

The entire package—supporting SHA1, SHA256, and SHA512, 6 or 8 digits, and calculating remaining seconds—spans 86 lines and is verified against the official RFC 6238 and RFC 4226 test vectors.

Protobuf Without protoc (internal/gamigration/payload.go)

Google Authenticator exports accounts as otpauth-migration://offline?data=... URIs, where data is a base64-encoded Protobuf message (MigrationPayload). Instead of installing protoc, generating .pb.go files, and dragging in generated message structs, the package uses google.golang.org/protobuf/encoding/protowire directly (a lightweight, low-level subpackage).

Implementing this by hand yielded three concrete takeaways:

  1. proto3 omits default/zero values. An export containing a single QR code might omit batch_size, which is why p.batchSize == 0 is normalized to 1 after parsing the message.
  2. Signed int32 integers in varints. If an int32 field carries a negative value, it travels across the wire sign-extended to 64 bits; you must cast to int32(value) before converting to int.
  3. Base64 + characters and url.ParseQuery. url.ParseQuery already URL-decodes the data parameter; decoding it again would corrupt the base64 string. However, some QR readers leave + unencoded instead of %2B, and ParseQuery turns + into a space. Restoring " " back to "+" before calling base64.RawStdEncoding.DecodeString fixes the issue without breaking properly encoded URIs.

Additionally, if new fields appear in future Google Authenticator versions, protowire.ConsumeFieldValue skips them cleanly in the default branch.

Reviewing the Code: Five Improvements Applied to the Core

Re-reading the entire project before writing this series revealed five areas for improvement in the core. All of them were implemented in commit 69a9d80:

  1. Removing an interface with no consumers (vault.Store).
    When designing the project, I defined a Store interface in internal/vault “in case the format changes someday”. In practice, the entire CLI received the concrete *vault.FileStore, and methods like ChangePassword, Export, or Restore didn’t even fit into Store. It’s a reminder of a classic Go proverb: accept interfaces at the consumer when a second implementation emerges, don’t declare them upfront at the producer.
  2. Decoupling deduplication from gamigration.
    The Dedupe function (which detects whether a secret already exists or conflicts with another issuer/name) lived in internal/gamigration, forcing piko2fa add to import the Google Authenticator package just to add a manual entry. Now, Dedupe, Conflict, and DedupeResult live in internal/model/dedupe.go, where domain logic truly belongs.
  3. Unifying invariants between model and store.
    Entry.Validate() (internal/model/entry.go) checked the secret, algorithm, digits, period, and type, but not whether ID was set; that was checked separately in FileStore.Add. Worse yet: decodeContents when loading a vault from disk didn’t check for empty or duplicate IDs. Now Entry.Validate() requires ID != "" and decodeContents rejects duplicate IDs upon loading.
  4. Avoiding duplicate cryptographic work and tightening export details.
    • piko2fa export --encrypted passed through withVault (which derived the key via Argon2id and decrypted JSON in memory) only to then call FileStore.Export, which re-read the file and derived the key a second time. Now, export --encrypted calls s.Export(...) directly after acquiring the lock, running Argon2id only once.
    • FileStore.Export checked os.Stat before writing with writeAtomic, leaving a small time-of-check to time-of-use (TOCTOU) race condition between checking and renaming. It now writes using writeExclusive (O_CREATE|O_EXCL, Sync(), Close(), and syncDir), guaranteeing atomically at the filesystem level that it will never overwrite an existing file.
    • In exportPlaintext (internal/cli/commands.go), plaintext URIs were accumulated in an immutable strings.Builder without a Sync() equivalent. They are now accumulated in a []byte and wiped with a subtle Go nuance:
      var content []byte defer func() { clear(content) }()
      Had we written defer clear(content) directly, Go would have evaluated the initial value of content (nil) when registering the defer, zeroing an empty slice while append allocated an entirely new underlying array behind the scenes.
  5. Module path ready for go install.
    go.mod still listed module piko2fa from early development. Changing it to module github.com/jure-ve/piko2fa allows installing the tool directly with:

What We’ll See in the Next Article

With the vault and cryptography covered, in the second part we’ll move up to the layer closest to the user and human error:

  • How to prevent an accidentally pasted secret URI from leaking into a Cobra error message, a *fs.PathError, or a %#v dump.
  • How to read passwords securely when stdin is piped, and restore terminal echo if the user hits Ctrl+C.
  • Non-obvious Bubble Tea TUI details (such as stripping the monotonic clock with .Round(0) so sleep/suspend time counts toward auto-lock, or sanitizing ANSI sequences from imported accounts).
  • And the second batch of improvements: minor UX bugs in import-ga, CLI-level sanitization, terminal width handling in the TUI, clearing the clipboard on Ctrl+C, and QR decoder optimizations.

All code remains available under the MIT license at github.com/jure-ve/piko2fa, and the five changes from this article are grouped in commit 69a9d80.

Which part of the architecture did you find most interesting, or what would you have done differently? Let me know in the comments.

Keep coding.