crypto

package module
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 19 Imported by: ? modules, 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

config-crypto

CI Go Reference Go Report Card Release OpenSSF Scorecard

Encryption codec for the config library. Provides transparent encryption of configuration values using AES-256-GCM with envelope encryption.

Installation

go get github.com/rbaliyan/config-crypto

Usage

package main

import (
    "context"
    "fmt"

    crypto "github.com/rbaliyan/config-crypto"
    "github.com/rbaliyan/config"
    "github.com/rbaliyan/config/codec"
    "github.com/rbaliyan/config/memory"
)

func main() {
    ctx := context.Background()

    // 32-byte key for AES-256.
    key := []byte("my-32-byte-secret-key-for-aes!!") // Use a proper key in production

    // Create a Provider from raw key bytes.
    provider, err := crypto.NewProvider(key, "key-1")
    if err != nil {
        panic(err)
    }
    defer provider.Close()

    // Create and register the encrypted codec.
    encJSON, err := crypto.NewCodec(codec.Default(), provider)
    if err != nil {
        panic(err)
    }
    codec.Register(encJSON)

    // Set up a config store.
    store := memory.NewStore()
    store.Connect(ctx)
    defer store.Close(ctx)

    // Encrypt sensitive values.
    encoded, _ := encJSON.Encode(ctx, "sk-secret-api-key")
    val, _ := config.NewValueFromBytes(ctx, encoded, encJSON.Name())
    store.Set(ctx, config.DefaultNamespace, "secrets/api-key", val)

    // Read is automatic — codec name "encrypted:json" resolves via registry.
    got, _ := store.Get(ctx, config.DefaultNamespace, "secrets/api-key")
    var result string
    got.Unmarshal(ctx, &result)
    fmt.Println(result) // "sk-secret-api-key"
}

How It Works

The config library stores a codec name (e.g. "encrypted:json") with every value. On read, codec.Get(name) resolves the codec. This package provides an encrypting codec that wraps an inner codec:

  • Encode: serialize with inner codec (JSON) → encrypt with AES-256-GCM
  • Decode: decrypt with AES-256-GCM → deserialize with inner codec (JSON)

Each value uses envelope encryption: a random Data Encryption Key (DEK) encrypts the data, and the DEK itself is wrapped with your Key Encryption Key (KEK). This means:

  • No nonce reuse risk (random DEK per value)
  • Efficient key rotation (only re-wrap DEKs)
  • Ciphertext is portable — anyone holding the same KEK bytes can decrypt, regardless of where those bytes came from (AWS KMS today, Vault KV tomorrow)

The Provider Interface

type Provider interface {
    Name() string
    Connect(ctx context.Context) error
    Encrypt(ctx context.Context, plaintext []byte) ([]byte, error)
    Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)
    HealthCheck(ctx context.Context) error
    Close() error
}

Provider is the single abstraction the codec depends on. Raw key bytes never leave the provider — callers see only Encrypt/Decrypt. Name() returns a short identifier used for logging and observability. Connect initialises any remote connection; in-memory implementations treat it as a no-op. HealthCheck returns nil for a healthy provider; static providers report liveness only (not closed). Close zeros key material and stops any background goroutines.

Two constructors live in the core package:

  • crypto.NewProvider(keyBytes, id) — static, from raw 32-byte AES-256 key bytes. Most common for single-key setups.
  • crypto.NewKeyRingProvider(initialBytes, id, rank) — mutable KeyRingProvider, exposed so KMS packages and application code can drive runtime key rotation. rank is a monotonically increasing version number used by NeedsReencryption to determine key ordering; pass 0 when the backing store does not provide version ordering.

Key Rotation

KeyRingProvider embeds Provider and adds key management methods:

type KeyRingProvider interface {
    Provider
    AddKey(keyBytes []byte, id string, rank uint64) error
    SetCurrentKey(id string) error
    RemoveKey(id string) error
    CurrentKeyID() string
    NeedsReencryption(ciphertext []byte) (bool, error)
}

rank is used by NeedsReencryption to determine ordering: it returns true only when the ciphertext was encrypted with a key whose rank is strictly lower than the current key's rank.

oldKey := []byte("original-32-byte-key-for-aes!!!")
newKey := []byte("rotated-32-byte-key-for-aes!!!!")

ring, _ := crypto.NewKeyRingProvider(newKey, "key-v2", 2)
defer ring.Close()
ring.AddKey(oldKey, "key-v1", 1)

encJSON, _ := crypto.NewCodec(codec.Default(), ring)
codec.Register(encJSON)

// Reads automatically use the correct key (key ID is in the header).
// Writes use the current key (key-v2).

// Check whether a stored ciphertext should be re-encrypted.
needsReenc, _ := ring.NeedsReencryption(storedCiphertext) // true for key-v1 ciphertext

// Remove old key when nothing in the store was encrypted with it.
ring.RemoveKey("key-v1")

Namespace Routing

NamespaceSelector routes Encrypt/Decrypt to different providers based on namespace — useful for multi-tenant config where each tenant has its own KEK:

tenantA, _ := crypto.NewProvider(keyA, "a-v1")
tenantB, _ := crypto.NewProvider(keyB, "b-v1")
fallback, _ := crypto.NewProvider(fallbackKey, "default-v1")

sel, _ := crypto.NewNamespaceSelector(
    crypto.WithNamespaceProvider("tenant-a", tenantA),
    crypto.WithNamespaceProvider("tenant-b", tenantB),
    crypto.WithFallbackProvider(fallback),
)
defer sel.Close() // also closes all registered providers

SelectorCodec wraps a NamespaceSelector with an inner codec so a single codec registration covers every namespace. It reads the namespace from the context — set it with crypto.WithNamespace(ctx, ns) — and routes Encode/Decode to the matching provider. This is the cleaner approach for most applications:

sc, _ := crypto.NewSelectorCodec(sel, codec.Default())
codec.Register(sc) // one registration covers all namespaces

// Inject the namespace into ctx before store operations.
ctx = crypto.WithNamespace(ctx, "tenant-a")
store.Set(ctx, "tenant-a", "db-password", value)

NamespaceFromContext(ctx) reads the namespace back, and NamespaceContextKey is the underlying context key. If no provider matches the namespace and no fallback is registered, Encode/Decode return ErrNoProviderForNamespace. NewSelectorCodec accepts the same WithClientCodec / WithCodecPrefix options as NewCodec.

ForNamespace (lower-level)

As a lower-level alternative, sel.ForNamespace(ns) yields a scoped Provider you can hand to a per-namespace NewCodec, registering one codec per namespace:

// Each namespace gets a scoped Provider.
codecA, _ := crypto.NewCodec(codec.Default(), sel.ForNamespace("tenant-a"))
codecB, _ := crypto.NewCodec(codec.Default(), sel.ForNamespace("tenant-b"))

AddProvider / RemoveProvider / RemoveAndClose manage registrations at runtime.

Encrypted Cache

EncryptedCache wraps any config.Cache (Redis, in-memory, …) so that cached values are stored as authenticated ciphertext. The full payload — data bytes, codec name, config type, entry ID, and metadata — is encrypted by the supplied Provider before the entry reaches the backing store. Only ExpiresAt is forwarded to the outer wrapper so the inner cache (e.g. Redis) can enforce TTL-based eviction without decrypting.

import (
    crypto "github.com/rbaliyan/config-crypto"
    configredis "github.com/rbaliyan/config/redis"
)

provider, _ := crypto.NewProvider(keyBytes, "cache-key-v1")

encCache, _ := crypto.NewEncryptedCache(
    configredis.NewCache(rdb, configredis.WithCacheTTL(5*time.Minute)),
    provider,
)

mgr, _ := config.New(
    config.WithStore(remoteStore),
    config.WithCache(encCache),
)

Key rotation: when the Provider's active key changes, previously cached ciphertext cannot be decrypted. Those entries are returned as config.ErrNotFound, causing the manager to re-fetch from the backing store and re-cache with the new key. No operator intervention is required — the cache re-warms transparently on the next access.

Error handling: cryptographic failures (wrong key, tampered ciphertext, unknown schema version) are treated as cache misses so the application keeps running. Provider operational failures (e.g. ErrProviderClosed) are propagated as real errors and not silently swallowed.

Namespace-aware encryption: combine with NamespaceSelector to use different keys per namespace:

sel, _ := crypto.NewNamespaceSelector(
    crypto.WithNamespaceProvider("tenant-a", providerA),
    crypto.WithNamespaceProvider("tenant-b", providerB),
    crypto.WithFallbackProvider(defaultProvider),
)
encCache, _ := crypto.NewEncryptedCache(innerCache, sel)

Session cache: crypto.NewSessionCache(capacity) returns an EncryptedCache backed by an in-memory LRU and a fresh random AES-256 key generated at call time. The key never leaves process memory and is discarded on restart, so cached values cannot be read by any other process or after a restart. Pass 0 for the default capacity (10000 entries). This is the recommended in-process cache for services handling secrets — it provides at-rest protection in memory with no external KMS or Vault wiring:

cache, _ := crypto.NewSessionCache(0) // default capacity (10000 entries)
mgr, _ := config.New(
    config.WithStore(remoteStore),
    config.WithCache(cache),
)

KMS Providers

All KMS providers are packages within the github.com/rbaliyan/config-crypto module — a single go get github.com/rbaliyan/config-crypto imports them all. Each provider returns a crypto.KeyRingProvider; internally it fetches key material from the backend and constructs a ring provider.

Each provider accepts a narrow Client interface using only stdlib types — you supply a one-method wrapper around your chosen SDK. This keeps the provider packages free of SDK dependencies.

go get github.com/rbaliyan/config-crypto
AWS KMS
import "github.com/rbaliyan/config-crypto/awskms"

// awskms.Client requires: Decrypt(ctx, keyID string, ciphertext []byte) ([]byte, error)
type myAWSClient struct{ sdk *kms.Client }
func (c *myAWSClient) Decrypt(ctx context.Context, keyID string, ciphertext []byte) ([]byte, error) {
    out, err := c.sdk.Decrypt(ctx, &kms.DecryptInput{CiphertextBlob: ciphertext, KeyId: aws.String(keyID)})
    if err != nil {
        return nil, err
    }
    return out.Plaintext, nil
}

cfg, _ := awsconfig.LoadDefaultConfig(ctx)
provider, _ := awskms.New(ctx, &myAWSClient{sdk: kms.NewFromConfig(cfg)},
    // Let KMS derive the key ID from the ciphertext context.
    awskms.WithEncryptedKey(encryptedKeyBytes, "key-1"),
    // ...or pin a specific KMS key ARN / alias:
    // awskms.WithEncryptedKeyForKMSKey(encryptedKeyBytes, "key-1", "arn:aws:kms:..."),
)
defer provider.Close()
encJSON, _ := crypto.NewCodec(codec.Default(), provider)
GCP Cloud KMS
import "github.com/rbaliyan/config-crypto/gcpkms"

// gcpkms.Client requires: Decrypt(ctx, resourceName string, ciphertext []byte) ([]byte, error)
type myGCPClient struct{ sdk *kms.KeyManagementClient }
func (c *myGCPClient) Decrypt(ctx context.Context, resourceName string, ciphertext []byte) ([]byte, error) {
    resp, err := c.sdk.Decrypt(ctx, &kmspb.DecryptRequest{
        Name:       resourceName,
        Ciphertext: ciphertext,
    })
    if err != nil {
        return nil, err
    }
    return resp.Plaintext, nil
}

kmsSDK, _ := kms.NewKeyManagementClient(ctx)
provider, _ := gcpkms.New(ctx, &myGCPClient{sdk: kmsSDK},
    gcpkms.WithEncryptedKey(encryptedBytes, "key-1", "projects/p/locations/l/keyRings/r/cryptoKeys/k"),
)
defer provider.Close()
Azure Key Vault
import "github.com/rbaliyan/config-crypto/azurekv"

// azurekv.Client requires: UnwrapKey(ctx, keyName, keyVersion, algorithm string, ciphertext []byte) ([]byte, error)
type myAzureClient struct{ sdk *azkeys.Client }
func (c *myAzureClient) UnwrapKey(ctx context.Context, keyName, keyVersion, algorithm string, ciphertext []byte) ([]byte, error) {
    resp, err := c.sdk.UnwrapKey(ctx, keyName, keyVersion, azkeys.KeyOperationParameters{
        Algorithm: (*azkeys.JSONWebKeyEncryptionAlgorithm)(&algorithm),
        Value:     ciphertext,
    }, nil)
    if err != nil {
        return nil, err
    }
    return resp.Result, nil
}

cred, _ := azidentity.NewDefaultAzureCredential(nil)
sdk, _ := azkeys.NewClient("https://my-vault.vault.azure.net/", cred, nil)
provider, _ := azurekv.New(ctx, &myAzureClient{sdk: sdk},
    azurekv.WithWrappedKey(wrappedBytes, "key-1", "my-key", "v1"),
)
defer provider.Close()
HashiCorp Vault (KV v2)

Backed by the Vault KV v2 secrets engine. Each secret version becomes one key entry; the KV version number is used as the rank for NeedsReencryption ordering.

import "github.com/rbaliyan/config-crypto/vault"

// vault.Client requires KVMetadata + KVGet (see package doc for full interface).
ring, _ := vault.New(ctx, client, "secret", "config-crypto/keys")
defer ring.Close()

// Optional: start a background goroutine that polls for new key versions.
stop, _ := vault.Poll(ctx, client, ring, "secret", "config-crypto/keys", 30*time.Second)
defer stop()

Note: The previous Transit-based provider has been removed. Transit-wrapped ciphertext is not portable across KMS backends; this library favours raw-bytes distribution so the database of encrypted values stays portable for its full lifetime.

GPG
import "github.com/rbaliyan/config-crypto/gpg"

// gpg.Client requires: Decrypt(ctx, ciphertext []byte) ([]byte, error)
encryptedKey, _ := os.ReadFile("keys/current.key.gpg")
client := gpg.NewExecClient() // uses system gpg binary
provider, _ := gpg.New(ctx, client,
    gpg.WithEncryptedKey(encryptedKey, "key-1"),
)
defer provider.Close()

Suited for non-server deployments where keys are distributed as GPG-encrypted files alongside the application.

All KMS providers decrypt their key material at construction time, copy it into a local ring provider, and discard the client. For live rotation without restart, use the generic crypto.Poll helper with the provider-specific NewPoller (awskms.NewPoller, gcpkms.NewPoller, azurekv.NewPoller), use vault.Poll for HashiCorp Vault, or call ring.AddKey/ring.SetCurrentKey manually when new key material is available.

Background Key Rotation

Two helpers drive runtime key rotation without restarting the process:

  • crypto.Poll is a generic helper that periodically invokes a user-supplied FetchFn to discover new key versions and promote the current key. FetchFn returns a slice of crypto.KeyVersion (ID, Bytes, Rank, IsCurrent); versions already in the ring are skipped. The initial fetch is fail-fast; per-version failures are retried up to WithPollMaxRetries (default 5) and then permanently skipped for the lifetime of the goroutine.

  • vault.Poll is a thin specialisation for the Vault KV v2 engine — it sources key versions directly from client.KVMetadata / client.KVGet without requiring the caller to write a FetchFn.

The AWS, GCP, and Azure provider packages ship a NewPoller(...) helper that returns a crypto.FetchFn. Pair it with crypto.Poll:

import (
    crypto "github.com/rbaliyan/config-crypto"
    "github.com/rbaliyan/config-crypto/awskms"
)

ring, _ := awskms.New(ctx, kmsClient,
    awskms.WithEncryptedKey(v1Ciphertext, "key-v1"),
)

// Build a FetchFn from ListKeyVersions + pre-encrypted ciphertexts.
fetch := awskms.NewPoller(listingClient, "arn:aws:kms:...", []awskms.KeyMaterialEntry{
    {VersionID: "abc-1", Ciphertext: v1Ciphertext, ID: "key-v1", Rank: 1},
    {VersionID: "abc-2", Ciphertext: v2Ciphertext, ID: "key-v2", Rank: 2},
})

stop, _ := crypto.Poll(ctx, ring, 30*time.Second, fetch,
    crypto.WithPollErrorHandler(func(err error) { log.Println(err) }),
)
defer stop()

Automated Re-encryption (rotation)

After the current key changes, existing ciphertext remains readable by any ring that still holds the older key (the key ID is embedded in the header), but it is not silently re-encrypted with the new key. The optional rotation sub-package drives that migration in the background:

import "github.com/rbaliyan/config-crypto/rotation"

orch, _ := rotation.NewOrchestrator(ring, store, encJSON,
    rotation.WithNamespaces("production", "staging"),
    rotation.WithScanInterval(1*time.Hour),
    rotation.WithConcurrency(4),
    rotation.WithErrorHandler(func(ns, key string, err error) {
        log.Printf("re-encrypt %s/%s: %v", ns, key, err)
    }),
)

// Start the background scan loop.
stop, _ := orch.Start(ctx)
defer stop()

// Or trigger a single pass over a namespace synchronously.
n, _ := orch.ReencryptNamespace(ctx, "production")

Each scan lists values in each configured namespace, filters to those whose codec starts with encrypted:, and asks the ring (NeedsReencryption) whether the ciphertext was written with an older key rank. Stale values are decrypted and re-encrypted with the current key, then written back via store.Set. Start may only be called once per Orchestrator; the returned stop function cancels the scan loop and blocks until the goroutine exits.

HealthCheck

HealthCheck(ctx) returns nil when the provider is usable. Its semantics depend on the backing provider:

  • Static providers (NewProvider, NewKeyRingProvider, and all KMS wrappers) report liveness only — nil unless Close has been called. They do not contact any backend.
  • NamespaceSelector: sel.ForNamespace(ns).HealthCheck(ctx) delegates to the registered provider for that namespace (or returns ErrNoProviderForNamespace).

Observability

The otel sub-package wraps any Provider with OpenTelemetry tracing and metrics. Both are opt-in (disabled by default):

import cryptootel "github.com/rbaliyan/config-crypto/otel"

instrumented, _ := cryptootel.WrapProvider(provider,
    cryptootel.WithTracesEnabled(true),
    cryptootel.WithMetricsEnabled(true),
)
encJSON, _ := crypto.NewCodec(codec.Default(), instrumented)

WrapProvider returns an *InstrumentedProvider (also a Provider); Unwrap() returns the wrapped provider. When tracing is enabled it emits spans for Connect, Encrypt, Decrypt, and HealthCheck. When metrics are enabled it records:

Metric Type Description
crypto.operations.total counter Total provider operations (attributes: operation, provider)
crypto.errors.total counter Operation errors (adds an error_type attribute)
crypto.operation.duration histogram (seconds) Operation latency

Use WithTracerName / WithMeterName or WithTracer / WithMeter to override the names or supply explicit tracer/meter instances.

Codec Options

Both NewCodec and NewSelectorCodec accept CodecOption values that adjust the registered codec name:

  • WithClientCodec() prefixes the name with client: (yielding client:encrypted:<inner>) so config-server treats it as a client-managed codec and passes the bytes through without attempting to decode them.
  • WithCodecPrefix(prefix) adds a custom prefix (<prefix>:encrypted:<inner>) for cases that need something other than the standard client:.

Binary Format

The encrypted payload is self-describing:

[2B magic "EC"]
[1B version = 0x02] [1B format = 0x01] [1B algorithm = 0x01 AES-256-GCM]
[1B key_id_len] [NB key_id UTF-8]
[12B dek_nonce] [2B encrypted_dek_len] [MB encrypted_dek]
[12B data_nonce] [remaining: ciphertext + 16B GCM tag]

The format byte is reserved for future wrapping schemes (e.g. post-quantum KEMs). encrypted_dek is variable-length (currently always 48B for AES-256-GCM wrap: 32B DEK + 16B tag). Overhead is ~49 + len(key_id) bytes of header plus 16B GCM tag on the payload.

v1 compatibility: Ciphertext produced by releases before the v2 format landed is still decryptable. The reader sniffs the version byte and dispatches to the v1 or v2 parser. Encrypt always writes v2.

Security Considerations

KEK material is held inside memguard encrypted Enclaves: keys are stored encrypted-at-rest in mlock'd memory (kept out of swap and invisible to heap scans between uses) and are only opened transiently as plaintext for the duration of a single Encrypt/Decrypt/wrap operation, then immediately destroyed. Key material is also defensively copied and zeroed when the Provider is closed (via Close(), DEK clearing, KMS provider intermediate buffers). However, Go's crypto/aes expands key bytes into an internal round-key schedule at cipher creation time and does not expose a way to zero that schedule. This means copies of key material may persist in heap memory until garbage-collected, even after Close() is called. This is a known limitation of the Go standard library and applies to all Go programs using crypto/aes. For threat models requiring guaranteed key erasure, use a hardware security module (HSM).

Known Gaps

  • GPG provider has no background poller. awskms, gcpkms, azurekv, and vault all offer a poll helper that plugs into crypto.Poll; the GPG provider does not (it is designed for file-based key distribution). Callers who want live rotation with GPG must obtain a KeyRingProvider via NewKeyRingProvider and drive AddKey / SetCurrentKey themselves when new key files arrive.

Documentation

Overview

Package crypto provides an encryption codec for the rbaliyan/config library. It implements AES-256-GCM envelope encryption: each config value is encrypted with a freshly generated Data Encryption Key (DEK) that is itself wrapped by a Key Encryption Key (KEK) held by a pluggable Provider.

The package is organised around the following building blocks:

  • Codec wraps an inner codec (json, yaml, toml, …) with transparent encryption. Register the codec with config's codec registry and configuration values are encrypted on Set and decrypted on Get.
  • Provider abstracts KEK ownership. Built-ins: NewProvider (static single-key), NewKeyRingProvider (multi-key with live rotation), plus KMS-backed providers in the awskms, gcpkms, azurekv, vault, and gpg sub-packages.
  • NamespaceSelector routes Encrypt/Decrypt to different providers based on the config namespace — useful for multi-tenant deployments where each tenant holds its own KEK.
  • SelectorCodec combines a NamespaceSelector with an inner codec so a single codec registration covers all namespaces; the namespace is read from the context via WithNamespace.
  • Poll drives backend-agnostic runtime key rotation against any KeyRingProvider. The AWS/GCP/Azure sub-packages ship a NewPoller helper that returns a FetchFn ready to hand to Poll; the vault sub-package has its own vault.Poll specialisation.
  • EncryptedCache wraps any config.Cache (Redis, memory, …) so that cached values are stored as authenticated ciphertext. The full payload — data bytes, codec name, type, and metadata — is encrypted by the supplied Provider before the entry reaches the backing store.

For re-encrypting at-rest ciphertext after the current KEK changes, see the rotation sub-package. The otel sub-package provides optional OpenTelemetry tracing and metrics via WrapProvider.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrKeyNotFound is returned when a key ID is not found in the provider.
	ErrKeyNotFound = errors.New("crypto: key not found")

	// ErrInvalidKeySize is returned when a key is not 32 bytes (AES-256).
	ErrInvalidKeySize = errors.New("crypto: invalid key size, must be 32 bytes")

	// ErrInvalidFormat is returned when encrypted data has an invalid format.
	ErrInvalidFormat = errors.New("crypto: invalid encrypted data format")

	// ErrUnsupportedFormat is returned when the format byte in a v2 header is not recognised.
	ErrUnsupportedFormat = errors.New("crypto: unsupported encrypted format")

	// ErrDecryptionFailed is returned when decryption fails (wrong key, tampered data).
	ErrDecryptionFailed = errors.New("crypto: decryption failed")

	// ErrInvalidKeyID is returned when a key ID is empty or invalid.
	ErrInvalidKeyID = errors.New("crypto: invalid key ID")

	// ErrProviderClosed is returned when a provider has been closed.
	ErrProviderClosed = errors.New("crypto: provider has been closed")

	// ErrRemoveCurrentKey is returned when attempting to remove the active encryption key.
	ErrRemoveCurrentKey = errors.New("crypto: cannot remove current key")

	// ErrNoProviderForNamespace is returned when a namespace has no registered provider and no fallback is set.
	ErrNoProviderForNamespace = errors.New("crypto: no key provider for namespace")

	// ErrDuplicateKeyID is returned from AddKey when the key ID is already present in the ring.
	ErrDuplicateKeyID = errors.New("crypto: duplicate key ID")
)
View Source
var NamespaceContextKey = namespaceKey{}

NamespaceContextKey is the context key used to pass the config namespace into SelectorCodec.Encode and SelectorCodec.Decode. Set it with:

ctx = crypto.WithNamespace(ctx, "payments")

Functions

func IsDecryptionFailed

func IsDecryptionFailed(err error) bool

IsDecryptionFailed returns true if the error is or wraps ErrDecryptionFailed.

func IsDuplicateKeyID added in v0.5.1

func IsDuplicateKeyID(err error) bool

IsDuplicateKeyID returns true if the error is or wraps ErrDuplicateKeyID.

func IsInvalidFormat

func IsInvalidFormat(err error) bool

IsInvalidFormat returns true if the error is or wraps ErrInvalidFormat.

func IsInvalidKeyID

func IsInvalidKeyID(err error) bool

IsInvalidKeyID returns true if the error is or wraps ErrInvalidKeyID.

func IsInvalidKeySize

func IsInvalidKeySize(err error) bool

IsInvalidKeySize returns true if the error is or wraps ErrInvalidKeySize.

func IsKeyNotFound

func IsKeyNotFound(err error) bool

IsKeyNotFound returns true if the error is or wraps ErrKeyNotFound.

func IsNoProviderForNamespace added in v0.3.0

func IsNoProviderForNamespace(err error) bool

IsNoProviderForNamespace returns true if the error is or wraps ErrNoProviderForNamespace.

func IsProviderClosed added in v0.3.0

func IsProviderClosed(err error) bool

IsProviderClosed returns true if the error is or wraps ErrProviderClosed.

func IsRemoveCurrentKey added in v0.2.3

func IsRemoveCurrentKey(err error) bool

IsRemoveCurrentKey returns true if the error is or wraps ErrRemoveCurrentKey.

func IsUnsupportedFormat added in v0.3.0

func IsUnsupportedFormat(err error) bool

IsUnsupportedFormat returns true if the error is or wraps ErrUnsupportedFormat.

func NamespaceFromContext added in v0.5.1

func NamespaceFromContext(ctx context.Context) string

NamespaceFromContext extracts the namespace previously set by WithNamespace. Returns an empty string if no namespace is present.

func Poll added in v0.5.1

func Poll(ctx context.Context, ring KeyRingProvider, interval time.Duration, fetchFn FetchFn, opts ...PollOption) (func(), error)

Poll starts a background goroutine that calls fetchFn at interval, adding any newly-seen key versions to ring and promoting the current key.

An initial fetch is performed before the ticker starts; if it fails, Poll returns an error immediately (fail-fast at startup).

The returned stop function cancels the goroutine and blocks until it exits. Callers should defer stop() after a successful Poll call.

func WithNamespace added in v0.5.1

func WithNamespace(ctx context.Context, namespace string) context.Context

WithNamespace returns a new context carrying the given namespace. Used to tell SelectorCodec which provider to route to during Encode/Decode.

Types

type Codec

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

Codec wraps an inner codec with envelope encryption. On Encode, the inner codec serializes the value, then the result is encrypted. On Decode, the data is decrypted, then the inner codec deserializes the plaintext.

Codec is safe for concurrent use if the underlying Provider and inner codec are safe for concurrent use.

func NewCodec

func NewCodec(inner codec.Codec, p Provider, opts ...CodecOption) (*Codec, error)

NewCodec creates an encrypting codec that wraps the given inner codec. The codec name is "encrypted:<inner>", e.g. "encrypted:json". With WithClientCodec the name becomes "client:encrypted:<inner>". Returns an error if inner or provider is nil.

Example
package main

import (
	"context"
	"fmt"

	crypto "github.com/rbaliyan/config-crypto"

	jsoncodec "github.com/rbaliyan/config/codec/json"
)

func main() {
	ctx := context.Background()

	// 32-byte key for AES-256.
	key := make([]byte, 32)
	for i := range key {
		key[i] = byte(i)
	}

	provider, err := crypto.NewProvider(key, "key-1")
	if err != nil {
		panic(err)
	}
	defer provider.Close()

	encJSON, err := crypto.NewCodec(jsoncodec.New(), provider)
	if err != nil {
		panic(err)
	}
	fmt.Println("Codec name:", encJSON.Name())

	// Decode round-trip.
	data, err := encJSON.Encode(ctx, "my-secret")
	if err != nil {
		panic(err)
	}

	var result string
	if err := encJSON.Decode(ctx, data, &result); err != nil {
		panic(err)
	}
	fmt.Println("Decrypted:", result)

}
Output:
Codec name: encrypted:json
Decrypted: my-secret
Example (WithConfig)
package main

import (
	"fmt"

	crypto "github.com/rbaliyan/config-crypto"
	"github.com/rbaliyan/config/codec"

	jsoncodec "github.com/rbaliyan/config/codec/json"
)

func main() {
	key := make([]byte, 32)
	for i := range key {
		key[i] = byte(i)
	}

	provider, err := crypto.NewProvider(key, "key-1")
	if err != nil {
		panic(err)
	}
	defer provider.Close()

	encJSON, err := crypto.NewCodec(jsoncodec.New(), provider)
	if err != nil {
		panic(err)
	}
	if err := codec.Register(encJSON); err != nil {
		panic(err)
	}

	resolved := codec.Get("encrypted:json")
	fmt.Println("Resolved:", resolved.Name())

}
Output:
Resolved: encrypted:json

func (*Codec) Decode

func (c *Codec) Decode(ctx context.Context, data []byte, v any) error

Decode decrypts the data, then deserializes the plaintext using the inner codec.

func (*Codec) Encode

func (c *Codec) Encode(ctx context.Context, v any) ([]byte, error)

Encode serializes the value using the inner codec, then encrypts the result.

func (*Codec) Name

func (c *Codec) Name() string

Name returns the codec name, e.g. "encrypted:json".

func (*Codec) Reverse added in v0.2.3

func (c *Codec) Reverse(ctx context.Context, data []byte) ([]byte, error)

Reverse decrypts the raw bytes, recovering the original plaintext. This implements codec.Transformer for use with codec.NewChain.

func (*Codec) Transform added in v0.2.3

func (c *Codec) Transform(ctx context.Context, data []byte) ([]byte, error)

Transform encrypts the raw bytes using envelope encryption. This implements codec.Transformer for use with codec.NewChain.

type CodecOption added in v0.3.0

type CodecOption func(*codecOptions)

CodecOption configures NewCodec behavior.

func WithClientCodec added in v0.2.3

func WithClientCodec() CodecOption

WithClientCodec prefixes the codec name with "client:" so the config-server recognises it as a client-managed codec and passes the bytes through without attempting to decode them. This is shorthand for WithCodecPrefix("client").

func WithCodecPrefix added in v0.2.3

func WithCodecPrefix(prefix string) CodecOption

WithCodecPrefix adds a custom prefix to the codec name. The resulting name is "<prefix>:encrypted:<inner>". Use this when you need a prefix other than the standard "client:".

type EncryptedCache added in v0.5.1

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

EncryptedCache wraps any config.Cache with transparent encryption using the supplied Provider. The full value payload (data bytes, codec name, type, entry ID, and metadata) is encrypted before being written to the inner cache, and decrypted on retrieval. This ensures credentials and other sensitive values are never stored in plaintext in external caches such as Redis, regardless of whether the backing store uses encryption at rest.

EncryptedCache is safe for concurrent use by multiple goroutines.

Error semantics:

  • Cache misses, expired entries, and cryptographic failures (wrong key, tampered ciphertext, corrupt payload, unknown schema version) return config.ErrNotFound so the manager transparently re-fetches from the store.
  • Entries not written by EncryptedCache (codec sentinel mismatch) are also returned as config.ErrNotFound.
  • Provider operational failures (e.g. ErrProviderClosed) are propagated as real errors so callers can surface and handle them.

Example:

provider, _ := crypto.NewProvider(keyBytes, "cache-key")
encCache, _ := crypto.NewEncryptedCache(
    configredis.NewCache(rdb, configredis.WithCacheTTL(5*time.Minute)),
    provider,
)
mgr, _ := config.New(
    config.WithStore(remoteStore),
    config.WithCache(encCache),
)

func NewEncryptedCache added in v0.5.1

func NewEncryptedCache(inner config.Cache, p Provider) (*EncryptedCache, error)

NewEncryptedCache returns a cache that encrypts all values before writing them to inner and decrypts on retrieval. Returns an error if inner or p is nil.

Example
package main

import (
	"context"
	"fmt"
	"sync"

	"github.com/rbaliyan/config"
	crypto "github.com/rbaliyan/config-crypto"
)

// mapCache is a minimal config.Cache used in examples.
type mapCache struct {
	mu   sync.RWMutex
	data map[string]config.Value
}

func newMapCache() *mapCache { return &mapCache{data: make(map[string]config.Value)} }

func (m *mapCache) Set(_ context.Context, ns, key string, v config.Value) error {
	m.mu.Lock()
	m.data[ns+"/"+key] = v
	m.mu.Unlock()
	return nil
}

func (m *mapCache) Get(_ context.Context, ns, key string) (config.Value, error) {
	m.mu.RLock()
	v, ok := m.data[ns+"/"+key]
	m.mu.RUnlock()
	if !ok {
		return nil, config.ErrNotFound
	}
	return v, nil
}

func (m *mapCache) Delete(_ context.Context, ns, key string) error {
	m.mu.Lock()
	delete(m.data, ns+"/"+key)
	m.mu.Unlock()
	return nil
}

func (m *mapCache) Stats() config.CacheStats { return config.CacheStats{} }

func main() {
	ctx := context.Background()

	key := make([]byte, 32)
	for i := range key {
		key[i] = byte(i)
	}

	provider, err := crypto.NewProvider(key, "cache-key-v1")
	if err != nil {
		panic(err)
	}
	defer provider.Close()

	inner := newMapCache()
	encCache, err := crypto.NewEncryptedCache(inner, provider)
	if err != nil {
		panic(err)
	}

	// Store an encrypted value.
	val := config.NewValue("my-secret", config.WithValueType(config.TypeString))
	if err := encCache.Set(ctx, "prod", "db/password", val); err != nil {
		panic(err)
	}

	// The inner cache holds ciphertext — not the original string.
	raw, _ := inner.Get(ctx, "prod", "db/password")
	fmt.Println("Inner codec:", raw.Codec())

	// Retrieve and decrypt.
	got, err := encCache.Get(ctx, "prod", "db/password")
	if err != nil {
		panic(err)
	}
	s, _ := got.String()
	fmt.Println("Decrypted:", s)

}
Output:
Inner codec: crypto:cache
Decrypted: my-secret

func NewSessionCache added in v0.5.2

func NewSessionCache(capacity int) (*EncryptedCache, error)

NewSessionCache returns an EncryptedCache backed by an in-memory LRU and a fresh random AES-256-GCM key generated at call time. The key never leaves process memory and is discarded on restart, so cached values cannot be read by any other process or after a restart — even if they share the same backing store.

capacity is the maximum number of entries (0 uses the config default of 10000).

This is the recommended in-process cache for services that handle secrets or other sensitive configuration values. It provides at-rest protection in memory without requiring an external key management system or Vault integration.

cache, err := crypto.NewSessionCache(0)  // default capacity (10000 entries)
mgr, err := config.New(
    config.WithStore(remoteStore),
    config.WithCache(cache),
)

func (*EncryptedCache) Delete added in v0.5.1

func (c *EncryptedCache) Delete(ctx context.Context, namespace, key string) error

Delete removes a cache entry from the inner cache.

func (*EncryptedCache) Get added in v0.5.1

func (c *EncryptedCache) Get(ctx context.Context, namespace, key string) (config.Value, error)

Get retrieves a value from the inner cache and decrypts it.

Returns config.ErrNotFound for:

  • Cache misses and expired entries.
  • Cryptographic failures (wrong key after rotation, tampered ciphertext, invalid or unsupported ciphertext format) — the manager re-fetches from the store and the fresh value is re-encrypted with the current key.
  • Corrupt payload (unknown schema version, out-of-range Type field, malformed JSON) — same fallback behaviour.

Returns a real error (not ErrNotFound) for provider operational failures such as ErrProviderClosed so callers can surface them rather than silently falling through to a potentially unavailable backend store.

func (*EncryptedCache) Set added in v0.5.1

func (c *EncryptedCache) Set(ctx context.Context, namespace, key string, value config.Value) error

Set encrypts the value's full payload and stores the ciphertext in the inner cache. Only ExpiresAt is forwarded to the outer wrapper so the inner cache (e.g. Redis) can enforce TTL-based eviction without decrypting. All other metadata — including Version, CreatedAt, UpdatedAt, and EntryID — is kept exclusively inside the ciphertext to avoid leaking operational metadata in Redis plaintext.

func (*EncryptedCache) Stats added in v0.5.1

func (c *EncryptedCache) Stats() config.CacheStats

Stats returns cache statistics. Hits and Misses reflect post-decryption outcomes measured by EncryptedCache; Size, Capacity, and Evictions are sourced from the inner cache.

A sudden miss-spike without a corresponding hit drop typically indicates key rotation: old ciphertext cannot be decrypted by the new provider, so each cached entry is re-fetched from the backing store and re-encrypted as it is accessed. This is expected behaviour during and shortly after a key rotation.

type FetchFn added in v0.5.1

type FetchFn func(ctx context.Context) ([]KeyVersion, error)

FetchFn retrieves the current set of key versions from a KMS. It must be idempotent: returning the same version multiple times is safe. Returning versions already known to the ring is safe — Poll skips them.

type KeyRingProvider added in v0.5.0

type KeyRingProvider interface {
	Provider

	// AddKey adds a key that can be used for decryption or set as the current
	// key. The keyBytes must be 32 bytes for AES-256 and id must not be empty.
	// rank is the KV store version number for this key; it is used by
	// NeedsReencryption to establish ordering. Pass 0 when the backing store
	// does not provide version ordering. Returns ErrDuplicateKeyID if the ID
	// already exists.
	AddKey(keyBytes []byte, id string, rank uint64) error

	// SetCurrentKey switches the active encryption key to the given ID.
	// The key must have been previously added via the constructor or AddKey.
	SetCurrentKey(id string) error

	// RemoveKey removes a key by ID. The current key cannot be removed.
	RemoveKey(id string) error

	// CurrentKeyID returns the ID of the key currently used for encryption.
	CurrentKeyID() string

	// NeedsReencryption reports whether ciphertext was encrypted with a key
	// that is older than the current key, based on the rank recorded when each
	// key was added. It returns true only when the current key has a strictly
	// higher rank than the key embedded in the ciphertext header.
	//
	// It returns false (not true) when the ciphertext key is unknown to this
	// provider, since ordering cannot be determined in that case.
	// It returns an error only if the ciphertext header cannot be parsed.
	NeedsReencryption(ciphertext []byte) (bool, error)
}

KeyRingProvider is a mutable Provider that supports runtime key rotation. Keys can be added, removed, and the current key switched at any time. End users usually get a KeyRingProvider from a KMS package; this interface is exported so KMS packages can build on top of it.

KeyRingProvider is safe for concurrent use.

func NewKeyRingProvider added in v0.5.0

func NewKeyRingProvider(initialBytes []byte, id string, rank uint64) (KeyRingProvider, error)

NewKeyRingProvider creates a mutable Provider with the given initial key. The keyBytes must be 32 bytes for AES-256. The id identifies this key. rank is the KV store version number for this key (e.g. the Vault KV version integer cast to uint64); it is used by NeedsReencryption to determine whether a given ciphertext was encrypted with an older key. Use 0 when the backing store does not provide version ordering. Key bytes are copied into a memguard Enclave; the caller should zero the original slice after construction as a defence-in-depth measure.

Example (Rotation)
package main

import (
	"context"
	"fmt"

	crypto "github.com/rbaliyan/config-crypto"

	jsoncodec "github.com/rbaliyan/config/codec/json"
)

func main() {
	ctx := context.Background()

	oldKey := make([]byte, 32)
	for i := range oldKey {
		oldKey[i] = byte(i)
	}

	// Encrypt with the old key.
	oldP, err := crypto.NewProvider(oldKey, "key-v1")
	if err != nil {
		panic(err)
	}
	defer oldP.Close()
	oldCodec, err := crypto.NewCodec(jsoncodec.New(), oldP)
	if err != nil {
		panic(err)
	}
	encrypted, err := oldCodec.Encode(ctx, "secret-data")
	if err != nil {
		panic(err)
	}

	// Rotate: KeyRingProvider has both keys; current is v2.
	newKey := make([]byte, 32)
	for i := range newKey {
		newKey[i] = byte(i + 100)
	}
	ring, err := crypto.NewKeyRingProvider(newKey, "key-v2", 2)
	if err != nil {
		panic(err)
	}
	defer ring.Close()
	if err := ring.AddKey(oldKey, "key-v1", 1); err != nil {
		panic(err)
	}
	newCodec, err := crypto.NewCodec(jsoncodec.New(), ring)
	if err != nil {
		panic(err)
	}

	var result string
	if err := newCodec.Decode(ctx, encrypted, &result); err != nil {
		panic(err)
	}
	fmt.Println("Decrypted with rotated provider:", result)

}
Output:
Decrypted with rotated provider: secret-data

type KeyVersion added in v0.5.1

type KeyVersion struct {
	ID        string // stable identifier (used as key ID in encrypted headers)
	Bytes     []byte // 32-byte AES-256 key material
	Rank      uint64 // ordering rank for NeedsReencryption; higher = newer
	IsCurrent bool   // true if this version should be the active encryption key
}

KeyVersion is a single key version returned by a FetchFn.

type NamespaceOption added in v0.3.0

type NamespaceOption func(*namespaceOptions)

NamespaceOption configures a NamespaceSelector.

func WithFallbackProvider added in v0.3.0

func WithFallbackProvider(provider Provider) NamespaceOption

WithFallbackProvider sets the fallback Provider used when a namespace has no dedicated provider.

func WithNamespaceProvider added in v0.3.0

func WithNamespaceProvider(namespace string, provider Provider) NamespaceOption

WithNamespaceProvider registers a Provider for the given namespace. Nil providers are ignored.

type NamespaceSelector added in v0.3.0

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

NamespaceSelector routes Encrypt/Decrypt to namespace-specific Providers. It holds a map of namespace to Provider plus an optional fallback provider. It is safe for concurrent use; providers can be added or removed at runtime.

In multi-tenant scenarios, use ForNamespace to obtain a namespace-scoped Provider; do not invoke Encrypt or Decrypt directly on the selector — those methods are not exposed because the selector itself does not know which namespace a payload belongs to.

func NewNamespaceSelector added in v0.3.0

func NewNamespaceSelector(opts ...NamespaceOption) (*NamespaceSelector, error)

NewNamespaceSelector creates a NamespaceSelector with the given options.

func (*NamespaceSelector) AddProvider added in v0.3.0

func (s *NamespaceSelector) AddProvider(namespace string, provider Provider) error

AddProvider registers a Provider for the given namespace at runtime. Returns an error if provider is nil or the selector has been closed.

func (*NamespaceSelector) Close added in v0.3.0

func (s *NamespaceSelector) Close() error

Close closes every Provider held by the selector (namespace-scoped and fallback). Errors from individual closes are joined via errors.Join. Safe to call multiple times; subsequent calls are no-ops.

func (*NamespaceSelector) ForNamespace added in v0.3.0

func (s *NamespaceSelector) ForNamespace(namespace string) Provider

ForNamespace returns a Provider scoped to the given namespace. If the namespace has a registered provider, that provider is used. Otherwise the fallback provider is used. If neither exists, the returned Provider returns ErrNoProviderForNamespace on Encrypt/Decrypt. The returned Provider is safe for concurrent use and reflects runtime changes to the selector (providers added/removed after ForNamespace).

Close on the returned Provider is a no-op; close the underlying providers or the selector itself.

func (*NamespaceSelector) RemoveAndClose added in v0.3.0

func (s *NamespaceSelector) RemoveAndClose(namespace string) error

RemoveAndClose removes the Provider for the given namespace and calls Close on it. Returns the Close error (or nil if the namespace had no provider). Use this when the selector owns the provider's lifecycle.

func (*NamespaceSelector) RemoveProvider added in v0.3.0

func (s *NamespaceSelector) RemoveProvider(namespace string)

RemoveProvider removes the Provider for the given namespace. The removed provider is not closed; the caller retains ownership and must call Close on it. Use RemoveAndClose if the selector should close the provider on the caller's behalf.

type PollOption added in v0.5.1

type PollOption func(*pollOptions)

PollOption configures Poll.

func WithPollErrorHandler added in v0.5.1

func WithPollErrorHandler(fn func(error)) PollOption

WithPollErrorHandler sets a callback for poll errors (fetch failures, AddKey failures). The callback runs on the polling goroutine and must not block. If unset, errors are logged via slog.

func WithPollMaxRetries added in v0.5.1

func WithPollMaxRetries(n int) PollOption

WithPollMaxRetries sets the per-version retry cap. After this many failures, the version is permanently skipped for the lifetime of the goroutine. Default is 5.

type Provider added in v0.3.0

type Provider interface {
	// Name returns a short human-readable identifier for this provider.
	// Used for logging and observability; need not be globally unique.
	Name() string

	// Connect initialises any remote connection the provider needs.
	// It is the caller's responsibility to call Connect before the first
	// Encrypt or Decrypt. Implementations backed by in-memory keys treat
	// this as a no-op; remote-key-wrapping implementations use it to
	// establish SDK sessions or verify credentials.
	Connect(ctx context.Context) error

	// Encrypt encrypts plaintext using envelope encryption.
	Encrypt(ctx context.Context, plaintext []byte) ([]byte, error)

	// Decrypt decrypts ciphertext that was produced by Encrypt.
	Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)

	// HealthCheck reports whether the provider is currently usable. It
	// returns nil for a healthy provider and an error otherwise.
	// Implementations backed by remote services may use ctx to bound the
	// check; static providers ignore ctx and return nil unless closed.
	HealthCheck(ctx context.Context) error

	// Close zeros all key material and releases resources.
	// After Close, Encrypt, Decrypt, and HealthCheck return ErrProviderClosed.
	Close() error
}

Provider encrypts and decrypts data using envelope encryption. Implementations must be safe for concurrent use.

func NewProvider added in v0.3.0

func NewProvider(keyBytes []byte, id string) (Provider, error)

NewProvider builds a static Provider from raw 32-byte AES-256 key bytes. Key bytes are copied internally; the caller may safely zero the original after construction. The returned Provider does not expose key rotation methods; use NewKeyRingProvider when runtime rotation is required.

type SelectorCodec added in v0.5.1

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

SelectorCodec wraps a NamespaceSelector with an inner codec (e.g. JSON) to provide per-namespace encryption through a single codec registration.

On Encode, it reads the namespace from ctx (via WithNamespace), serializes the value with the inner codec, then encrypts with the namespace-specific provider from the selector.

On Decode, it reads the namespace from ctx, decrypts with the matching provider, then deserializes with the inner codec.

Register once at startup:

sel, _ := crypto.NewNamespaceSelector(
    crypto.WithNamespaceProvider("payments", awsProvider),
    crypto.WithNamespaceProvider("users",    gcpProvider),
    crypto.WithFallbackProvider(defaultProvider),
)
sc, _ := crypto.NewSelectorCodec(sel, jsoncodec.New())
codec.Register(sc) // one registration covers all namespaces

When calling store operations, inject the namespace into ctx first:

ctx = crypto.WithNamespace(ctx, "payments")
store.Set(ctx, "payments", "db-password", value)

SelectorCodec is safe for concurrent use if the NamespaceSelector and inner codec are safe for concurrent use.

func NewSelectorCodec added in v0.5.1

func NewSelectorCodec(selector *NamespaceSelector, inner codec.Codec, opts ...CodecOption) (*SelectorCodec, error)

NewSelectorCodec creates a SelectorCodec. The codec name is "encrypted:<inner>" (e.g. "encrypted:json"). WithClientCodec and WithCodecPrefix options from NewCodec are reused here. Returns an error if selector or inner is nil.

func (*SelectorCodec) Decode added in v0.5.1

func (c *SelectorCodec) Decode(ctx context.Context, data []byte, v any) error

Decode decrypts data with the provider resolved from ctx's namespace, then deserializes into v using the inner codec.

func (*SelectorCodec) Encode added in v0.5.1

func (c *SelectorCodec) Encode(ctx context.Context, v any) ([]byte, error)

Encode serializes v with the inner codec then encrypts with the provider resolved from ctx's namespace. Returns ErrNoProviderForNamespace if no provider is registered for the namespace and no fallback is set.

func (*SelectorCodec) Name added in v0.5.1

func (c *SelectorCodec) Name() string

Name returns the codec name, e.g. "encrypted:json".

func (*SelectorCodec) Reverse added in v0.5.1

func (c *SelectorCodec) Reverse(ctx context.Context, data []byte) ([]byte, error)

Reverse decrypts raw bytes using the provider resolved from ctx's namespace. Implements codec.Transformer for use with codec.NewChain.

func (*SelectorCodec) Transform added in v0.5.1

func (c *SelectorCodec) Transform(ctx context.Context, data []byte) ([]byte, error)

Transform encrypts raw bytes using the provider resolved from ctx's namespace. Implements codec.Transformer for use with codec.NewChain.

Directories

Path Synopsis
Package awskms provides a crypto.Provider backed by AWS KMS.
Package awskms provides a crypto.Provider backed by AWS KMS.
Package azurekv provides a crypto.Provider backed by Azure Key Vault.
Package azurekv provides a crypto.Provider backed by Azure Key Vault.
Package gcpkms provides a crypto.Provider backed by Google Cloud KMS.
Package gcpkms provides a crypto.Provider backed by Google Cloud KMS.
Package gpg provides a crypto.Provider that decrypts AES-256 keys using GPG.
Package gpg provides a crypto.Provider that decrypts AES-256 keys using GPG.
internal
kmsring
Package kmsring factors out the common "unwrap N encrypted keys and build a crypto.KeyRingProvider" loop shared by every KMS adapter in this module.
Package kmsring factors out the common "unwrap N encrypted keys and build a crypto.KeyRingProvider" loop shared by every KMS adapter in this module.
Package otel provides OpenTelemetry instrumentation for the config-crypto Provider interface.
Package otel provides OpenTelemetry instrumentation for the config-crypto Provider interface.
Package rotation provides a background Orchestrator that re-encrypts stored configuration values whose encryption key is no longer the current version of the ring.
Package rotation provides a background Orchestrator that re-encrypts stored configuration values whose encryption key is no longer the current version of the ring.
Package vault provides a crypto.KeyRingProvider backed by a HashiCorp Vault KV v2 secret.
Package vault provides a crypto.KeyRingProvider backed by a HashiCorp Vault KV v2 secret.

Jump to

Keyboard shortcuts

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