crypto

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 9 Imported by: 3

README

crypto

arkoren.dev/core/service/crypto defines authenticated-encryption contracts and the typed Encrypter facade. Use it for stored tokens or personal data that your service must recover; use password hashing for passwords instead.

Use a driver from its own module, then wrap it with crypto.New for JSON-encoded values. Use EncryptRaw and DecryptRaw for bytes.

Install go get arkoren.dev/core and a cipher driver such as go get arkoren.dev/driver/aes from your application's module directory. Load a persistent secret key before constructing the driver and handle constructor errors before using the encrypter. Never generate a replacement key on every startup: existing ciphertext would become unreadable.

Follow the encryption guide for a typed round trip and safe key rotation, or the crypto API reference for all operations and failure behavior.

Documentation

Overview

Package crypto defines the authenticated-encryption contract and an Encrypter facade for typed values. It uses its primary driver for encryption and tries configured previous drivers in order for decryption, allowing gradual rotation.

Construction policies run directly once in order on a fresh Builder. Nil entries panic; expanded nil/empty slices supply no edits. Previous appends copied driver interfaces; the live drivers themselves remain shared. New validates the primary before policies and all fallbacks afterwards. It does not encrypt, decrypt, connect or start a driver during construction.

Optional aggregate metrics count and time complete facade calls, including JSON encoding/decoding failures and all key attempts. Decryption records one final logical outcome, never primary or intermediate fallback failures. A successful previous_key outcome means the caller can rotate the value, not that a replacement was persisted. DecryptWithRotation's boolean reports which driver authenticated the ciphertext, even if later JSON decoding fails; only use or rotate the decoded value after a nil error. A decoding failure records an error outcome, never previous_key. Labels contain bounded operation, outcome and error classes, never keys, plaintext, ciphertext or native errors. No spans or events are created. Nil Builder.Telemetry follows telemetry.Default per call; telemetry.New(nil) disables reporting without timing or instrument construction on calls. Published telemetry selections detach from the draft; the telemetry service remains shared. Driver and application JSON codec panics propagate unchanged. A panicking call has no completed logical result and records neither count nor duration, including when a previous key succeeded before JSON decoding panicked.

Example:

encrypter, err := crypto.New(current, func(encrypter *crypto.Builder) {
	encrypter.Previous(previous)
})
if err != nil {
	return err
}
_ = encrypter

Index

Constants

This section is empty.

Variables

View Source
var ErrEncrypterClosed = errors.New("encrypter is closed")

ErrEncrypterClosed identifies use of a stopped driver that owned key material. Match it with errors.Is and construct a new active driver before retrying; an Encrypter does not restart or take ownership of its drivers.

Example:

_, err := encrypter.DecryptRaw(ciphertext)
if errors.Is(err, crypto.ErrEncrypterClosed) {
	return fmt.Errorf("decrypt with an active driver: %w", err)
}
if err != nil {
	return err
}
View Source
var ErrInvalidCiphertext = errors.New("invalid ciphertext")

ErrInvalidCiphertext is returned by Decrypt when the input is truncated, was altered, or was not produced by the driver's key and parameters. A facade tries its configured previous drivers before returning the primary failure; this sentinel alone does not distinguish tampering from a wrong key.

Example:

_, err := encrypter.DecryptRaw(ciphertext)
if errors.Is(err, crypto.ErrInvalidCiphertext) {
	return fmt.Errorf("reject the unauthenticated encrypted record: %w", err)
}
if err != nil {
	return err
}
View Source
var ErrInvalidDriver = errors.New("encryption driver is invalid")

ErrInvalidDriver identifies a nil current or previous encryption driver. New rejects a nil current driver before construction callbacks and a nil previous driver after all callbacks; no driver operation is invoked.

Example:

_, err := crypto.New(nil)
if errors.Is(err, crypto.ErrInvalidDriver) {
	return fmt.Errorf("configure a current encryption driver: %w", err)
}

Functions

This section is empty.

Types

type Builder

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

Builder configures decryption fallbacks and aggregate metrics for New. Methods return this draft; telemetry services remain shared dependencies. New copies the fallback interface slice, not the live drivers it contains. Retaining the draft cannot change an Encrypter's fallback ordering.

Example:

encrypter, err := crypto.New(current, func(encrypter *crypto.Builder) {
	encrypter.Previous(previous)
})
if err != nil {
	return err
}
_ = encrypter

func (*Builder) Previous

func (encrypter *Builder) Previous(drivers ...Driver) *Builder

Previous appends drivers in decryption fallback order, including across calls. New validates nil fallback drivers after all policies. The supplied interface slice is copied immediately; driver objects remain shared dependencies.

Example:

encrypter, err := crypto.New(current, func(encrypter *crypto.Builder) {
	encrypter.Previous(previous)
})
if err != nil {
	return err
}
_ = encrypter

func (*Builder) Telemetry

func (encrypter *Builder) Telemetry(service *telemetry.Telemetry) *Builder

Telemetry selects aggregate metrics without traces or events. Nil resolves telemetry.Default per call; telemetry.New(nil) explicitly disables metrics. The service stays shared, but retaining this draft cannot replace a published Encrypter's selection. It returns the same draft.

Example:

encrypter, err := crypto.New(driver, func(encrypter *crypto.Builder) {
	encrypter.Telemetry(telemetry.New(nil))
})
if err != nil {
	return err
}
_ = encrypter

type BuilderFunc

type BuilderFunc = func(*Builder)

BuilderFunc edits one fresh construction draft directly, once and synchronously in order. A nil current driver is rejected before callbacks; nil callback entries panic and expanded nil or empty slices omit edits. Publication detaches the fallback interface slice, not the live drivers or their referenced state. Construction callbacks themselves are not retained.

Example:

var rotation crypto.BuilderFunc = func(encrypter *crypto.Builder) {
	encrypter.Previous(previous)
}
encrypter, err := crypto.New(current, rotation)
if err != nil {
	return err
}
_ = encrypter

type Driver

type Driver interface {
	// Encrypt encrypts raw bytes using the driver's current key and parameters.
	// Empty input is valid; the input is not modified and the returned
	// ciphertext does not alias it. Driver failures are returned as errors.
	//
	// Example:
	//
	//	ciphertext, err := driver.Encrypt([]byte("fixture"))
	//	if err != nil {
	//		return err
	//	}
	//	_ = ciphertext
	Encrypt(value []byte) ([]byte, error)

	// Decrypt decrypts raw bytes. Input that fails authentication yields an
	// error wrapping [ErrInvalidCiphertext]. The input is not modified and the
	// returned plaintext does not alias it. This driver alone does not try the
	// Encrypter's previous keys; the facade owns fallback ordering.
	//
	// Example:
	//
	//	plaintext, err := driver.Decrypt(ciphertext)
	//	if err != nil {
	//		return err
	//	}
	//	useCredential(plaintext)
	Decrypt(value []byte) ([]byte, error)
}

Driver encrypts and decrypts raw data.

Encryption is authenticated and randomized: encrypting the same value twice yields different outputs that both decrypt to the value, and any modification of an output makes Decrypt fail. Encrypt accepts an empty value. Neither method modifies its argument, and the result never aliases it. A driver that holds key material and has been stopped returns ErrEncrypterClosed from both methods.

Example:

var driver crypto.Driver = encrypter.Driver()
ciphertext, err := driver.Encrypt([]byte("fixture"))
if err != nil {
	return err
}
_ = ciphertext // Raw driver calls bypass facade metrics and fallback policy.

type Encrypter

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

Encrypter provides typed encryption over a Driver. It is immutable after New and safe for concurrent use whenever its drivers are. Aggregate metrics describe complete calls, not individual fallback attempts. The zero Encrypter has no driver; construct it with New before use.

Example:

encrypter, err := crypto.New(driver)
if err != nil {
	return err
}
ciphertext, err := encrypter.Encrypt("stored token")
if err != nil {
	return err
}
_ = ciphertext

func New

func New(driver Driver, configure ...BuilderFunc) (*Encrypter, error)

New creates an Encrypter that encrypts and decrypts with driver. To migrate stored values, pass older drivers with Builder.Previous, then decrypt with DecryptWithRotation and, when it reports a previous key, encrypt with this Encrypter and persist the replacement in the caller's transaction.

It returns ErrInvalidDriver when driver or any previous driver is nil. The primary driver is validated before callbacks; fallback validation follows them. Callbacks run directly once in order; supplied nil entries panic, while expanded nil or empty slices omit edits. Construction performs no I/O. Driver objects and any state they reference remain shared; construction callbacks are not retained. The caller owns each driver's lifecycle and must not stop it while this Encrypter can still use it.

Example:

encrypter, err := crypto.New(current, func(encrypter *crypto.Builder) {
	encrypter.Previous(previous)
})
if err != nil {
	return err
}
_ = encrypter

func (*Encrypter) Decrypt

func (encrypter *Encrypter) Decrypt[T any](value []byte) (res T, err error)

Decrypt decrypts value and JSON-decodes it into T. Metrics cover all key attempts and decoding as one logical operation; a decoding error is a failed operation even after successful decryption. Panics propagate without recording a completed operation.

Example:

token, err := encrypter.Decrypt[string](ciphertext)
if err != nil {
	return err
}
_ = token

func (*Encrypter) DecryptRaw

func (encrypter *Encrypter) DecryptRaw(value []byte) ([]byte, error)

DecryptRaw decrypts raw bytes. A normal return records one logical decrypt across the entire key chain. Panics propagate without recording a completed operation.

Example:

plaintext, err := encrypter.DecryptRaw(ciphertext)
if err != nil {
	return err
}
_ = plaintext

func (*Encrypter) DecryptRawWithRotation

func (encrypter *Encrypter) DecryptRawWithRotation(value []byte) (result []byte, previous bool, err error)

DecryptRawWithRotation decrypts raw bytes and reports whether a previous driver succeeded. When it does, encrypt the plaintext with this Encrypter and persist the replacement using the caller's normal write path. Metrics combine all driver attempts into one final outcome, preserving the primary error if all fail. Successful fallback never implies persisted rotation. A true boolean accompanies successful raw decryption; any decryption failure returns false. No JSON decoding occurs. Panics propagate without recording a completed operation. The example's persistReplacement function is application-owned persistence.

Example:

plaintext, previous, err := encrypter.DecryptRawWithRotation(ciphertext)
if err != nil {
	return err
}
if previous {
	replacement, err := encrypter.EncryptRaw(plaintext)
	if err != nil {
		return err
	}
	if err := persistReplacement(replacement); err != nil {
		return err
	}
}

func (*Encrypter) DecryptWithRotation

func (encrypter *Encrypter) DecryptWithRotation[T any](value []byte) (res T, usedPreviousKey bool, err error)

DecryptWithRotation decrypts and JSON-decodes value, reporting whether a previous driver authenticated the ciphertext. The boolean remains true if that driver's plaintext later fails JSON decoding; inspect err before using the result or replacing stored data. Only after a nil error, encrypt the decoded result with this Encrypter and persist the replacement using the caller's normal write path when the boolean is true. Metrics record the final returned result once, including JSON decoding errors. A decode error has an error outcome even when the boolean is true. A successful previous_key outcome does not mean rotation was persisted. Panics propagate without recording a completed operation. The example's persistReplacement function is application-owned persistence.

Example:

token, previous, err := encrypter.DecryptWithRotation[string](ciphertext)
if err != nil {
	return err
}
if previous {
	replacement, err := encrypter.Encrypt(token)
	if err != nil {
		return err
	}
	if err := persistReplacement(replacement); err != nil {
		return err
	}
}

func (*Encrypter) Driver

func (encrypter *Encrypter) Driver() Driver

Driver returns the shared primary encryption driver, not previous drivers. Direct calls bypass this Encrypter's JSON encoding, fallback chain, and aggregate metrics. The driver retains its original lifecycle owner.

Example:

ciphertext, err := encrypter.Driver().Encrypt([]byte("fixture"))
if err != nil {
	return err
}
_ = ciphertext

func (*Encrypter) DriverAs

func (encrypter *Encrypter) DriverAs[T any]() (T, bool)

DriverAs returns the first driver of type T in the chain of the underlying driver. A driver that wraps another exposes it with an Unwrap() Driver method, so wrappers such as prefixing or tracing drivers do not hide the concrete driver. Only the primary chain is searched, not previous drivers. A failed match returns the zero T and false. Matching does not transfer lifecycle ownership or add facade metrics to native calls.

With aescrypto imported from arkoren.dev/driver/aes/aescrypto:

driver, ok := encrypter.DriverAs[*aescrypto.Driver]()
if !ok {
	return errors.New("primary driver is not AES")
}
ciphertext, err := driver.Encrypt([]byte("fixture"))
if err != nil {
	return err
}
_ = ciphertext

func (*Encrypter) Encrypt

func (encrypter *Encrypter) Encrypt[T any](value T) (result []byte, err error)

Encrypt encrypts a JSON-encoded value. Metrics include encoding and driver failures, with one observation per normal return. Panics propagate without recording a completed operation.

Example:

ciphertext, err := encrypter.Encrypt("stored token")
if err != nil {
	return err
}
_ = ciphertext

func (*Encrypter) EncryptRaw

func (encrypter *Encrypter) EncryptRaw(value []byte) (result []byte, err error)

EncryptRaw encrypts raw bytes. A normal return records one encryption operation without JSON encoding. Panics propagate without recording a completed operation.

Example:

ciphertext, err := encrypter.EncryptRaw(plaintext)
if err != nil {
	return err
}
_ = ciphertext

Directories

Path Synopsis
Package cryptotest provides Run, a conformance suite that every crypto.Driver implementation must pass.
Package cryptotest provides Run, a conformance suite that every crypto.Driver implementation must pass.

Jump to

Keyboard shortcuts

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