encryption

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

README

eventsalsa/encryption

KMS-native envelope encryption for Go systems — supporting AWS KMS, Google Cloud KMS, and local symmetric KEKs, with stateless PostgreSQL key storage, mandatory AAD scope binding, reusable in-memory sessions, and zero-downtime key rotation.

Features

  • KMS-native envelope encryption — two-tier key hierarchy (kek.Keyring KEK → per-scope DEK → application data) where KEK material never leaves the KMS boundary
  • Cloud & local KEK providers — ships kek/awskms (AWS KMS SDK v2 with native ReEncrypt), kek/gcpkms (Google Cloud KMS with Castagnoli CRC32C verification), and kek/local (in-memory & file-based AES-256-GCM)
  • Confused-deputy protection via AAD — every wrapped DEK is cryptographically bound to its (scope, scope_id, key_version) tuple via Additional Authenticated Data (EncryptionContext in AWS KMS, AdditionalAuthenticatedData in GCP KMS, GCM AAD locally)
  • High-throughput Session & CachingKeyring — unwrap a DEK once via env.OpenSession to encrypt/decrypt entire event streams with zero network calls, or wrap any Keyring in kek.NewCachingKeyring (bounded TTL + LRU with automatic memory scrubbing)
  • Stateless PostgreSQL storage — explicit connection passing (*pgxpool.Pool, pgx.Tx, *pgx.Conn) for clean SQL transaction participation and single-statement atomic key rotation
  • GDPR crypto-shredding — store.DestroyKeys permanently deletes scope keys, rendering historical event ciphertexts mathematically unreadable
  • KEK rotation & cross-provider migration — postgres.RewrapKeys migrates stored DEKs in batches (using server-side AWS KMS ReEncrypt when available or transparent Unwrap + Wrap across providers)
  • Isolated Go sub-modules — root module has zero cloud SDK dependencies; install kek/awskms or kek/gcpkms only when needed

Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                               Application                               │
│                                                                         │
│         postgres.Store                         envelope.Envelope        │
│          │          │                           │             │         │
│          │          ▼                           ▼             ▼         │
│          │     PostgreSQL                 kek.Keyring   envelope.Session│
│          │   (pgx.Tx / Pool)            (or CachingKR)        │         │
│          └──────────────────────────────────┐   │             ▼         │
│                                             │   │       cipher.Cipher   │
│                                             ▼   ▼       (AES-256-GCM)   │
│                                    ┌────────────────────┐               │
│                                    │  kek/local         │               │
│                                    │  kek/awskms (KMS)  │               │
│                                    │  kek/gcpkms (KMS)  │               │
│                                    └────────────────────┘               │
└─────────────────────────────────────────────────────────────────────────┘
Package Overview
Package Module Role
encryption (root) github.com/eventsalsa/encryption Sentinel errors, EncryptedKey, KeyScope (canonical AAD), and ZeroBytes
cipher github.com/eventsalsa/encryption Cipher AEAD interface (Encrypt/Decrypt with aad []byte)
cipher/aesgcm github.com/eventsalsa/encryption AES-256-GCM AEAD implementation
kek github.com/eventsalsa/encryption Wrapper, Rewrapper, Keyring, and CachingKeyring
kek/local github.com/eventsalsa/encryption In-process AES-256-GCM KEK wrapper + map and file loaders
kek/awskms github.com/eventsalsa/encryption/kek/awskms AWS KMS Wrapper & native server-side Rewrapper (ReEncrypt)
kek/gcpkms github.com/eventsalsa/encryption/kek/gcpkms Google Cloud KMS Wrapper with end-to-end CRC32C verification
envelope github.com/eventsalsa/encryption Envelope and Session for DEK lifecycle and payload encryption
postgres github.com/eventsalsa/encryption Stateless PostgreSQL Store and batch RewrapKeys
postgres/migrations github.com/eventsalsa/encryption Embedded PostgreSQL migration SQL and generator
hash github.com/eventsalsa/encryption Hasher interface + HMAC-SHA256 blind indexing
testutil github.com/eventsalsa/encryption Test helpers (NewTestKeyring())

Getting Started

1. Generate Database Migration
go run github.com/eventsalsa/encryption/cmd/migrate-gen -output migrations
# Or print directly to stdout:
go run github.com/eventsalsa/encryption/cmd/migrate-gen -stdout
2. Configure a KEK Keyring (AWS KMS, GCP KMS, or Local)
// Option A: AWS KMS (github.com/eventsalsa/encryption/kek/awskms)
awsWrapper, err := awskms.NewWrapper(kmsClient, "arn:aws:kms:eu-west-1:123456789012:key/mrk-1234")
keyring, err := kek.NewKeyring(awsWrapper.ID(), awsWrapper)

// Option B: Google Cloud KMS (github.com/eventsalsa/encryption/kek/gcpkms)
gcpWrapper, err := gcpkms.NewWrapper(gcpClient, "projects/my-proj/locations/global/keyRings/kr/cryptoKeys/kek-1")
keyring, err := kek.NewKeyring(gcpWrapper.ID(), gcpWrapper)

// Option C: Local 32-byte KEK (in-memory or from files)
keyring, err := local.NewKeyringFromMap(map[string][]byte{"local-v1": raw32ByteKey}, "local-v1")

// Optional: Decorate with an in-memory TTL + LRU cache to avoid repeated KMS RPCs
cachedKeyring, err := kek.NewCachingKeyring(keyring, kek.CacheConfig{
	TTL:        5 * time.Minute,
	MaxEntries: 1000,
})
defer cachedKeyring.Close()
3. Encrypt & Decrypt (Single-Shot and Reusable Sessions)
env := envelope.New(cachedKeyring, aesgcm.New())
store := postgres.NewStore(env, postgres.Config{})

// 1. Create or fetch the active key for a scope
key, err := store.CreateKey(ctx, pool, "user-pii", "user-123")
if errors.Is(err, encryption.ErrKeyExists) {
	key, err = store.GetActiveKey(ctx, pool, "user-pii", "user-123")
}

// 2. Single-shot encryption/decryption (with optional payload AAD)
ct, err := env.EncryptString(ctx, key, "alice@example.com", []byte("field:email"))
pt, err := env.DecryptString(ctx, key, ct, []byte("field:email"))

// 3. Batch / event-stream session (unwraps DEK once, encrypts/decrypts in RAM)
session, err := env.OpenSession(ctx, key)
if err != nil {
	return err
}
defer session.Close() // Scrubs plaintext DEK from RAM

emailCT, err := session.Encrypt([]byte("alice@example.com"), []byte("field:email"))
phoneCT, err := session.Encrypt([]byte("+15550100"), []byte("field:phone"))

KEK Rotation & Cross-Provider Rewrapping

When rotating KEKs or migrating from local keys to Cloud KMS, register both the old and new wrappers in kek.Keyring and run postgres.RewrapKeys:

result, err := postgres.RewrapKeys(ctx, pool, postgres.Config{}, env, postgres.RewrapKeysOptions{
	FromKEKID: "local-v1",
	ToKEKID:   awsWrapper.ID(),
	BatchSize: 500,
})

Build & Test

# Run the full validation suite (fmt, vet, golangci-lint, test, integration, gosec, govulncheck)
make check

Documentation

Overview

Package encryption provides envelope encryption for Go systems.

Architecture

The library uses envelope encryption: data is encrypted with a Data Encryption Key (DEK), and the DEK is encrypted with a system Key Encryption Key (KEK).

  • cipher/: pluggable symmetric encryption interface and implementations (AES-256-GCM)
  • systemkey/: system key (KEK) management abstractions and filesystem loaders
  • envelope/: pure in-memory envelope encryption engine
  • postgres/: stateless PostgreSQL keystore and key lifecycle management
  • postgres/migrations: PostgreSQL migration SQL generator
  • hash/: deterministic HMAC-SHA256 blind indexing

Package encryption provides envelope encryption for Go systems.

This package defines shared sentinel errors used across all sub-packages.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrKeyNotFound    = errors.New("encryption key not found")
	ErrKeyExists      = errors.New("encryption key already exists")
	ErrEncryption     = errors.New("encryption failed")
	ErrDecryption     = errors.New("decryption failed")
	ErrInvalidKeySize = errors.New("invalid key size")
	ErrKeyRevoked     = errors.New("encryption key has been revoked")
	ErrKeyDestroyed   = errors.New("encryption key has been destroyed")
	ErrSessionClosed  = errors.New("encryption session is closed")
	ErrInvalidConfig  = errors.New("invalid encryption configuration")
)

Sentinel errors used across the encryption library.

Functions

func ZeroBytes

func ZeroBytes(b []byte)

ZeroBytes overwrites a byte slice with zeros to clear sensitive key material from memory. Use with defer after decrypting DEKs:

defer encryption.ZeroBytes(dek)

Types

type EncryptedKey added in v0.0.6

type EncryptedKey struct {
	Scope        string
	ScopeID      string
	KeyVersion   int
	EncryptedDEK []byte
	KEKID        string
	CreatedAt    time.Time
	RevokedAt    *time.Time
}

EncryptedKey represents a wrapped DEK and its lifecycle metadata.

func (*EncryptedKey) KeyScope added in v0.0.6

func (k *EncryptedKey) KeyScope() KeyScope

KeyScope returns the key's identifying scope tuple.

type KeyScope added in v0.0.6

type KeyScope struct {
	Scope      string
	ScopeID    string
	KeyVersion int
}

KeyScope uniquely identifies a versioned DEK within a logical namespace.

func (KeyScope) AAD added in v0.0.6

func (s KeyScope) AAD() []byte

AAD returns a canonical, unambiguous length-prefixed representation of the KeyScope ("<len(Scope)>:<Scope>|<len(ScopeID)>:<ScopeID>|<KeyVersion>") used as Additional Authenticated Data (AAD) when wrapping, unwrapping, or rewrapping a DEK.

func (KeyScope) Validate added in v0.0.6

func (s KeyScope) Validate() error

Validate checks that the KeyScope has non-empty Scope, ScopeID, and a positive KeyVersion.

Directories

Path Synopsis
Package cipher defines the authenticated symmetric encryption interface (AEAD) used throughout the encryption library.
Package cipher defines the authenticated symmetric encryption interface (AEAD) used throughout the encryption library.
aesgcm
Package aesgcm provides an AES-256-GCM implementation of the cipher.Cipher interface.
Package aesgcm provides an AES-256-GCM implementation of the cipher.Cipher interface.
cmd
migrate-gen command
Command migrate-gen generates SQL migration files for the PostgreSQL keystore.
Command migrate-gen generates SQL migration files for the PostgreSQL keystore.
Package envelope implements KMS-native envelope encryption using a two-tier key hierarchy: Key Encryption Keys (KEKs) protect per-scope Data Encryption Keys (DEKs), and DEKs protect application data via local AEAD.
Package envelope implements KMS-native envelope encryption using a two-tier key hierarchy: Key Encryption Keys (KEKs) protect per-scope Data Encryption Keys (DEKs), and DEKs protect application data via local AEAD.
examples
basic command
Example: envelope encryption with envelope.Envelope and envelope.Session.
Example: envelope encryption with envelope.Envelope and envelope.Session.
pii command
Example: GDPR PII encryption and crypto-shredding lifecycle with PostgreSQL.
Example: GDPR PII encryption and crypto-shredding lifecycle with PostgreSQL.
secrets command
Example: Secret encryption with key rotation and historical audit retention.
Example: Secret encryption with key rotation and historical audit retention.
kek
Package kek defines Key Encryption Key (KEK) abstractions for wrapping, unwrapping, and rewrapping Data Encryption Keys (DEKs).
Package kek defines Key Encryption Key (KEK) abstractions for wrapping, unwrapping, and rewrapping Data Encryption Keys (DEKs).
local
Package local implements an in-process symmetric kek.Wrapper using a cipher.Cipher (AES-256-GCM by default) and provides in-memory and file-based KEK loaders.
Package local implements an in-process symmetric kek.Wrapper using a cipher.Cipher (AES-256-GCM by default) and provides in-memory and file-based KEK loaders.
migrations
Package migrations exposes the embedded PostgreSQL keystore migration.
Package migrations exposes the embedded PostgreSQL keystore migration.
Package testutil provides test helpers for encryption testing.
Package testutil provides test helpers for encryption testing.

Jump to

Keyboard shortcuts

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