keystore

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 24 Imported by: 0

README

Secure Key Storage Solution

This package provides a secure storage solution for cryptographic keys and sensitive materials. It supports various key types, protection levels, and operations for managing cryptographic keys throughout their lifecycle.

Features

  • Multiple Key Types: Support for RSA, ECDSA, Ed25519, and symmetric keys
  • Key Usage Definitions: Define keys for signing, encryption, authentication, and TLS
  • Protection Levels: Software-based protection with extensibility for HSM integration
  • Key Management: Store, retrieve, delete, and list keys with rich metadata
  • Key Rotation: Automatic key rotation based on configurable policies
  • Key Export/Import: Export and import keys in various formats (PEM, DER)
  • Type-Specific Operations: Retrieve keys in their native Go cryptographic types

Usage

Creating a Key Store
import (
    "time"
    "github.com/perplext/LLMrecon/src/security/keystore"
)

// Create key store options
options := keystore.KeyStoreOptions{
    StoragePath:           "/path/to/keystore.json",
    Passphrase:            "secure-passphrase",
    AutoSave:              true,
    RotationCheckInterval: time.Hour * 24, // Check for rotation daily
    AlertCallback: func(key *keystore.KeyMetadata, daysUntilExpiration int) {
        log.Printf("Key %s (%s) will expire in %d days", key.Name, key.ID, daysUntilExpiration)
    },
}

// Create key store
ks, err := keystore.NewFileKeyStore(options)
if err != nil {
    log.Fatalf("Failed to create key store: %v", err)
}
defer ks.Close()
Generating Keys
// Generate RSA key
rsaMetadata := &keystore.KeyMetadata{
    Name:            "my-rsa-signing-key",
    Type:            keystore.RSAKey,
    Usage:           keystore.SigningKey,
    ProtectionLevel: keystore.SoftwareProtection,
    Algorithm:       "RSA-2048",
    Tags:            []string{"application", "signing"},
    Description:     "RSA signing key for application",
    RotationPeriod:  90, // 90 days
}

rsaKey, err := ks.GenerateKey(keystore.RSAKey, "RSA-2048", rsaMetadata)
if err != nil {
    log.Fatalf("Failed to generate RSA key: %v", err)
}

// Generate ECDSA key
ecdsaMetadata := &keystore.KeyMetadata{
    Name:            "my-ecdsa-signing-key",
    Type:            keystore.ECDSAKey,
    Usage:           keystore.SigningKey,
    ProtectionLevel: keystore.SoftwareProtection,
    Algorithm:       "ECDSA-P256",
    Tags:            []string{"application", "signing"},
    Description:     "ECDSA signing key for application",
    RotationPeriod:  90, // 90 days
}

ecdsaKey, err := ks.GenerateKey(keystore.ECDSAKey, "ECDSA-P256", ecdsaMetadata)
if err != nil {
    log.Fatalf("Failed to generate ECDSA key: %v", err)
}

// Generate symmetric key
symmetricMetadata := &keystore.KeyMetadata{
    Name:            "my-encryption-key",
    Type:            keystore.SymmetricKey,
    Usage:           keystore.EncryptionKey,
    ProtectionLevel: keystore.SoftwareProtection,
    Algorithm:       "AES-256",
    Tags:            []string{"application", "encryption"},
    Description:     "Symmetric encryption key",
    RotationPeriod:  30, // 30 days
}

symmetricKey, err := ks.GenerateKey(keystore.SymmetricKey, "AES-256", symmetricMetadata)
if err != nil {
    log.Fatalf("Failed to generate symmetric key: %v", err)
}
Retrieving Keys
// Get key by ID
key, err := ks.GetKey("key-id")
if err != nil {
    log.Fatalf("Failed to get key: %v", err)
}

// Get key metadata only
metadata, err := ks.GetKeyMetadata("key-id")
if err != nil {
    log.Fatalf("Failed to get key metadata: %v", err)
}

// Get RSA private key
rsaPrivateKey, err := ks.GetRSAPrivateKey("key-id")
if err != nil {
    log.Fatalf("Failed to get RSA private key: %v", err)
}

// Get RSA public key
rsaPublicKey, err := ks.GetRSAPublicKey("key-id")
if err != nil {
    log.Fatalf("Failed to get RSA public key: %v", err)
}

// Get ECDSA private key
ecdsaPrivateKey, err := ks.GetECDSAPrivateKey("key-id")
if err != nil {
    log.Fatalf("Failed to get ECDSA private key: %v", err)
}

// Get ECDSA public key
ecdsaPublicKey, err := ks.GetECDSAPublicKey("key-id")
if err != nil {
    log.Fatalf("Failed to get ECDSA public key: %v", err)
}

// Get Ed25519 private key
ed25519PrivateKey, err := ks.GetEd25519PrivateKey("key-id")
if err != nil {
    log.Fatalf("Failed to get Ed25519 private key: %v", err)
}

// Get Ed25519 public key
ed25519PublicKey, err := ks.GetEd25519PublicKey("key-id")
if err != nil {
    log.Fatalf("Failed to get Ed25519 public key: %v", err)
}
Listing Keys
// List all keys
keys, err := ks.ListKeys()
if err != nil {
    log.Fatalf("Failed to list keys: %v", err)
}

// List keys by type
rsaKeys, err := ks.ListKeysByType(keystore.RSAKey)
if err != nil {
    log.Fatalf("Failed to list RSA keys: %v", err)
}

// List keys by usage
signingKeys, err := ks.ListKeysByUsage(keystore.SigningKey)
if err != nil {
    log.Fatalf("Failed to list signing keys: %v", err)
}

// List keys by tag
appKeys, err := ks.ListKeysByTag("application")
if err != nil {
    log.Fatalf("Failed to list application keys: %v", err)
}
Key Rotation
// Rotate a key
newKey, err := ks.RotateKey("key-id")
if err != nil {
    log.Fatalf("Failed to rotate key: %v", err)
}
Key Export and Import
// Export a key in PEM format (public key only)
pemData, err := ks.ExportKey("key-id", "PEM", false)
if err != nil {
    log.Fatalf("Failed to export key: %v", err)
}

// Export a key in DER format (with private key)
derData, err := ks.ExportKey("key-id", "DER", true)
if err != nil {
    log.Fatalf("Failed to export key: %v", err)
}

// Import a key from PEM format
importMetadata := &keystore.KeyMetadata{
    Name:            "imported-key",
    Type:            keystore.RSAKey,
    Usage:           keystore.SigningKey,
    ProtectionLevel: keystore.SoftwareProtection,
    Tags:            []string{"imported"},
    Description:     "Imported key",
    RotationPeriod:  90, // 90 days
}

importedKey, err := ks.ImportKey(pemData, "PEM", importMetadata)
if err != nil {
    log.Fatalf("Failed to import key: %v", err)
}
Key Deletion
// Delete a key
err := ks.DeleteKey("key-id")
if err != nil {
    log.Fatalf("Failed to delete key: %v", err)
}

Security Considerations

  1. Passphrase Protection: The key store is protected by a passphrase. Choose a strong, high-entropy passphrase.
  2. Key Rotation: Regularly rotate keys according to your security policy. The RotationPeriod in key metadata defines how often keys should be rotated.
  3. Access Control: Implement appropriate access controls to restrict who can access the key store.
  4. Audit Logging: Enable audit logging to track key operations.
  5. Backup: Regularly back up your key store to prevent data loss.
  6. HSM Integration: For high-security environments, consider using hardware security modules (HSMs) for key protection.

Environment Compatibility

The key storage solution is designed to work across different environments:

  • Development
  • Testing
  • Production

Configuration options can be adjusted based on the environment to balance security and usability.

Integration with Other Components

This key storage solution integrates with:

  • The vault package for secure credential management
  • The crypto package for cryptographic operations
  • The x509 package for certificate handling

Example

See the examples directory for a complete example of how to use the key storage solution.

Documentation

Overview

Package keystore provides secure storage for cryptographic keys and sensitive materials.

Package keystore provides secure storage for cryptographic keys and sensitive materials.

Package keystore provides secure storage for cryptographic keys and sensitive materials.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ExportFormat added in v0.8.0

type ExportFormat string

ExportFormat represents the format for key export

const (
	FormatPEM    ExportFormat = "pem"
	FormatJSON   ExportFormat = "json"
	FormatBinary ExportFormat = "binary"
)

type ExportedKey added in v0.8.0

type ExportedKey struct {
	ID          string            `json:"id"`
	Type        KeyType           `json:"type"`
	Algorithm   string            `json:"algorithm"`
	Data        string            `json:"data"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	CreatedAt   time.Time         `json:"created_at"`
	ExportedAt  time.Time         `json:"exported_at"`
	Expiration  *time.Time        `json:"expiration,omitempty"`
	Fingerprint string            `json:"fingerprint"`
}

ExportedKey represents an exported key with metadata

type FileKeyStore

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

FileKeyStore implements the KeyStore interface with file-based storage

func NewFileKeyStore

func NewFileKeyStore(options KeyStoreOptions) (*FileKeyStore, error)

NewFileKeyStore creates a new file-based key store

func (*FileKeyStore) Close

func (ks *FileKeyStore) Close() error

Close closes the key store

func (*FileKeyStore) DeleteKey

func (ks *FileKeyStore) DeleteKey(id string) error

DeleteKey deletes a key by ID

func (*FileKeyStore) ExportKey

func (ks *FileKeyStore) ExportKey(id string, format string, includePrivate bool) ([]byte, error)

ExportKey exports a key in the specified format

func (*FileKeyStore) GenerateKey

func (ks *FileKeyStore) GenerateKey(keyType KeyType, algorithm string, metadata *KeyMetadata) (*Key, error)

GenerateKey generates a new key with the specified parameters

func (*FileKeyStore) GetCertificate

func (ks *FileKeyStore) GetCertificate(id string) (*x509.Certificate, error)

GetCertificate gets a certificate by ID

func (*FileKeyStore) GetECDSAPrivateKey

func (ks *FileKeyStore) GetECDSAPrivateKey(id string) (*ecdsa.PrivateKey, error)

GetECDSAPrivateKey gets an ECDSA private key by ID

func (*FileKeyStore) GetECDSAPublicKey

func (ks *FileKeyStore) GetECDSAPublicKey(id string) (*ecdsa.PublicKey, error)

GetECDSAPublicKey gets an ECDSA public key by ID

func (*FileKeyStore) GetEd25519PrivateKey

func (ks *FileKeyStore) GetEd25519PrivateKey(id string) (ed25519.PrivateKey, error)

GetEd25519PrivateKey gets an Ed25519 private key by ID

func (*FileKeyStore) GetEd25519PublicKey

func (ks *FileKeyStore) GetEd25519PublicKey(id string) (ed25519.PublicKey, error)

GetEd25519PublicKey gets an Ed25519 public key by ID

func (*FileKeyStore) GetKey

func (ks *FileKeyStore) GetKey(id string) (*Key, error)

GetKey retrieves a key by ID

func (*FileKeyStore) GetKeyMetadata

func (ks *FileKeyStore) GetKeyMetadata(id string) (*KeyMetadata, error)

GetKeyMetadata retrieves key metadata by ID

func (*FileKeyStore) GetRSAPrivateKey

func (ks *FileKeyStore) GetRSAPrivateKey(id string) (*rsa.PrivateKey, error)

GetRSAPrivateKey gets an RSA private key by ID

func (*FileKeyStore) GetRSAPublicKey

func (ks *FileKeyStore) GetRSAPublicKey(id string) (*rsa.PublicKey, error)

GetRSAPublicKey gets an RSA public key by ID

func (*FileKeyStore) ImportKey

func (ks *FileKeyStore) ImportKey(keyData []byte, format string, metadata *KeyMetadata) (*Key, error)

ImportKey imports a key from the specified format

func (*FileKeyStore) ListKeys

func (ks *FileKeyStore) ListKeys() ([]*KeyMetadata, error)

ListKeys lists all keys in the key store

func (*FileKeyStore) ListKeysByTag

func (ks *FileKeyStore) ListKeysByTag(tag string) ([]*KeyMetadata, error)

ListKeysByTag lists keys with a specific tag

func (*FileKeyStore) ListKeysByType

func (ks *FileKeyStore) ListKeysByType(keyType KeyType) ([]*KeyMetadata, error)

ListKeysByType lists keys of a specific type

func (*FileKeyStore) ListKeysByUsage

func (ks *FileKeyStore) ListKeysByUsage(usage KeyUsage) ([]*KeyMetadata, error)

ListKeysByUsage lists keys with a specific usage

func (*FileKeyStore) RotateKey

func (ks *FileKeyStore) RotateKey(id string) (*Key, error)

RotateKey rotates a key by generating a new key and updating references

func (*FileKeyStore) StoreKey

func (ks *FileKeyStore) StoreKey(key *Key) error

StoreKey stores a key in the key store

type HSMConfig

type HSMConfig struct {
	// Enabled indicates whether HSM integration is enabled
	Enabled bool

	// Provider is the HSM provider (e.g., "pkcs11", "cng", "kms")
	Provider string

	// LibraryPath is the path to the HSM library
	LibraryPath string

	// SlotID is the HSM slot ID
	SlotID uint

	// TokenLabel is the HSM token label
	TokenLabel string

	// PIN is the HSM PIN
	PIN string

	// KeyLabel is the prefix for key labels in the HSM
	KeyLabel string
}

HSMConfig contains configuration for HSM integration

type HSMManager

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

HSMManager provides integration with Hardware Security Modules

func NewHSMManager

func NewHSMManager(config HSMConfig) (*HSMManager, error)

NewHSMManager creates a new HSM manager

func (*HSMManager) Close

func (m *HSMManager) Close() error

Close closes the HSM manager

func (*HSMManager) DeleteKey

func (m *HSMManager) DeleteKey(id string) error

DeleteKey deletes a key from the HSM

func (*HSMManager) ExportKey

func (m *HSMManager) ExportKey(id string, format string, includePrivate bool) ([]byte, error)

ExportKey exports a key from the HSM (if allowed)

func (*HSMManager) GetECDSAPrivateKey

func (m *HSMManager) GetECDSAPrivateKey(id string) (*ecdsa.PrivateKey, error)

GetECDSAPrivateKey gets an ECDSA private key from the HSM

func (*HSMManager) GetECDSAPublicKey

func (m *HSMManager) GetECDSAPublicKey(id string) (*ecdsa.PublicKey, error)

GetECDSAPublicKey gets an ECDSA public key from the HSM

func (*HSMManager) GetEd25519PrivateKey

func (m *HSMManager) GetEd25519PrivateKey(id string) (ed25519.PrivateKey, error)

GetEd25519PrivateKey gets an Ed25519 private key from the HSM

func (*HSMManager) GetEd25519PublicKey

func (m *HSMManager) GetEd25519PublicKey(id string) (ed25519.PublicKey, error)

GetEd25519PublicKey gets an Ed25519 public key from the HSM

func (*HSMManager) GetKey

func (m *HSMManager) GetKey(id string) (*Key, error)

GetKey retrieves a key from the HSM

func (*HSMManager) GetRSAPrivateKey

func (m *HSMManager) GetRSAPrivateKey(id string) (*rsa.PrivateKey, error)

GetRSAPrivateKey gets an RSA private key from the HSM

func (*HSMManager) GetRSAPublicKey

func (m *HSMManager) GetRSAPublicKey(id string) (*rsa.PublicKey, error)

GetRSAPublicKey gets an RSA public key from the HSM

func (*HSMManager) ImportKey

func (m *HSMManager) ImportKey(keyData []byte, format string, metadata *KeyMetadata) (*Key, error)

ImportKey imports a key into the HSM

func (*HSMManager) StoreKey

func (m *HSMManager) StoreKey(key *Key) error

StoreKey stores a key in the HSM

type Key

type Key struct {
	// Metadata contains metadata about the key
	Metadata KeyMetadata `json:"metadata"`
	// Material contains the actual key material
	Material KeyMaterial `json:"material,omitempty"`
}

Key represents a cryptographic key with its metadata

type KeyEntry added in v0.8.0

type KeyEntry struct {
	// ID is a unique identifier for the key
	ID string `json:"id"`
	// Type is the type of key
	Type KeyType `json:"type"`
	// Algorithm is the algorithm used by the key
	Algorithm string `json:"algorithm"`
	// Key is the actual key material
	Key interface{} `json:"key"`
	// Metadata contains additional key metadata
	Metadata map[string]string `json:"metadata"`
	// CreatedAt is when the key was created
	CreatedAt time.Time `json:"created_at"`
	// UpdatedAt is when the key was last updated
	UpdatedAt time.Time `json:"updated_at"`
}

KeyEntry represents a key entry in the keystore

type KeyExportOptions added in v0.8.0

type KeyExportOptions struct {
	Format     ExportFormat `json:"format"`
	Password   string       `json:"password,omitempty"`
	Encrypted  bool         `json:"encrypted"`
	Metadata   bool         `json:"metadata"`
	Expiration *time.Time   `json:"expiration,omitempty"`
}

KeyExportOptions contains options for key export

type KeyExporter added in v0.8.0

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

KeyExporter handles key export operations

func NewKeyExporter added in v0.8.0

func NewKeyExporter(ks *Keystore) *KeyExporter

NewKeyExporter creates a new key exporter

func (*KeyExporter) ExportKey added in v0.8.0

func (ke *KeyExporter) ExportKey(keyID string, opts KeyExportOptions) (*ExportedKey, error)

ExportKey exports a key with the specified options

type KeyFilter added in v0.8.0

type KeyFilter struct {
	Types         []KeyType         `json:"types,omitempty"`
	Algorithms    []string          `json:"algorithms,omitempty"`
	Metadata      map[string]string `json:"metadata,omitempty"`
	CreatedAfter  *time.Time        `json:"created_after,omitempty"`
	CreatedBefore *time.Time        `json:"created_before,omitempty"`
	UpdatedAfter  *time.Time        `json:"updated_after,omitempty"`
	UpdatedBefore *time.Time        `json:"updated_before,omitempty"`
	Active        *bool             `json:"active,omitempty"`
}

KeyFilter represents filters for key retrieval

type KeyImportOptions added in v0.8.0

type KeyImportOptions struct {
	Format      ExportFormat `json:"format"`
	Password    string       `json:"password,omitempty"`
	ValidateKey bool         `json:"validate_key"`
	Overwrite   bool         `json:"overwrite"`
}

KeyImportOptions contains options for key import

type KeyImporter added in v0.8.0

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

KeyImporter handles key import operations

func NewKeyImporter added in v0.8.0

func NewKeyImporter(ks *Keystore) *KeyImporter

NewKeyImporter creates a new key importer

func (*KeyImporter) ImportKey added in v0.8.0

func (ki *KeyImporter) ImportKey(exportedKey *ExportedKey, opts KeyImportOptions) error

ImportKey imports a key from exported data

type KeyListResult added in v0.8.0

type KeyListResult struct {
	Keys    []*KeyEntry `json:"keys"`
	Total   int         `json:"total"`
	Limit   int         `json:"limit"`
	Offset  int         `json:"offset"`
	HasMore bool        `json:"has_more"`
}

KeyListResult represents the result of a key list operation

type KeyMaterial

type KeyMaterial struct {
	// Private contains the private key data
	Private []byte `json:"private,omitempty"`
	// Public contains the public key data
	Public []byte `json:"public,omitempty"`
	// Certificate contains the certificate data (if applicable)
	Certificate []byte `json:"certificate,omitempty"`
	// Format is the format of the key data (e.g., "PEM", "DER")
	Format string `json:"format"`
}

KeyMaterial contains the actual key material

type KeyMetadata

type KeyMetadata struct {
	// ID is a unique identifier for the key
	ID string `json:"id"`
	// Name is a human-readable name for the key
	Name string `json:"name"`
	// Type is the type of key
	Type KeyType `json:"type"`
	// Usage is the intended usage of the key
	Usage KeyUsage `json:"usage"`
	// ProtectionLevel is the level of protection for the key
	ProtectionLevel KeyProtectionLevel `json:"protection_level"`
	// Algorithm is the specific algorithm (e.g., "RSA-2048", "ECDSA-P256")
	Algorithm string `json:"algorithm"`
	// HasPrivateKey indicates whether a private key is available
	HasPrivateKey bool `json:"has_private_key"`
	// HasPublicKey indicates whether a public key is available
	HasPublicKey bool `json:"has_public_key"`
	// Tags are optional tags for organizing keys
	Tags []string `json:"tags,omitempty"`
	// Description is an optional description of the key
	Description string `json:"description,omitempty"`
	// CreatedAt is when the key was created
	CreatedAt time.Time `json:"created_at"`
	// UpdatedAt is when the key was last updated
	UpdatedAt time.Time `json:"updated_at"`
	// ExpiresAt is when the key expires (if applicable)
	ExpiresAt time.Time `json:"expires_at,omitempty"`
	// LastUsedAt is when the key was last used
	LastUsedAt time.Time `json:"last_used_at,omitempty"`
	// LastRotatedAt is when the key was last rotated
	LastRotatedAt time.Time `json:"last_rotated_at,omitempty"`
	// RotationPeriod is the recommended rotation period in days
	RotationPeriod int `json:"rotation_period,omitempty"`
	// Fingerprint is a unique fingerprint of the key
	Fingerprint string `json:"fingerprint,omitempty"`
}

KeyMetadata contains metadata about a key

type KeyProtectionLevel

type KeyProtectionLevel string

KeyProtectionLevel represents the level of protection for a key

const (
	// SoftwareProtection represents software-based protection
	SoftwareProtection KeyProtectionLevel = "software"
	// HSMProtection represents hardware security module protection
	HSMProtection KeyProtectionLevel = "hsm"
	// TPMProtection represents TPM-based protection
	TPMProtection KeyProtectionLevel = "tpm"
	// SecureEnclaveProtection represents secure enclave protection
	SecureEnclaveProtection KeyProtectionLevel = "secure_enclave"
)

type KeyRetriever added in v0.8.0

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

KeyRetriever handles key retrieval operations

func NewKeyRetriever added in v0.8.0

func NewKeyRetriever(ks *Keystore) *KeyRetriever

NewKeyRetriever creates a new key retriever

func (*KeyRetriever) FindKeysByAlgorithm added in v0.8.0

func (kr *KeyRetriever) FindKeysByAlgorithm(algorithm string) ([]*KeyEntry, error)

FindKeysByAlgorithm retrieves keys by their algorithm

func (*KeyRetriever) FindKeysByMetadata added in v0.8.0

func (kr *KeyRetriever) FindKeysByMetadata(metadata map[string]string) ([]*KeyEntry, error)

FindKeysByMetadata retrieves keys that match the specified metadata

func (*KeyRetriever) FindKeysByType added in v0.8.0

func (kr *KeyRetriever) FindKeysByType(keyType KeyType) ([]*KeyEntry, error)

FindKeysByType retrieves keys by their type

func (*KeyRetriever) FindKeysCreatedAfter added in v0.8.0

func (kr *KeyRetriever) FindKeysCreatedAfter(after time.Time) ([]*KeyEntry, error)

FindKeysCreatedAfter retrieves keys created after the specified time

func (*KeyRetriever) GetKey added in v0.8.0

func (kr *KeyRetriever) GetKey(keyID string) (*KeyEntry, error)

GetKey retrieves a key by its ID

func (*KeyRetriever) GetKeyCount added in v0.8.0

func (kr *KeyRetriever) GetKeyCount() int

GetKeyCount returns the total number of keys in the keystore

func (*KeyRetriever) GetKeyIDs added in v0.8.0

func (kr *KeyRetriever) GetKeyIDs() []string

GetKeyIDs returns all key IDs in the keystore

func (*KeyRetriever) GetKeyStatistics added in v0.8.0

func (kr *KeyRetriever) GetKeyStatistics() map[string]interface{}

GetKeyStatistics returns statistics about the keys in the keystore

func (*KeyRetriever) GetKeys added in v0.8.0

func (kr *KeyRetriever) GetKeys(keyIDs []string) (map[string]*KeyEntry, error)

GetKeys retrieves multiple keys by their IDs

func (*KeyRetriever) KeyExists added in v0.8.0

func (kr *KeyRetriever) KeyExists(keyID string) bool

KeyExists checks if a key with the specified ID exists

func (*KeyRetriever) ListKeys added in v0.8.0

func (kr *KeyRetriever) ListKeys(options *KeySearchOptions) (*KeyListResult, error)

ListKeys retrieves all keys with optional filtering, sorting, and pagination

func (*KeyRetriever) SearchKeys added in v0.8.0

func (kr *KeyRetriever) SearchKeys(query string) ([]*KeyEntry, error)

SearchKeys performs a text search across key IDs and metadata

type KeyRotationInfo added in v0.8.0

type KeyRotationInfo struct {
	KeyID          string         `json:"key_id"`
	Status         RotationStatus `json:"status"`
	CreatedAt      time.Time      `json:"created_at"`
	LastRotated    *time.Time     `json:"last_rotated"`
	NextRotation   *time.Time     `json:"next_rotation"`
	RotationCount  int            `json:"rotation_count"`
	Policy         RotationPolicy `json:"policy"`
	PreviousKeyIDs []string       `json:"previous_key_ids"`
}

KeyRotationInfo contains information about key rotation

type KeyRotationPolicy

type KeyRotationPolicy struct {
	// Enabled indicates whether automatic rotation is enabled
	Enabled bool

	// IntervalDays is the number of days between rotations
	IntervalDays int

	// LastRotation is the timestamp of the last rotation
	LastRotation time.Time

	// WarningDays is the number of days before expiration to start showing warnings
	WarningDays int
}

KeyRotationPolicy defines when keys should be rotated

type KeyRotator added in v0.8.0

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

KeyRotator handles key rotation operations

func NewKeyRotator added in v0.8.0

func NewKeyRotator(ks *Keystore) *KeyRotator

NewKeyRotator creates a new key rotator

func (*KeyRotator) CheckRotationStatus added in v0.8.0

func (kr *KeyRotator) CheckRotationStatus() map[string]RotationStatus

CheckRotationStatus checks the rotation status of all keys

func (*KeyRotator) GetExpiredKeys added in v0.8.0

func (kr *KeyRotator) GetExpiredKeys() []*KeyRotationInfo

GetExpiredKeys returns keys that have expired

func (*KeyRotator) GetExpiringKeys added in v0.8.0

func (kr *KeyRotator) GetExpiringKeys() []*KeyRotationInfo

GetExpiringKeys returns keys that are approaching expiration

func (*KeyRotator) GetRotationHistory added in v0.8.0

func (kr *KeyRotator) GetRotationHistory() []RotationEvent

GetRotationHistory returns the rotation history

func (*KeyRotator) GetRotationInfo added in v0.8.0

func (kr *KeyRotator) GetRotationInfo(keyID string) (*KeyRotationInfo, error)

GetRotationInfo returns rotation information for a key

func (*KeyRotator) GetRotationPolicy added in v0.8.0

func (kr *KeyRotator) GetRotationPolicy(keyID string) (*RotationPolicy, error)

GetRotationPolicy returns the rotation policy for a key

func (*KeyRotator) RotateAllKeys added in v0.8.0

func (kr *KeyRotator) RotateAllKeys(reason string, rotatedBy string) error

RotateAllKeys rotates all keys that have rotation policies

func (*KeyRotator) RotateKey added in v0.8.0

func (kr *KeyRotator) RotateKey(keyID string, reason string, rotatedBy string) error

RotateKey manually rotates a key

func (*KeyRotator) SetRotationPolicy added in v0.8.0

func (kr *KeyRotator) SetRotationPolicy(keyID string, policy RotationPolicy) error

SetRotationPolicy sets the rotation policy for a key

func (*KeyRotator) StartAutoRotation added in v0.8.0

func (kr *KeyRotator) StartAutoRotation() error

StartAutoRotation starts the automatic rotation process

func (*KeyRotator) StopAutoRotation added in v0.8.0

func (kr *KeyRotator) StopAutoRotation() error

StopAutoRotation stops the automatic rotation process

type KeySearchOptions added in v0.8.0

type KeySearchOptions struct {
	Query      string             `json:"query"`
	Filter     *KeyFilter         `json:"filter,omitempty"`
	Sort       *SortOptions       `json:"sort,omitempty"`
	Pagination *PaginationOptions `json:"pagination,omitempty"`
}

KeySearchOptions contains options for key searching

type KeyStore

type KeyStore interface {
	// StoreKey stores a key in the key store
	StoreKey(key *Key) error

	// GetKey retrieves a key by ID
	GetKey(id string) (*Key, error)

	// GetKeyMetadata retrieves key metadata by ID
	GetKeyMetadata(id string) (*KeyMetadata, error)

	// DeleteKey deletes a key by ID
	DeleteKey(id string) error

	// ListKeys lists all keys in the key store
	ListKeys() ([]*KeyMetadata, error)

	// ListKeysByType lists keys of a specific type
	ListKeysByType(keyType KeyType) ([]*KeyMetadata, error)

	// ListKeysByUsage lists keys with a specific usage
	ListKeysByUsage(usage KeyUsage) ([]*KeyMetadata, error)

	// ListKeysByTag lists keys with a specific tag
	ListKeysByTag(tag string) ([]*KeyMetadata, error)

	// RotateKey rotates a key by generating a new key and updating references
	RotateKey(id string) (*Key, error)

	// ExportKey exports a key in the specified format
	ExportKey(id string, format string, includePrivate bool) ([]byte, error)

	// ImportKey imports a key from the specified format
	ImportKey(keyData []byte, format string, metadata *KeyMetadata) (*Key, error)

	// GenerateKey generates a new key with the specified parameters
	GenerateKey(keyType KeyType, algorithm string, metadata *KeyMetadata) (*Key, error)

	// GetRSAPrivateKey gets an RSA private key by ID
	GetRSAPrivateKey(id string) (*rsa.PrivateKey, error)

	// GetRSAPublicKey gets an RSA public key by ID
	GetRSAPublicKey(id string) (*rsa.PublicKey, error)

	// GetECDSAPrivateKey gets an ECDSA private key by ID
	GetECDSAPrivateKey(id string) (*ecdsa.PrivateKey, error)

	// GetECDSAPublicKey gets an ECDSA public key by ID
	GetECDSAPublicKey(id string) (*ecdsa.PublicKey, error)

	// GetEd25519PrivateKey gets an Ed25519 private key by ID
	GetEd25519PrivateKey(id string) (ed25519.PrivateKey, error)

	// GetEd25519PublicKey gets an Ed25519 public key by ID
	GetEd25519PublicKey(id string) (ed25519.PublicKey, error)

	// GetCertificate gets a certificate by ID
	GetCertificate(id string) (*x509.Certificate, error)

	// Close closes the key store
	Close() error
}

KeyStore defines the interface for key storage operations

type KeyStoreOptions

type KeyStoreOptions struct {
	// StoragePath is the path to the key store
	StoragePath string

	// Passphrase is used to derive the encryption key
	Passphrase string

	// HSMConfig contains configuration for HSM integration
	HSMConfig *HSMConfig

	// AutoSave determines whether to automatically save after changes
	AutoSave bool

	// RotationCheckInterval is how often to check for keys that need rotation
	RotationCheckInterval time.Duration

	// AlertCallback is called when a key needs rotation
	AlertCallback func(key *KeyMetadata, daysUntilExpiration int)
}

KeyStoreOptions contains options for creating a key store

type KeyType

type KeyType string

KeyType represents the type of cryptographic key

const (
	// RSAKey represents an RSA key
	RSAKey KeyType = "rsa"
	// ECDSAKey represents an ECDSA key
	ECDSAKey KeyType = "ecdsa"
	// Ed25519Key represents an Ed25519 key
	Ed25519Key KeyType = "ed25519"
	// SymmetricKey represents a symmetric key
	SymmetricKey KeyType = "symmetric"
	// CertificateKey represents a certificate with private key
	CertificateKey KeyType = "certificate"

	// Alternative constants used in other files
	KeyTypeRSA KeyType = "rsa"
	KeyTypeAES KeyType = "aes"
)

type KeyUsage

type KeyUsage string

KeyUsage represents the intended usage of a key

const (
	// SigningKey represents a key used for digital signatures
	SigningKey KeyUsage = "signing"
	// EncryptionKey represents a key used for encryption
	EncryptionKey KeyUsage = "encryption"
	// AuthenticationKey represents a key used for authentication
	AuthenticationKey KeyUsage = "authentication"
	// TLSKey represents a key used for TLS
	TLSKey KeyUsage = "tls"
)

type Keystore added in v0.8.0

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

Keystore represents a keystore implementation

type PaginationOptions added in v0.8.0

type PaginationOptions struct {
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

PaginationOptions represents pagination options

type RotationEvent added in v0.8.0

type RotationEvent struct {
	KeyID        string    `json:"key_id"`
	OldKeyID     string    `json:"old_key_id"`
	NewKeyID     string    `json:"new_key_id"`
	RotationType string    `json:"rotation_type"` // "manual", "scheduled", "emergency"
	Timestamp    time.Time `json:"timestamp"`
	Reason       string    `json:"reason"`
	RotatedBy    string    `json:"rotated_by"`
}

RotationEvent represents a key rotation event

type RotationPolicy added in v0.8.0

type RotationPolicy struct {
	MaxAge          time.Duration `json:"max_age"`
	RotationPeriod  time.Duration `json:"rotation_period"`
	AutoRotate      bool          `json:"auto_rotate"`
	NotifyBefore    time.Duration `json:"notify_before"`
	ArchiveOldKeys  bool          `json:"archive_old_keys"`
	MaxArchivedKeys int           `json:"max_archived_keys"`
}

RotationPolicy defines the rotation policy for keys

type RotationStatus added in v0.8.0

type RotationStatus string

RotationStatus represents the rotation status of a key

const (
	StatusActive   RotationStatus = "active"
	StatusExpiring RotationStatus = "expiring"
	StatusExpired  RotationStatus = "expired"
	StatusRotated  RotationStatus = "rotated"
	StatusArchived RotationStatus = "archived"
)

type SortOptions added in v0.8.0

type SortOptions struct {
	Field     string `json:"field"`     // "id", "type", "algorithm", "created_at", "updated_at"
	Direction string `json:"direction"` // "asc", "desc"
}

SortOptions represents sorting options for key retrieval

Directories

Path Synopsis
Example program demonstrating the usage of the keystore package
Example program demonstrating the usage of the keystore package

Jump to

Keyboard shortcuts

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