keystore

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 21 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.

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 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 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 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 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"
)

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"
)

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