crypto

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2025 License: MPL-2.0 Imports: 21 Imported by: 0

README

Harpocrates: High-Performance Professional Cryptography Library for Go

an AGILira library

Designed for Nemesis, Harpocrates delivers secure and well-tested primitives for encryption, decryption, key and nonce management, and key fingerprinting using AES-256-GCM with advanced optimizations including cipher caching, buffer pooling, and cache-line tuned algorithms.

CI Security Go Report Card Test Coverage

FeaturesInstallationQuick ExamplesPhilosophyDocumentationSecurityPerformance

Features

High-Performance Core Cryptography
  • AES-256-GCM authenticated encryption with cipher caching (49% performance boost)
  • Binary & string data support with optimized EncryptBytes/DecryptBytes core functions
  • Streaming encryption/decryption for large datasets (GB-scale) with chunked processing
  • Advanced buffer pooling with 79% memory reduction and cache-line optimization
  • Ring buffer techniques applied for consistent low latency
  • Thread-safe operations with linear scaling on multi-core systems
Zero-Downtime Key Management
  • Zero-downtime key rotation with dual-KEK architecture and automated rollback
  • NEMESIS-grade key lifecycle with multi-state management (pending, validating, active, deprecated, revoked)
  • Prepare→Validate→Commit rotation phases with automatic failure recovery
  • Backward compatibility - all existing APIs work unchanged while adding new capabilities
Key Derivation Functions
  • Argon2id key derivation (resistant to ASIC/FPGA attacks) with secure defaults
  • PBKDF2-SHA256 legacy support for backward compatibility
  • HKDF key derivation for hierarchical key generation and context separation
  • Cryptographically secure random generation for keys and nonces
Hardware Security Module (HSM) Integration
  • Enterprise HSM support with PKCS#11 compliance (SafeNet, Thales, AWS CloudHSM)
  • Plugin architecture powered by github.com/agilira/go-plugins
  • Hardware-protected key generation within secure HSM boundaries
  • FIPS 140-2 Level 3/4 compliance for regulated environments
  • Tamper-resistant operations with hardware attestation
  • Multi-vendor compatibility through standardized plugin interface
Security & Quality
  • Secure memory zeroization for sensitive data protection
  • Advanced error handling with rich error context and structured error codes
  • Comprehensive testing with 90%+ coverage including boundary, stress, and integration tests
  • Secure by Design: Red-team tested against attack vectors in cryptographic operations

Compatibility and Support

Harpocrates supports the latest two minor versions of Go (currently Go 1.24+ and Go 1.25+) and follows Long-Term Support guidelines to ensure consistent performance across production deployments.

Installation

go get github.com/agilira/harpocrates

Quick Examples

Basic Encryption/Decryption
import crypto "github.com/agilira/harpocrates"

key, err := crypto.GenerateKey()
if err != nil {
    // handle error
}

// For text data (convenience functions)
ciphertext, err := crypto.Encrypt("secret data", key)
plaintext, err := crypto.Decrypt(ciphertext, key)

// For binary data (core functions - recommended)
binaryData := []byte{0x00, 0x01, 0xFF, 0xFE}
ciphertext, err := crypto.EncryptBytes(binaryData, key)
decrypted, err := crypto.DecryptBytes(ciphertext, key)
Zero-Downtime Key Rotation
// Initialize key manager
km := crypto.NewKeyManager()

// Current way: immediate rotation (brief downtime)
newKEK, err := km.RotateKEK("purpose")

// New way: zero-downtime rotation
newKEK, err := km.RotateKEKZeroDowntime("purpose")

// Or step-by-step control
pendingKEK, err := km.PrepareKEKRotation("purpose")  // Phase 1: prepare
err = km.ValidateKEKRotation()                       // Phase 2: validate  
err = km.CommitKEKRotation()                         // Phase 3: commit
// err = km.RollbackKEKRotation()                    // Emergency rollback
Streaming Large Data
// For large files/datasets (GB-scale)
key, _ := crypto.GenerateKey()

// Streaming encryption
encryptor, err := crypto.NewStreamingEncryptor(outputWriter, key)
defer encryptor.Close()
io.Copy(encryptor, inputReader) // Encrypts while streaming

// Streaming decryption  
decryptor, err := crypto.NewStreamingDecryptor(inputReader, key)
defer decryptor.Close()
io.Copy(outputWriter, decryptor) // Decrypts while streaming
Hardware Security Module (HSM) Integration
// Initialize HSM with go-plugins gRPC interface
hsm, err := crypto.NewHSM("pkcs11", map[string]interface{}{
    "plugin_path":  "./plugins/hsm-pkcs11",
    "grpc_address": "localhost:50051",
    "slot_id":      0,
    "pin":          "1234",
})
defer hsm.Close()

// Generate key in HSM hardware
keyHandle, err := hsm.GenerateKey("vault-master-kek", 32)

// Hardware-protected encryption
ciphertext, err := hsm.Encrypt(keyHandle, []byte("sensitive data"))
plaintext, err := hsm.Decrypt(keyHandle, ciphertext)
Advanced Key Derivation
password := []byte("my-secure-password")
salt := []byte("random-salt-123")

// Argon2id (recommended)
key, err := crypto.DeriveKeyDefault(password, salt, 32)

// HKDF for hierarchical keys
context := []byte("user-session-keys")
sessionKey, err := crypto.DeriveKeyHKDF(masterKey, salt, context, 32)

// Custom Argon2 parameters
key, err := crypto.DeriveKeyWithParams(password, salt, 3, 64*1024, 4, 32)

The Philosophy Behind Harpocrates

Harpocrates, the child of silence, understood what others could not grasp. In ancient temples, when priests whispered the most sacred incantations, when merchants sealed their most valuable contracts, when lovers shared their deepest secrets—Harpocrates was there, finger raised to his lips, guardian of what must never be spoken aloud.

The young god knew that true power lay not in the message itself, but in ensuring that only the intended could hear it. His silence was not empty—it was full of protection. Each secret he guarded was wrapped in layers of divine safekeeping, accessible only to those who possessed the proper keys to unlock his trust.

In the halls of Alexandria's great library, scholars would invoke Harpocrates before transcribing their most precious knowledge, knowing that the god of silence would ensure their wisdom reached only worthy hands across the centuries.

Documentation

Security

This library uses industry-standard cryptographic algorithms and follows security best practices. For detailed security information, see Security Documentation.

Performance

Benchmark Results (AMD Ryzen 5 7520U)
BenchmarkEncryptionAllocation-8    734821    1692 ns/op    632 B/op    15 allocs/op
BenchmarkEncryptionWithPooling/Small_(16B)-8    827762    1528 ns/op    424 B/op    14 allocs/op
Scaling Characteristics
  • Single-core: 1.31M ops/sec theoretical maximum
  • Multi-core: Linear scaling with worker pools
  • Memory: 79% reduction in allocations with buffer pooling
  • Latency: Consistent sub-microsecond performance with cache optimization

Harpocrates • an AGILira library

Documentation

Overview

Package crypto provides high-performance secure cryptographic utilities for Go applications.

This package offers a comprehensive set of cryptographic primitives including:

  • AES-256-GCM authenticated encryption and decryption with cipher caching
  • Argon2id key derivation for secure password-based key generation
  • HKDF-SHA256 for high-entropy key derivation (DEK generation)
  • PBKDF2-SHA256 legacy support for backward compatibility
  • Cryptographically secure random number generation
  • Advanced key rotation and management for enterprise vaults (NEMESIS-ready)
  • Hardware Security Module (HSM) integration with plugin architecture
  • Secure memory zeroization and buffer pooling for sensitive data
  • Streaming encryption for large datasets

The package is designed for high-performance production systems, with optimizations including cipher caching, buffer pooling, and micro-optimizations achieving 1.31M+ operations per second on modern hardware.

Quick Start

Basic encryption and decryption:

// Generate a new encryption key
key, err := crypto.GenerateKey()
if err != nil {
	log.Fatal(err)
}

// Encrypt some data
ciphertext, err := crypto.Encrypt("sensitive data", key)
if err != nil {
	log.Fatal(err)
}

// Decrypt the data
plaintext, err := crypto.Decrypt(ciphertext, key)
if err != nil {
	log.Fatal(err)
}

fmt.Println(plaintext) // Output: sensitive data

Key Derivation

For deriving keys from passwords:

password := []byte("my-secure-password")
salt := []byte("random-salt-123")

// Derive a key using Argon2id with secure defaults
derivedKey, err := crypto.DeriveKeyDefault(password, salt, 32)
if err != nil {
	log.Fatal(err)
}

// Use custom parameters for higher security
params := &crypto.KDFParams{
	Time:    4,    // 4 iterations
	Memory:  128,  // 128 MB memory
	Threads: 2,    // 2 threads
}
key, err := crypto.DeriveKey(password, salt, 32, params)

Key Management

Key utilities for import/export and validation:

// Generate and export a key
key, _ := crypto.GenerateKey()
base64Key := crypto.KeyToBase64(key)
hexKey := crypto.KeyToHex(key)

// Import and validate a key
importedKey, err := crypto.KeyFromBase64(base64Key)
if err != nil {
	log.Fatal(err)
}
err = crypto.ValidateKey(importedKey)
if err != nil {
	log.Fatal("Invalid key:", err)
}

// Generate a fingerprint for identification
fingerprint := crypto.GetKeyFingerprint(key)
fmt.Println("Key fingerprint:", fingerprint)

// Securely wipe sensitive data
crypto.Zeroize(key)

Error Handling

All functions return standard Go errors for maximum compatibility. For advanced error handling with rich error details, the library integrates with github.com/agilira/go-errors.

Example error handling:

ciphertext, err := crypto.Encrypt("data", key)
if err != nil {
	if errors.Is(err, crypto.ErrInvalidKeySize) {
		// Handle invalid key size
	} else if errors.Is(err, crypto.ErrEmptyPlaintext) {
		// Handle empty plaintext
	}
	// Handle other errors
}

Security Considerations

This library uses industry-standard cryptographic algorithms with enterprise security:

  • AES-256-GCM for authenticated encryption with nonce uniqueness guarantees
  • Argon2id for key derivation (resistant to ASIC/FPGA attacks and side-channel attacks)
  • HKDF-SHA256 for high-entropy key derivation (suitable for DEK generation)
  • Cryptographically secure random number generation (crypto/rand)
  • Secure memory zeroization with cache-line aligned clearing
  • Thread-safe key rotation with mutex protection against race conditions
  • Cipher caching with key fingerprinting to prevent key confusion attacks
  • Buffer pooling with security-first design (automatic zeroing on return)

Security testing includes advanced attack simulation following Argus security patterns. For detailed security information, see the Security documentation.

Performance

The library is highly optimized for production workloads with:

  • Cipher caching: Eliminates aes.NewCipher + cipher.NewGCM overhead (49% performance boost)
  • Buffer pooling: Reduces memory allocations by 79% with intelligent reuse
  • Cache-line optimization: Loop unrolling and memory access patterns tuned for modern CPUs
  • Ring buffer techniques: Applied micro-optimizations for consistent low latency

Benchmark results on AMD Ryzen 5 7520U:

  • Single operation: ~764ns (1.31M ops/sec)
  • Encrypt+Decrypt cycle: ~1528ns (655k ops/sec)
  • Memory efficiency: 632B per operation vs 3050B (standard implementation)
  • Thread-safe: Linear scaling with worker pools for multi-core systems

Target performance for NEMESIS vault: 500k+ ops/sec (2.6x margin achieved)

Key Rotation for Enterprise Vaults (NEMESIS)

Advanced key management with zero-downtime rotation:

// Create a key manager for enterprise vault
km := crypto.NewKeyManager()

// Generate and activate initial KEK
kek, err := km.GenerateKEK("vault-master")
if err != nil {
	log.Fatal(err)
}
err = km.ActivateKEK(kek.ID)

// Derive data encryption keys
context := []byte("tenant:vault-app,path:/secrets/db")
dek, kekID, err := km.DeriveDataKey(context, 32)
if err != nil {
	log.Fatal(err)
}

// Perform zero-downtime rotation
newKEK, err := km.PrepareKEKRotation("vault-master-v2")
if err != nil {
	log.Fatal(err)
}

// Validate new KEK before commit
if err := km.ValidateKEKRotation(newKEK.ID); err != nil {
	km.RollbackKEKRotation() // Safe rollback
	log.Fatal(err)
}

// Commit rotation atomically
if err := km.CommitKEKRotation(); err != nil {
	log.Fatal(err)
}

Hardware Security Module (HSM) Support

Enterprise-grade HSM integration using the go-plugins architecture for secure key management and cryptographic operations in hardware-protected environments:

// Initialize HSM with plugin
hsm, err := crypto.NewHSM("pkcs11", map[string]interface{}{
	"library_path": "/usr/lib/pkcs11/libpkcs11.so",
	"slot_id":      0,
	"pin":          "1234",
})
if err != nil {
	log.Fatal("HSM initialization failed:", err)
}
defer hsm.Close()

// Generate key in HSM
keyHandle, err := hsm.GenerateKey("vault-master-kek", 32)
if err != nil {
	log.Fatal("HSM key generation failed:", err)
}

// Use HSM for encryption
plaintext := []byte("sensitive vault data")
ciphertext, err := hsm.Encrypt(keyHandle, plaintext)
if err != nil {
	log.Fatal("HSM encryption failed:", err)
}

// Decrypt using HSM
decrypted, err := hsm.Decrypt(keyHandle, ciphertext)
if err != nil {
	log.Fatal("HSM decryption failed:", err)
}

HSM Features:

  • PKCS#11 standard compliance for broad hardware support
  • Plugin architecture using github.com/agilira/go-plugins
  • Secure key generation within hardware boundaries
  • Hardware-protected encryption/decryption operations
  • Key lifecycle management (generation, rotation, destruction)
  • Tamper-resistant security with hardware attestation
  • Multi-vendor HSM support (SafeNet, Thales, AWS CloudHSM, etc.)

The HSM integration provides FIPS 140-2 Level 3/4 security compliance for enterprise vault deployments requiring hardware-based key protection.

Streaming Encryption for Large Datasets

Efficient streaming encryption for large files and data streams:

// Create streaming encryptor
key, _ := crypto.GenerateKey()
encryptor, err := crypto.NewStreamingEncryptorWithChunkSize(output, key, 64*1024)
if err != nil {
	log.Fatal(err)
}
defer encryptor.Close()

// Stream large amounts of data
for _, chunk := range dataChunks {
	if _, err := encryptor.Write(chunk); err != nil {
		log.Fatal(err)
	}
}

Copyright (c) 2025 AGILira Series: an AGLIra library SPDX-License-Identifier: MPL-2.0

Index

Constants

View Source
const (
	ErrCodeInvalidKey   = "CRYPTO_INVALID_KEY"
	ErrCodeEmptyPlain   = "CRYPTO_EMPTY_PLAINTEXT"
	ErrCodeCipherInit   = "CRYPTO_CIPHER_INIT"
	ErrCodeGCMInit      = "CRYPTO_GCM_INIT"
	ErrCodeNonceGen     = "CRYPTO_NONCE_GEN"
	ErrCodeBase64Decode = "CRYPTO_BASE64_DECODE"
	ErrCodeCipherShort  = "CRYPTO_CIPHERTEXT_SHORT"
	ErrCodeDecrypt      = "CRYPTO_DECRYPT"
)

Error codes for rich error handling

View Source
const (
	// DefaultTime is the default number of iterations for Argon2id.
	// Higher values increase security but also computation time.
	DefaultTime = 3

	// DefaultMemory is the default memory usage in MB for Argon2id.
	// Higher values increase security against memory-based attacks.
	DefaultMemory = 64

	// DefaultThreads is the default number of threads for Argon2id.
	// Should not exceed the number of CPU cores.
	DefaultThreads = 4
)

Default Argon2 parameters for key derivation. These values provide a good balance between security and performance.

View Source
const (
	ErrCodeKeyNotFound      = "KEY_NOT_FOUND"
	ErrCodeKeyInactive      = "KEY_INACTIVE"
	ErrCodeKeyGeneration    = "KEY_GENERATION"
	ErrCodeKeyRotation      = "KEY_ROTATION"
	ErrCodeKeyValidation    = "KEY_VALIDATION"
	ErrCodeKeySerialization = "KEY_SERIALIZATION"
)

Error codes for key rotation

View Source
const (
	StatusActive     = "active"     // Active key for encryption/decryption
	StatusPending    = "pending"    // Key in preparation for activation
	StatusValidating = "validating" // Key in validation phase
	StatusDeprecated = "deprecated" // Deprecated key (for decryption only)
	StatusRevoked    = "revoked"    // Revoked key (not usable)
)

Key status constants

View Source
const DefaultChunkSize = 64 * 1024

Default chunk size for streaming operations (64KB) This balances memory usage with encryption efficiency.

View Source
const KeySize = 32

KeySize is the required key size for AES-256 encryption in bytes. AES-256 requires exactly 32 bytes (256 bits) for the encryption key.

Variables

View Source
var (
	// ErrInvalidKeySize is returned when the provided key is not exactly 32 bytes.
	ErrInvalidKeySize = errors.New("crypto: invalid key size")

	// ErrEmptyPlaintext is returned when trying to decrypt an empty string.
	// Note: Empty plaintext is supported for encryption.
	ErrEmptyPlaintext = errors.New("crypto: plaintext cannot be empty")

	// ErrCipherInit is returned when AES cipher initialization fails.
	ErrCipherInit = errors.New("crypto: cipher initialization error")

	// ErrGCMInit is returned when GCM mode initialization fails.
	ErrGCMInit = errors.New("crypto: GCM initialization error")

	// ErrNonceGen is returned when nonce generation fails.
	ErrNonceGen = errors.New("crypto: nonce generation error")

	// ErrBase64Decode is returned when base64 decoding fails.
	ErrBase64Decode = errors.New("crypto: base64 decode error")

	// ErrCiphertextShort is returned when the ciphertext is too short to contain a valid nonce.
	ErrCiphertextShort = errors.New("crypto: ciphertext too short")

	// ErrDecrypt is returned when decryption fails due to authentication failure or corruption.
	ErrDecrypt = errors.New("crypto: decryption error")
)

Public standard errors for drop-in compatibility. These errors can be used with errors.Is() for error checking.

View Source
var (
	ErrHSMNotInitialized    = goerrors.New("HSM_001", "HSM provider not initialized")
	ErrHSMKeyNotFound       = goerrors.New("HSM_002", "Key not found in HSM")
	ErrHSMOperationFailed   = goerrors.New("HSM_003", "HSM operation failed")
	ErrHSMInvalidKeyType    = goerrors.New("HSM_004", "Invalid or unsupported key type")
	ErrHSMInvalidUsage      = goerrors.New("HSM_005", "Invalid key usage for operation")
	ErrHSMProviderNotFound  = goerrors.New("HSM_006", "HSM provider not found")
	ErrHSMHealthCheckFailed = goerrors.New("HSM_007", "HSM health check failed")
	ErrHSMOperationTimeout  = goerrors.New("HSM_008", "HSM operation timed out")
	ErrHSMInvalidParameters = goerrors.New("HSM_009", "Invalid operation parameters")
	ErrHSMAccessDenied      = goerrors.New("HSM_010", "Access denied by HSM")
)

Common HSM errors with proper error codes for auditing

Functions

func Decrypt

func Decrypt(encryptedText string, key []byte) (string, error)

Decrypt decrypts a base64-encoded ciphertext string using AES-256-GCM authenticated decryption.

This is a convenience wrapper around DecryptBytes that works with strings. The function verifies the authenticity of the ciphertext using the embedded authentication tag. If the ciphertext has been tampered with, the function will return an error.

Parameters:

  • encryptedText: The base64-encoded encrypted string (cannot be empty)
  • key: The 32-byte decryption key (must be exactly KeySize bytes)

Returns:

  • The decrypted plaintext string
  • An error if decryption fails (authentication failure, corruption, or invalid input)

Example:

key, _ := crypto.GenerateKey()
ciphertext, _ := crypto.Encrypt("sensitive data", key)
plaintext, err := crypto.Decrypt(ciphertext, key)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Decrypted:", plaintext) // Output: sensitive data

The function will return an error if:

  • The key size is incorrect
  • The encrypted text is empty
  • The base64 decoding fails
  • The ciphertext is too short
  • Authentication fails (tampering detected)

func DecryptBytes

func DecryptBytes(encryptedText string, key []byte) ([]byte, error)

DecryptBytes decrypts a base64-encoded ciphertext string using AES-256-GCM authenticated decryption.

The function verifies the authenticity of the ciphertext using the embedded authentication tag. If the ciphertext has been tampered with, the function will return an error. This is the core decryption function that returns binary data with buffer pooling optimization.

Parameters:

  • encryptedText: The base64-encoded encrypted string (cannot be empty)
  • key: The 32-byte decryption key (must be exactly KeySize bytes)

Returns:

  • The decrypted plaintext as a byte slice
  • An error if decryption fails (authentication failure, corruption, or invalid input)

Example:

key, _ := crypto.GenerateKey()
data := []byte("sensitive binary data")
ciphertext, _ := crypto.EncryptBytes(data, key)
plaintext, err := crypto.DecryptBytes(ciphertext, key)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Decrypted:", string(plaintext)) // Output: sensitive binary data

The function will return an error if:

  • The key size is incorrect
  • The encrypted text is empty
  • The base64 decoding fails
  • The ciphertext is too short
  • Authentication fails (tampering detected)

func DecryptBytesWithAAD

func DecryptBytesWithAAD(encryptedText string, key []byte, aad []byte) ([]byte, error)

DecryptBytesWithAAD decrypts a base64-encoded ciphertext string using AES-256-GCM with Additional Authenticated Data.

This function verifies both the ciphertext authenticity and the AAD integrity. If either the ciphertext or AAD has been tampered with, the function will return an error. This is designed for NEMESIS vault requirements with metadata authentication.

Parameters:

  • encryptedText: The base64-encoded encrypted string (cannot be empty)
  • key: The 32-byte decryption key (must be exactly KeySize bytes)
  • aad: Additional Authenticated Data (must match encryption AAD)

Returns:

  • The decrypted plaintext as a byte slice
  • An error if decryption or AAD verification fails

Example for NEMESIS:

aad := []byte(`{"tenant":"app","path":"/db/pass","version":1,"keyID":"kek_abc123"}`)
decrypted, err := crypto.DecryptBytesWithAAD(ciphertext, key, aad)

func DecryptWithAAD

func DecryptWithAAD(encryptedText string, key []byte, aad string) (string, error)

DecryptWithAAD decrypts a base64-encoded ciphertext string using AES-256-GCM with Additional Authenticated Data.

This is a convenience wrapper around DecryptBytesWithAAD that works with strings. Verifies both ciphertext authenticity and AAD integrity for NEMESIS requirements.

Parameters:

  • encryptedText: The base64-encoded encrypted string (cannot be empty)
  • key: The 32-byte decryption key (must be exactly KeySize bytes)
  • aad: Additional Authenticated Data as string (must match encryption AAD)

Returns:

  • The decrypted plaintext string
  • An error if decryption or AAD verification fails

Example for NEMESIS:

aad := `{"tenant":"app","path":"/db/pass","version":1,"keyID":"kek_abc123"}`
plaintext, err := crypto.DecryptWithAAD(ciphertext, key, aad)

func DeriveKey

func DeriveKey(password, salt []byte, keyLen int, params *KDFParams) ([]byte, error)

DeriveKey derives a key from a password and salt using Argon2id (the recommended variant).

Argon2id is the recommended variant of Argon2, providing resistance against both side-channel attacks and time-memory trade-off attacks. It uses secure default parameters that provide strong protection against both CPU and memory-based attacks.

Parameters:

  • password: The password to derive the key from (cannot be empty)
  • salt: The salt to use for key derivation (cannot be empty, should be random)
  • keyLen: The desired length of the derived key in bytes (must be positive)
  • params: Custom Argon2id parameters (nil to use secure defaults)

Returns:

  • The derived key as a byte slice
  • An error if key derivation fails

Example:

password := []byte("my-secure-password")
salt := []byte("random-salt-123")

// Use secure defaults
key, err := crypto.DeriveKey(password, salt, 32, nil)
if err != nil {
	log.Fatal(err)
}

// Use custom parameters
params := &crypto.KDFParams{
	Time:    4,
	Memory:  128,
	Threads: 2,
}
key, err := crypto.DeriveKey(password, salt, 32, params)

If params is nil, secure defaults are used (Time: 3, Memory: 64MB, Threads: 4).

func DeriveKeyDefault

func DeriveKeyDefault(password, salt []byte, keyLen int) ([]byte, error)

DeriveKeyDefault derives a key using Argon2id with secure default parameters.

This is a convenience function for when you don't need custom parameters. It's equivalent to calling DeriveKey with params set to nil.

Parameters:

  • password: The password to derive the key from (cannot be empty)
  • salt: The salt to use for key derivation (cannot be empty, should be random)
  • keyLen: The desired length of the derived key in bytes (must be positive)

Returns:

  • The derived key as a byte slice
  • An error if key derivation fails

Example:

password := []byte("my-secure-password")
salt := []byte("random-salt-123")
key, err := crypto.DeriveKeyDefault(password, salt, 32)
if err != nil {
	log.Fatal(err)
}

func DeriveKeyHKDF

func DeriveKeyHKDF(masterKey, salt, info []byte, keyLen int) ([]byte, error)

DeriveKeyHKDF derives a key using HKDF-SHA256 (RFC 5869). This is ideal for envelope encryption where you need to derive multiple keys from a single master key (e.g., KEK → DEK derivation in NEMESIS).

Parameters:

  • masterKey: The input keying material (IKM), typically 32 bytes
  • salt: Optional salt value (can be nil), used for key strengthening
  • info: Optional context/application info (can be nil), prevents key reuse across contexts
  • keyLen: Length of output key in bytes (typically 32 for AES-256)

Example:

masterKey := []byte("my-32-byte-master-key-for-nemesis")
dek, err := crypto.DeriveKeyHKDF(masterKey, nil, []byte("nemesis-dek-v1"), 32)
if err != nil {
    log.Fatal(err)
}

Security: HKDF is designed for high-entropy inputs (like randomly generated keys). For password-based key derivation, use DeriveKey() with Argon2id instead.

func DeriveKeyHKDFDefault

func DeriveKeyHKDFDefault(masterKey []byte, keyLen int) ([]byte, error)

DeriveKeyHKDFDefault derives a key using HKDF-SHA256 with sensible defaults. Uses empty salt and info, suitable for simple key derivation scenarios.

Parameters:

  • masterKey: The input keying material (32+ bytes recommended)
  • keyLen: Length of output key in bytes (typically 32)

Example:

dek, err := crypto.DeriveKeyHKDFDefault(kek, 32)

func DeriveKeyPBKDF2 deprecated

func DeriveKeyPBKDF2(password, salt []byte, iterations, keyLen int) ([]byte, error)

DeriveKeyPBKDF2 derives a key using PBKDF2-SHA256 (deprecated).

This function is deprecated and kept only for backward compatibility. Use DeriveKey with Argon2id instead for better security against modern attacks. This function will be removed in a future version.

Parameters:

  • password: The password to derive the key from (cannot be empty)
  • salt: The salt to use for key derivation (cannot be empty, should be random)
  • iterations: The number of iterations (must be positive, recommend at least 100,000)
  • keyLen: The desired length of the derived key in bytes (must be positive)

Returns:

  • The derived key as a byte slice
  • An error if key derivation fails

Example:

password := []byte("my-secure-password")
salt := []byte("random-salt-123")
key, err := crypto.DeriveKeyPBKDF2(password, salt, 100000, 32)
if err != nil {
	log.Fatal(err)
}

Deprecated: Use DeriveKey instead for better security.

func DeriveKeyWithParams

func DeriveKeyWithParams(password, salt []byte, time, memoryMB, threads, keyLen int) ([]byte, error)

DeriveKeyWithParams derives a key from a password and salt using Argon2id with custom parameters.

This is a legacy function that provides direct parameter control. For new code, consider using DeriveKey with a KDFParams struct for better readability and maintainability.

Parameters:

  • password: The password to derive the key from (cannot be empty)
  • salt: The salt to use for key derivation (cannot be empty, should be random)
  • time: The number of iterations (must be positive)
  • memoryMB: The memory usage in MB (must be positive)
  • threads: The number of threads (must be positive)
  • keyLen: The desired length of the derived key in bytes (must be positive)

Returns:

  • The derived key as a byte slice
  • An error if key derivation fails

Example:

password := []byte("my-secure-password")
salt := []byte("random-salt-123")
key, err := crypto.DeriveKeyWithParams(password, salt, 4, 128, 2, 32)
if err != nil {
	log.Fatal(err)
}

Use this function only if you need to customize the parameters for specific requirements.

func Encrypt

func Encrypt(plaintext string, key []byte) (string, error)

Encrypt encrypts a plaintext string using AES-256-GCM authenticated encryption.

This is a convenience wrapper around EncryptBytes that works with strings. The function uses AES-256 in GCM mode, which provides both confidentiality and authenticity. The returned string is base64-encoded and contains the nonce, ciphertext, and authentication tag.

Parameters:

  • plaintext: The string to encrypt (can be empty)
  • key: The 32-byte encryption key (must be exactly KeySize bytes)

Returns:

  • A base64-encoded string containing the encrypted data
  • An error if encryption fails

Example:

key, _ := crypto.GenerateKey()
ciphertext, err := crypto.Encrypt("sensitive data", key)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Encrypted:", ciphertext)

Empty plaintext is supported and will result in a valid ciphertext containing only the nonce and authentication tag.

func EncryptBytes

func EncryptBytes(plaintext []byte, key []byte) (string, error)

EncryptBytes encrypts a plaintext byte slice using AES-256-GCM authenticated encryption.

The function uses AES-256 in GCM mode, which provides both confidentiality and authenticity. The returned string is base64-encoded and contains the nonce, ciphertext, and authentication tag. This is the core encryption function that works with binary data with buffer pooling optimization.

Parameters:

  • plaintext: The byte slice to encrypt (can be empty)
  • key: The 32-byte encryption key (must be exactly KeySize bytes)

Returns:

  • A base64-encoded string containing the encrypted data
  • An error if encryption fails

Example:

key, _ := crypto.GenerateKey()
data := []byte("sensitive binary data")
ciphertext, err := crypto.EncryptBytes(data, key)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Encrypted:", ciphertext)

Empty plaintext is supported and will result in a valid ciphertext containing only the nonce and authentication tag.

func EncryptBytesWithAAD

func EncryptBytesWithAAD(plaintext []byte, key []byte, aad []byte) (string, error)

EncryptBytesWithAAD encrypts a plaintext byte slice using AES-256-GCM with Additional Authenticated Data.

This function is designed for NEMESIS vault requirements where AAD contains metadata like {tenant, path, version, KeyID} for authenticated encryption with context binding.

Parameters:

  • plaintext: The byte slice to encrypt (can be empty)
  • key: The 32-byte encryption key (must be exactly KeySize bytes)
  • aad: Additional Authenticated Data (authenticated but not encrypted)

Returns:

  • A base64-encoded string containing the encrypted data
  • An error if encryption fails

Example for NEMESIS:

key, _ := crypto.GenerateKey()
aad := []byte(`{"tenant":"app","path":"/db/pass","version":1,"keyID":"kek_abc123"}`)
ciphertext, err := crypto.EncryptBytesWithAAD(secretData, key, aad)

func EncryptWithAAD

func EncryptWithAAD(plaintext string, key []byte, aad string) (string, error)

EncryptWithAAD encrypts a plaintext string using AES-256-GCM with Additional Authenticated Data.

This is a convenience wrapper around EncryptBytesWithAAD that works with strings. Designed for NEMESIS vault requirements where AAD contains metadata for context binding.

Parameters:

  • plaintext: The string to encrypt (can be empty)
  • key: The 32-byte encryption key (must be exactly KeySize bytes)
  • aad: Additional Authenticated Data as string (authenticated but not encrypted)

Returns:

  • A base64-encoded string containing the encrypted data
  • An error if encryption fails

Example for NEMESIS:

key, _ := crypto.GenerateKey()
aad := `{"tenant":"app","path":"/db/pass","version":1,"keyID":"kek_abc123"}`
ciphertext, err := crypto.EncryptWithAAD("secret-password", key, aad)

func GenerateKey

func GenerateKey() ([]byte, error)

GenerateKey generates a cryptographically secure random key of KeySize bytes.

This function creates a new 32-byte (256-bit) key suitable for AES-256 encryption. The key is generated using the cryptographically secure random number generator provided by the operating system.

Returns:

  • A 32-byte key as a byte slice
  • An error if key generation fails

Example:

key, err := crypto.GenerateKey()
if err != nil {
	log.Fatal(err)
}
fmt.Println("Generated key length:", len(key)) // Output: 32

The generated key is suitable for use with Encrypt and Decrypt functions.

func GenerateNonce

func GenerateNonce(size int) ([]byte, error)

GenerateNonce generates a cryptographically secure random nonce of the given size.

A nonce (number used once) is a random value that should be used only once for each encryption operation. This function generates a cryptographically secure random nonce suitable for use with AES-GCM encryption.

Parameters:

  • size: The desired size of the nonce in bytes (must be positive)

Returns:

  • A byte slice containing the random nonce
  • An error if nonce generation fails

Example:

nonce, err := crypto.GenerateNonce(12) // 12 bytes is standard for AES-GCM
if err != nil {
	log.Fatal(err)
}
fmt.Println("Generated nonce length:", len(nonce)) // Output: 12

For AES-GCM, a 12-byte nonce is recommended for optimal security and performance.

func GetKeyFingerprint

func GetKeyFingerprint(key []byte) string

GetKeyFingerprint generates a fingerprint for a key (non-cryptographic).

This function creates a short, human-readable identifier for a key by computing the SHA-256 hash and taking the first 8 bytes. This provides better collision resistance than using just the first few bytes of the key while maintaining speed.

The fingerprint is useful for logging, debugging, and identifying keys without exposing the actual key material.

Parameters:

  • key: The key to generate a fingerprint for

Returns:

  • A 16-character hexadecimal string representing the fingerprint
  • An empty string if the key is empty

Example:

key, _ := crypto.GenerateKey()
fingerprint := crypto.GetKeyFingerprint(key)
fmt.Println("Key fingerprint:", fingerprint) // e.g., "a1b2c3d4e5f67890"

Uses the first 8 bytes of SHA-256 for better collision resistance while maintaining speed.

func KeyFromBase64

func KeyFromBase64(s string) ([]byte, error)

KeyFromBase64 decodes a base64 string to a key.

This function is the inverse of KeyToBase64 and is useful for loading keys from text-based storage formats like JSON or configuration files.

Parameters:

  • s: The base64-encoded string to decode

Returns:

  • The decoded key as a byte slice
  • An error if the base64 decoding fails

Example:

base64Key := "dGVzdC1rZXktZGF0YS0xMjM0NTY3ODkwYWJjZGVm"
key, err := crypto.KeyFromBase64(base64Key)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Decoded key length:", len(key))

func KeyFromHex

func KeyFromHex(s string) ([]byte, error)

KeyFromHex decodes a hexadecimal string to a key.

This function is the inverse of KeyToHex and is useful for loading keys from hexadecimal representations. The input string can contain both uppercase and lowercase hexadecimal characters.

Parameters:

  • s: The hexadecimal string to decode

Returns:

  • The decoded key as a byte slice
  • An error if the hexadecimal decoding fails

Example:

hexKey := "746573742d6b65792d646174612d31323334353637383930616263646566"
key, err := crypto.KeyFromHex(hexKey)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Decoded key length:", len(key))

func KeyToBase64

func KeyToBase64(key []byte) string

KeyToBase64 encodes a key as a base64 string.

This function is useful for storing keys in text-based formats like JSON or configuration files. The returned string is safe to use in URLs and other text contexts.

Parameters:

  • key: The key to encode (can be any byte slice)

Returns:

  • A base64-encoded string representation of the key

Example:

key, _ := crypto.GenerateKey()
base64Key := crypto.KeyToBase64(key)
fmt.Println("Base64 key:", base64Key)

func KeyToHex

func KeyToHex(key []byte) string

KeyToHex encodes a key as a hexadecimal string.

This function is useful for displaying keys in a human-readable format or storing them in text-based formats. The returned string contains only lowercase hexadecimal characters (0-9, a-f).

Parameters:

  • key: The key to encode (can be any byte slice)

Returns:

  • A hexadecimal string representation of the key

Example:

key, _ := crypto.GenerateKey()
hexKey := crypto.KeyToHex(key)
fmt.Println("Hex key:", hexKey)

func ValidateKey

func ValidateKey(key []byte) error

ValidateKey checks that a key has the correct size for AES-256.

This function verifies that the provided key is exactly 32 bytes (256 bits), which is required for AES-256 encryption. It's useful for validating keys before using them with the Encrypt and Decrypt functions.

Parameters:

  • key: The key to validate

Returns:

  • An error if the key size is incorrect, nil if valid

Example:

key, _ := crypto.GenerateKey()
err := crypto.ValidateKey(key)
if err != nil {
	log.Fatal("Invalid key:", err)
}
fmt.Println("Key is valid for AES-256")

The function will return an error if the key is not exactly 32 bytes.

func WarmupPools

func WarmupPools(count int)

WarmupPools pre allocates buffers in the pools to reduce cold latency

func Zeroize

func Zeroize(b []byte)

Zeroize securely wipes a byte slice from memory.

This function overwrites all bytes in the slice with zeros to prevent sensitive data from remaining in memory after use. This is important for security when dealing with cryptographic keys and other sensitive data.

Note: This function modifies the original slice in place.

Parameters:

  • b: The byte slice to zeroize

Example:

key, _ := crypto.GenerateKey()
// Use the key for encryption/decryption
ciphertext, _ := crypto.Encrypt("data", key)
// Securely wipe the key from memory
crypto.Zeroize(key)

Types

type HSMCapability

type HSMCapability string

HSMCapability represents specific HSM capabilities and features

const (
	// Key Generation Capabilities
	CapabilityGenerateSymmetric  HSMCapability = "generate_symmetric"  // AES, ChaCha20, etc.
	CapabilityGenerateAsymmetric HSMCapability = "generate_asymmetric" // RSA, ECDSA, EdDSA
	CapabilityGenerateEphemeral  HSMCapability = "generate_ephemeral"  // Session keys, temporary keys

	// Cryptographic Operations
	CapabilityEncrypt       HSMCapability = "encrypt"        // Symmetric/Asymmetric encryption
	CapabilityDecrypt       HSMCapability = "decrypt"        // Symmetric/Asymmetric decryption
	CapabilitySign          HSMCapability = "sign"           // Digital signatures
	CapabilityVerify        HSMCapability = "verify"         // Signature verification
	CapabilityKeyDerivation HSMCapability = "key_derivation" // PBKDF2, HKDF, scrypt

	// Advanced Features
	CapabilityKeyWrapping      HSMCapability = "key_wrapping"      // Key encryption keys (KEK)
	CapabilityKeyUnwrapping    HSMCapability = "key_unwrapping"    // KEK decryption
	CapabilityRandomGeneration HSMCapability = "random_generation" // Hardware RNG
	CapabilityKeyRotation      HSMCapability = "key_rotation"      // Automated key rotation
	CapabilityKeyBackup        HSMCapability = "key_backup"        // Key backup/recovery

	// Security Features
	CapabilityTamperEvidence   HSMCapability = "tamper_evidence"    // Tamper detection
	CapabilitySecureKeyStorage HSMCapability = "secure_key_storage" // Hardware-backed storage
	CapabilityAccessControl    HSMCapability = "access_control"     // Role-based access
)

type HSMKeyInfo

type HSMKeyInfo struct {
	ID          string            `json:"id"`          // Unique key identifier in HSM
	Label       string            `json:"label"`       // Human-readable label
	Type        KeyType           `json:"type"`        // Type of cryptographic key
	Usage       []KeyUsage        `json:"usage"`       // Allowed key usage operations
	Size        int               `json:"size"`        // Key size in bits
	Algorithm   string            `json:"algorithm"`   // Cryptographic algorithm
	CreatedAt   time.Time         `json:"created_at"`  // Creation timestamp
	ExpiresAt   *time.Time        `json:"expires_at"`  // Expiration time (if any)
	Extractable bool              `json:"extractable"` // Whether key can be exported
	Metadata    map[string]string `json:"metadata"`    // Additional HSM-specific metadata
}

HSMKeyInfo represents metadata about keys stored in HSM

type HSMManager

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

HSMManager manages multiple HSM providers using the go-plugins framework

func NewHSMManager

func NewHSMManager(config *HSMManagerConfig, pluginManager *goplugins.Manager[HSMRequest, HSMResponse]) (*HSMManager, error)

NewHSMManager creates a new HSM manager with plugin support

func (*HSMManager) Close

func (h *HSMManager) Close() error

Close shuts down all HSM providers

func (*HSMManager) GetProvider

func (h *HSMManager) GetProvider(name string) (HSMProvider, error)

GetProvider returns an HSM provider by name

func (*HSMManager) RegisterProvider

func (h *HSMManager) RegisterProvider(name string, provider HSMProvider) error

RegisterProvider registers an HSM provider with the manager

type HSMManagerConfig

type HSMManagerConfig struct {
	DefaultProvider     string                            `json:"default_provider"`      // Default HSM provider to use
	ProviderConfigs     map[string]map[string]interface{} `json:"provider_configs"`      // Per-provider configurations
	FailoverEnabled     bool                              `json:"failover_enabled"`      // Enable automatic failover
	FailoverProviders   []string                          `json:"failover_providers"`    // Failover provider priority order
	HealthCheckInterval time.Duration                     `json:"health_check_interval"` // Health check frequency
	OperationTimeout    time.Duration                     `json:"operation_timeout"`     // Default operation timeout
}

HSMManagerConfig provides configuration for the HSM manager

type HSMOperationContext

type HSMOperationContext struct {
	Context     context.Context        `json:"-"`            // Go context for cancellation/timeout
	KeyID       string                 `json:"key_id"`       // Key identifier for operation
	Algorithm   string                 `json:"algorithm"`    // Specific algorithm variant
	Parameters  map[string]interface{} `json:"parameters"`   // Algorithm-specific parameters
	Metadata    map[string]string      `json:"metadata"`     // Operation metadata
	UserContext map[string]string      `json:"user_context"` // User/session context
}

HSMOperationContext provides context for HSM operations

type HSMProvider

type HSMProvider interface {
	// Provider Information
	Name() string                  // Provider name (e.g., "pkcs11", "aws-cloudhsm")
	Version() string               // Provider version
	Capabilities() []HSMCapability // Supported capabilities

	// Lifecycle Management
	Initialize(ctx context.Context, config map[string]interface{}) error // Initialize HSM connection
	Close() error                                                        // Clean shutdown and resource cleanup
	IsHealthy() bool                                                     // Health check status

	// Key Management Operations
	GenerateKey(ctx HSMOperationContext, keyType KeyType, usage []KeyUsage, params map[string]interface{}) (*HSMKeyInfo, error)
	ImportKey(ctx HSMOperationContext, keyMaterial []byte, keyType KeyType, usage []KeyUsage, params map[string]interface{}) (*HSMKeyInfo, error)
	DeleteKey(ctx HSMOperationContext) error
	ListKeys(ctx context.Context, filter map[string]interface{}) ([]*HSMKeyInfo, error)
	GetKeyInfo(ctx HSMOperationContext) (*HSMKeyInfo, error)

	// Cryptographic Operations
	Encrypt(ctx HSMOperationContext, plaintext []byte) ([]byte, error)
	Decrypt(ctx HSMOperationContext, ciphertext []byte) ([]byte, error)
	Sign(ctx HSMOperationContext, data []byte, hashAlgorithm crypto.Hash) ([]byte, error)
	Verify(ctx HSMOperationContext, data []byte, signature []byte, hashAlgorithm crypto.Hash) error

	// Key Derivation and Wrapping
	DeriveKey(ctx HSMOperationContext, derivationData []byte, outputKeyType KeyType, params map[string]interface{}) (*HSMKeyInfo, error)
	WrapKey(ctx HSMOperationContext, targetKeyID string, wrappingParams map[string]interface{}) ([]byte, error)
	UnwrapKey(ctx HSMOperationContext, wrappedKey []byte, keyType KeyType, usage []KeyUsage, params map[string]interface{}) (*HSMKeyInfo, error)

	// Random Number Generation
	GenerateRandom(ctx context.Context, length int) ([]byte, error)
}

HSMProvider defines the interface that all HSM plugins must implement

This interface provides a comprehensive set of cryptographic operations that can be performed by Hardware Security Modules. Implementations should handle errors gracefully and provide detailed error information for security auditing.

type HSMRequest

type HSMRequest struct {
	Operation  string                 `json:"operation"`  // Operation type (encrypt, decrypt, sign, etc.)
	Context    HSMOperationContext    `json:"context"`    // Operation context
	Data       []byte                 `json:"data"`       // Operation data
	Parameters map[string]interface{} `json:"parameters"` // Operation parameters
}

HSMRequest represents a request to an HSM provider plugin

type HSMResponse

type HSMResponse struct {
	Success  bool                   `json:"success"`  // Operation success status
	Data     []byte                 `json:"data"`     // Response data
	KeyInfo  *HSMKeyInfo            `json:"key_info"` // Key information (for key operations)
	Error    string                 `json:"error"`    // Error message (if any)
	Metadata map[string]interface{} `json:"metadata"` // Response metadata
}

HSMResponse represents a response from an HSM provider plugin

type KDFParams

type KDFParams struct {
	// Time is the number of iterations for Argon2id.
	// Higher values increase security but also computation time.
	// If zero, DefaultTime is used.
	Time uint32 `json:"time,omitempty"`

	// Memory is the memory usage in MB for Argon2id.
	// Higher values increase security against memory-based attacks.
	// If zero, DefaultMemory is used.
	Memory uint32 `json:"memory,omitempty"`

	// Threads is the number of threads for Argon2id.
	// Should not exceed the number of CPU cores.
	// If zero, DefaultThreads is used.
	Threads uint8 `json:"threads,omitempty"`
}

KDFParams defines custom parameters for Argon2id key derivation.

If a field is zero, the library's secure default will be used. This allows for flexible configuration while maintaining security.

Example:

// Use custom parameters
params := &crypto.KDFParams{
	Time:    4,    // 4 iterations
	Memory:  128,  // 128 MB memory
	Threads: 2,    // 2 threads
}
key, err := crypto.DeriveKey(password, salt, 32, params)

// Use secure defaults (pass nil)
key, err := crypto.DeriveKey(password, salt, 32, nil)

func FastKDFParams

func FastKDFParams() *KDFParams

FastKDFParams returns Argon2id parameters optimized for speed.

These parameters prioritize performance while maintaining acceptable security. Suitable for development, testing, or scenarios where KDF performance is critical and the threat model allows for slightly reduced security margins.

Parameters: Time=1, Memory=32MB, Threads=2

func HighSecurityKDFParams

func HighSecurityKDFParams() *KDFParams

HighSecurityKDFParams returns Argon2id parameters for maximum security scenarios.

These parameters prioritize security over performance and should be used when protecting highly sensitive data or when computational resources are abundant. Recommended for master key derivation or high-value secret encryption.

Parameters: Time=5, Memory=128MB, Threads=4

func NemesisKDFParams

func NemesisKDFParams() *KDFParams

NemesisKDFParams returns Argon2id parameters optimized for NEMESIS vault workloads.

These parameters balance security with performance for high-throughput vault operations while maintaining strong resistance against attacks. Suitable for production NEMESIS deployments with moderate security requirements.

Parameters: Time=2, Memory=64MB, Threads=4

type KeyManager

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

KeyManager manages key rotations for the NEMESIS vault

func NewKeyManager

func NewKeyManager() *KeyManager

NewKeyManager creates a new key manager

func NewKeyManagerWithOptions

func NewKeyManagerWithOptions(maxVersions int) *KeyManager

NewKeyManagerWithOptions creates a key manager with custom options

func (*KeyManager) ActivateKEK

func (km *KeyManager) ActivateKEK(keyID string) error

ActivateKEK activates a KEK as the current key

func (*KeyManager) CommitKEKRotation

func (km *KeyManager) CommitKEKRotation() error

CommitKEKRotation completes the rotation by activating the new KEK Phase 3: Activate the new KEK while keeping the old one available for decrypt

func (*KeyManager) DecryptWithKEK

func (km *KeyManager) DecryptWithKEK(encryptedData string, kekID string) (string, error)

DecryptWithKEK decrypts data using a specific KEK (for backward compatibility)

func (*KeyManager) DeriveDataKey

func (km *KeyManager) DeriveDataKey(context []byte, keyLength int) ([]byte, string, error)

DeriveDataKey derives a DEK (Data Encryption Key) from the current KEK using HKDF

func (*KeyManager) EncryptWithKEK

func (km *KeyManager) EncryptWithKEK(plaintext string, kekID string) (string, error)

EncryptWithKEK encrypts using a specific KEK with cached cipher for optimal performance

func (*KeyManager) ExportKeyMaterial

func (km *KeyManager) ExportKeyMaterial() ([]byte, error)

ExportKeyMaterial exports the keys in a secure format (without the actual keys)

func (*KeyManager) GenerateKEK

func (km *KeyManager) GenerateKEK(purpose string) (*KeyVersion, error)

GenerateKEK generates a new KEK (Key Encryption Key) for NEMESIS

func (*KeyManager) GetCurrentKEK

func (km *KeyManager) GetCurrentKEK() (*KeyVersion, error)

GetCurrentKEK returns the current active KEK

func (*KeyManager) GetKEKByID

func (km *KeyManager) GetKEKByID(keyID string) (*KeyVersion, error)

GetKEKByID returns a specific KEK by ID (for legacy data decryption)

func (*KeyManager) ListKEKs

func (km *KeyManager) ListKEKs() []*KeyVersion

ListKEKs returns all KEKs with their status

func (*KeyManager) PrepareKEKRotation

func (km *KeyManager) PrepareKEKRotation(purpose string) (*KeyVersion, error)

PrepareKEKRotation prepares a new KEK for zero-downtime rotation Phase 1: Generate the new KEK in pending state without impacting the active one

func (*KeyManager) RevokeKEK

func (km *KeyManager) RevokeKEK(keyID string) error

RevokeKEK revokes a specific KEK

func (*KeyManager) RollbackKEKRotation

func (km *KeyManager) RollbackKEKRotation() error

RollbackKEKRotation undoes an ongoing rotation

func (*KeyManager) RotateKEK

func (km *KeyManager) RotateKEK(purpose string) (*KeyVersion, error)

RotateKEK performs a full KEK rotation by generating and activating a new key

func (*KeyManager) RotateKEKZeroDowntime

func (km *KeyManager) RotateKEKZeroDowntime(purpose string) (*KeyVersion, error)

RotateKEKZeroDowntime runs the full zero-downtime KEK rotation process Complete orchestration: prepare -> validate -> commit with automatic rollback on error

func (*KeyManager) ValidateKEKRotation

func (km *KeyManager) ValidateKEKRotation() error

ValidateKEKRotation validates that the new KEK works correctly Phase 2: Test encrypt/decrypt with the new KEK before activating it

type KeyType

type KeyType string

KeyType represents different types of cryptographic keys

const (
	KeyTypeAES256    KeyType = "aes-256"    // 256-bit AES symmetric key
	KeyTypeAES128    KeyType = "aes-128"    // 128-bit AES symmetric key
	KeyTypeChaCha20  KeyType = "chacha20"   // ChaCha20 symmetric key
	KeyTypeRSA2048   KeyType = "rsa-2048"   // 2048-bit RSA key pair
	KeyTypeRSA4096   KeyType = "rsa-4096"   // 4096-bit RSA key pair
	KeyTypeECDSAP256 KeyType = "ecdsa-p256" // ECDSA P-256 key pair
	KeyTypeECDSAP384 KeyType = "ecdsa-p384" // ECDSA P-384 key pair
	KeyTypeEd25519   KeyType = "ed25519"    // Ed25519 key pair
	KeyTypeGeneric   KeyType = "generic"    // Generic key material
)

type KeyUsage

type KeyUsage string

KeyUsage defines how a key can be used

const (
	KeyUsageEncrypt KeyUsage = "encrypt" // Encryption operations
	KeyUsageDecrypt KeyUsage = "decrypt" // Decryption operations
	KeyUsageSign    KeyUsage = "sign"    // Digital signature creation
	KeyUsageVerify  KeyUsage = "verify"  // Signature verification
	KeyUsageWrap    KeyUsage = "wrap"    // Key wrapping (KEK)
	KeyUsageUnwrap  KeyUsage = "unwrap"  // Key unwrapping
	KeyUsageDerive  KeyUsage = "derive"  // Key derivation
	KeyUsageGeneral KeyUsage = "general" // General purpose usage
)

type KeyVersion

type KeyVersion struct {
	ID        string                 `json:"id"`                 // Unique identifier for the key version
	Key       []byte                 `json:"-"`                  // The cryptographic key (not serialized in JSON for security)
	KeyB64    string                 `json:"key,omitempty"`      // Key in base64 for export/import when needed
	Version   int                    `json:"version"`            // Incremental version number
	CreatedAt time.Time              `json:"created_at"`         // Creation timestamp
	Status    string                 `json:"status"`             // "active", "pending", "deprecated", "revoked"
	Algorithm string                 `json:"algorithm"`          // Cryptographic algorithm used
	Purpose   string                 `json:"purpose"`            // Purpose of the key (e.g. "KEK", "DEK", "signature")
	Metadata  map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
	// contains filtered or unexported fields
}

KeyVersion represents a specific version of a cryptographic key

func (*KeyVersion) EncryptBytesWithCachedGCM

func (kv *KeyVersion) EncryptBytesWithCachedGCM(plaintext []byte) (string, error)

EncryptBytesWithCachedGCM encrypts bytes using the cached GCM - core optimization for 500k ops/sec target

func (*KeyVersion) EncryptWithCachedGCM

func (kv *KeyVersion) EncryptWithCachedGCM(plaintext string) (string, error)

EncryptWithCachedGCM encrypts using the cached GCM for optimal performance - eliminates overhead of aes.NewCipher + cipher.NewGCM

type PoolStats

type PoolStats struct {
	SmallBuffers   int
	MediumBuffers  int
	LargeBuffers   int
	DynamicBuffers int
}

PoolStats provides statistics on the pools for performance monitoring

func GetPoolStats

func GetPoolStats() PoolStats

GetPoolStats returns the current statistics of the pools (for debugging/monitoring)

type StreamingDecryptor

type StreamingDecryptor interface {
	// Read decrypts and returns data from the underlying reader.
	// Data is processed in chunks for memory efficiency.
	Read(data []byte) (int, error)

	// Close finalizes the decryption and verifies final authentication.
	// Must be called to ensure data integrity.
	Close() error
}

StreamingDecryptor provides streaming decryption capabilities for large datasets. It decrypts data in chunks while verifying authentication tags.

Example usage:

key, _ := crypto.GenerateKey()
decryptor, _ := crypto.NewStreamingDecryptor(inputReader, key)
defer decryptor.Close()

io.Copy(outputWriter, decryptor) // Decrypts while streaming

Note: Reads header information first to extract nonce and verify format.

func NewStreamingDecryptor

func NewStreamingDecryptor(reader io.Reader, key []byte) (StreamingDecryptor, error)

NewStreamingDecryptor creates a new streaming decryptor.

Parameters:

  • reader: Source reader for encrypted data
  • key: 32-byte AES-256 key for decryption

The decryptor automatically reads the header to extract nonce and chunk size, then provides streaming decryption of the remaining data.

Example:

file, _ := os.Open("encrypted.bin")
key := getKey() // Your 32-byte key
dec, err := crypto.NewStreamingDecryptor(file, key)
if err != nil {
    log.Fatal(err)
}
defer dec.Close()

type StreamingEncryptor

type StreamingEncryptor interface {
	// Write encrypts and writes data to the underlying writer.
	// Data is processed in chunks for memory efficiency.
	Write(data []byte) (int, error)

	// Close finalizes the encryption and writes any remaining data.
	// Must be called to ensure data integrity.
	Close() error
}

StreamingEncryptor provides streaming encryption capabilities for large datasets. It encrypts data in chunks while maintaining the security guarantees of AES-GCM.

Example usage:

key, _ := crypto.GenerateKey()
encryptor, _ := crypto.NewStreamingEncryptor(outputWriter, key)
defer encryptor.Close()

io.Copy(encryptor, inputReader) // Encrypts while streaming

Note: The output format includes a header with nonce and authentication data.

func NewStreamingEncryptor

func NewStreamingEncryptor(writer io.Writer, key []byte) (StreamingEncryptor, error)

NewStreamingEncryptor creates a new streaming encryptor with default chunk size.

Parameters:

  • writer: Destination writer for encrypted data
  • key: 32-byte AES-256 key for encryption

Returns a StreamingEncryptor that encrypts data in chunks while maintaining AES-GCM security guarantees. The encrypted stream includes a header with metadata required for decryption.

Example:

file, _ := os.Create("encrypted.bin")
key, _ := crypto.GenerateKey()
enc, err := crypto.NewStreamingEncryptor(file, key)
if err != nil {
    log.Fatal(err)
}
defer enc.Close()

func NewStreamingEncryptorWithChunkSize

func NewStreamingEncryptorWithChunkSize(writer io.Writer, key []byte, chunkSize int) (StreamingEncryptor, error)

NewStreamingEncryptorWithChunkSize creates a streaming encryptor with custom chunk size.

Parameters:

  • writer: Destination writer for encrypted data
  • key: 32-byte AES-256 key for encryption
  • chunkSize: Size of each encrypted chunk (recommended: 64KB-1MB)

Smaller chunks use less memory but have more overhead. Larger chunks are more efficient but use more memory.

Jump to

Keyboard shortcuts

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