encryption

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Encryption constants
	KeySize          = 32     // AES-256
	NonceSize        = 12     // GCM standard nonce size
	TagSize          = 16     // GCM authentication tag size
	SaltSize         = 32     // Salt for PBKDF2
	BlockSize        = 65536  // 64KB blocks
	PBKDF2Iterations = 600000 // OWASP recommended minimum

	// File header constants
	MagicNumber  = "GDBE0001" // GraphDB Encryption v0001
	HeaderSize   = 64
	DEKBlockSize = 256
	FileVersion  = 1
)

Variables

View Source
var (
	ErrInvalidKey           = fmt.Errorf("invalid encryption key")
	ErrInvalidCiphertext    = fmt.Errorf("invalid ciphertext")
	ErrAuthenticationFailed = fmt.Errorf("authentication failed - data may be tampered")
	ErrInvalidHeader        = fmt.Errorf("invalid file header")
	ErrUnsupportedVersion   = fmt.Errorf("unsupported encryption version")
)
View Source
var (
	ErrKeyNotFound       = fmt.Errorf("key not found")
	ErrInvalidKeyVersion = fmt.Errorf("invalid key version")
	ErrKeyAlreadyExists  = fmt.Errorf("key already exists")
	ErrNoActiveKey       = fmt.Errorf("no active key version")
)

Functions

func GenerateKey

func GenerateKey() ([]byte, error)

GenerateKey generates a cryptographically secure random encryption key

func GenerateSalt

func GenerateSalt() ([]byte, error)

GenerateSalt generates a cryptographically secure random salt

func MarshalDEKBlock

func MarshalDEKBlock(dekBlock *DEKBlock) []byte

MarshalDEKBlock serializes a DEK block to bytes

func MarshalFileHeader

func MarshalFileHeader(header *FileHeader) []byte

MarshalFileHeader serializes a file header to bytes

func ValidateFileHeader

func ValidateFileHeader(header *FileHeader) error

ValidateFileHeader validates an encrypted file header

Types

type DEKBlock

type DEKBlock struct {
	Nonce        [NonceSize]byte // Nonce for DEK encryption
	EncryptedDEK [KeySize]byte   // Encrypted data encryption key
	Tag          [TagSize]byte   // Authentication tag
	Reserved     [196]byte       // Reserved for future use
}

DEKBlock represents the encrypted data encryption key block

func UnmarshalDEKBlock

func UnmarshalDEKBlock(buf []byte) (*DEKBlock, error)

UnmarshalDEKBlock deserializes a DEK block from bytes

type DataBlock

type DataBlock struct {
	Nonce [NonceSize]byte // Unique nonce for this block
	Data  []byte          // Encrypted data + authentication tag
}

DataBlock represents an encrypted data block

type Decrypter

type Decrypter interface {
	// Decrypt decrypts ciphertext and returns plaintext.
	// Returns ErrAuthenticationFailed if the data has been tampered with.
	Decrypt(ciphertext []byte) ([]byte, error)
}

Decrypter is the interface for decryption operations.

type EncryptDecrypter

type EncryptDecrypter interface {
	Encrypter
	Decrypter
}

EncryptDecrypter combines encryption and decryption capabilities. Use this interface when both operations are needed.

type Encrypter

type Encrypter interface {
	// Encrypt encrypts plaintext and returns ciphertext.
	// The returned ciphertext includes any necessary metadata (nonce, tag, etc.)
	Encrypt(plaintext []byte) ([]byte, error)
}

Encrypter is the interface for encryption operations. This interface can be used by packages that need encryption without depending on the concrete Engine implementation.

type Engine

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

Engine provides AES-256-GCM encryption and decryption

func NewEngine

func NewEngine(masterKey []byte) (*Engine, error)

NewEngine creates a new encryption engine with the given master key

func NewEngineFromPassphrase

func NewEngineFromPassphrase(passphrase string, salt []byte) (*Engine, error)

NewEngineFromPassphrase creates an engine with a key derived from a passphrase

func (*Engine) Decrypt

func (e *Engine) Decrypt(ciphertext []byte) ([]byte, error)

Decrypt decrypts ciphertext using AES-256-GCM with the engine's master key Input format: nonce + ciphertext + tag concatenated

func (*Engine) DecryptBlock

func (e *Engine) DecryptBlock(block *DataBlock, dek []byte) ([]byte, error)

DecryptBlock decrypts a data block with a given DEK

func (*Engine) DecryptDEK

func (e *Engine) DecryptDEK(dekBlock *DEKBlock) ([]byte, error)

DecryptDEK decrypts a data encryption key with the master key

func (*Engine) DecryptWithKey

func (e *Engine) DecryptWithKey(ciphertext []byte, key []byte) ([]byte, error)

DecryptWithKey decrypts ciphertext with a specific key Input format: nonce + ciphertext + tag concatenated

func (*Engine) Encrypt

func (e *Engine) Encrypt(plaintext []byte) ([]byte, error)

Encrypt encrypts plaintext using AES-256-GCM with the engine's master key Returns: nonce + ciphertext + tag concatenated

func (*Engine) EncryptBlock

func (e *Engine) EncryptBlock(plaintext []byte, dek []byte) (*DataBlock, error)

EncryptBlock encrypts a data block with a given DEK

func (*Engine) EncryptDEK

func (e *Engine) EncryptDEK(dek []byte) (*DEKBlock, error)

EncryptDEK encrypts a data encryption key with the master key

func (*Engine) EncryptWithKey

func (e *Engine) EncryptWithKey(plaintext []byte, key []byte) ([]byte, error)

EncryptWithKey encrypts plaintext with a specific key Returns: nonce + ciphertext + tag concatenated

func (*Engine) NewStreamDecryptor

func (e *Engine) NewStreamDecryptor(r io.Reader) (*StreamDecryptor, error)

NewStreamDecryptor creates a new streaming decryptor

func (*Engine) NewStreamEncryptor

func (e *Engine) NewStreamEncryptor(w io.Writer, keyVersion uint32) (*StreamEncryptor, error)

NewStreamEncryptor creates a new streaming encryptor

type FileHeader

type FileHeader struct {
	Magic      [8]byte  // Magic number
	Version    uint32   // File format version
	Algorithm  uint32   // Encryption algorithm identifier
	KeyVersion uint32   // Key version for rotation
	Reserved   [44]byte // Reserved for future use
}

FileHeader represents the encrypted file header

func CreateFileHeader

func CreateFileHeader(keyVersion uint32) *FileHeader

CreateFileHeader creates a new encrypted file header

func UnmarshalFileHeader

func UnmarshalFileHeader(buf []byte) (*FileHeader, error)

UnmarshalFileHeader deserializes a file header from bytes

type KeyEntry

type KeyEntry struct {
	Metadata     KeyMetadata `json:"metadata"`
	EncryptedKey []byte      `json:"encrypted_key"` // KEK encrypted with MEK
}

KeyEntry represents a stored key with its metadata

type KeyManager

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

KeyManager manages encryption keys, including rotation and versioning

func NewKeyManager

func NewKeyManager(config KeyManagerConfig) (*KeyManager, error)

NewKeyManager creates a new key manager

func (*KeyManager) CleanupDeprecatedKeys

func (km *KeyManager) CleanupDeprecatedKeys(olderThan time.Duration) error

CleanupDeprecatedKeys removes deprecated keys older than the specified age

func (*KeyManager) Close

func (km *KeyManager) Close() error

Close securely closes the key manager

func (*KeyManager) DeprecateKey

func (km *KeyManager) DeprecateKey(version uint32) error

DeprecateKey marks a key as deprecated (warning, will be removed)

func (*KeyManager) ExportKeyMetadata

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

ExportKeyMetadata exports key metadata for auditing (without actual keys)

func (*KeyManager) GenerateKEK

func (km *KeyManager) GenerateKEK() (uint32, error)

GenerateKEK generates a new Key Encryption Key

func (*KeyManager) GetActiveKEK

func (km *KeyManager) GetActiveKEK() ([]byte, uint32, error)

GetActiveKEK retrieves the currently active KEK

func (*KeyManager) GetActiveVersion

func (km *KeyManager) GetActiveVersion() uint32

GetActiveVersion returns the current active key version

func (*KeyManager) GetKEK

func (km *KeyManager) GetKEK(version uint32) ([]byte, error)

GetKEK retrieves and decrypts a KEK by version

func (*KeyManager) GetKeyAge

func (km *KeyManager) GetKeyAge(version uint32) (time.Duration, error)

GetKeyAge returns the age of a key version

func (*KeyManager) GetKeyMetadata

func (km *KeyManager) GetKeyMetadata(version uint32) (*KeyMetadata, error)

GetKeyMetadata returns metadata for a specific key version

func (*KeyManager) GetStatistics

func (km *KeyManager) GetStatistics() KeyManagerStatistics

GetStatistics returns statistics about the key manager

func (*KeyManager) ListKeys

func (km *KeyManager) ListKeys() []KeyMetadata

ListKeys returns metadata for all keys

func (*KeyManager) RevokeKey

func (km *KeyManager) RevokeKey(version uint32) error

RevokeKey marks a key as revoked (should not be used)

func (*KeyManager) RotateKey

func (km *KeyManager) RotateKey() (uint32, error)

RotateKey creates a new KEK and marks the old one as rotated

func (*KeyManager) ShouldRotate

func (km *KeyManager) ShouldRotate(maxAge time.Duration) bool

ShouldRotate checks if the active key should be rotated based on age

type KeyManagerConfig

type KeyManagerConfig struct {
	KeyDir      string        // Directory to store key metadata
	MasterKey   []byte        // Master encryption key (MEK)
	AutoRotate  bool          // Enable automatic key rotation
	RotateAfter time.Duration // Rotate keys after this duration
}

KeyManagerConfig holds configuration for the key manager

type KeyManagerStatistics

type KeyManagerStatistics struct {
	TotalKeys      int           `json:"total_keys"`
	ActiveKeys     int           `json:"active_keys"`
	RotatedKeys    int           `json:"rotated_keys"`
	DeprecatedKeys int           `json:"deprecated_keys"`
	RevokedKeys    int           `json:"revoked_keys"`
	ActiveVersion  uint32        `json:"active_version"`
	ActiveKeyAge   time.Duration `json:"active_key_age"`
	OldestKeyAge   time.Duration `json:"oldest_key_age"`
	NewestKeyAge   time.Duration `json:"newest_key_age"`
}

KeyManagerStatistics holds statistics about the key manager

type KeyMetadata

type KeyMetadata struct {
	Version     uint32    `json:"version"`
	CreatedAt   time.Time `json:"created_at"`
	ActivatedAt time.Time `json:"activated_at,omitempty"`
	RotatedAt   time.Time `json:"rotated_at,omitempty"`
	Status      KeyStatus `json:"status"`
	Algorithm   string    `json:"algorithm"`
	Purpose     string    `json:"purpose"` // "KEK" or "DEK"
}

KeyMetadata contains metadata about an encryption key

type KeyProvider

type KeyProvider interface {
	// GetActiveKEK retrieves the currently active Key Encryption Key.
	// Returns the key, its version number, and any error.
	GetActiveKEK() ([]byte, uint32, error)

	// GetKEK retrieves a Key Encryption Key by version number.
	// Used for decrypting data encrypted with older key versions.
	GetKEK(version uint32) ([]byte, error)

	// GetActiveVersion returns the current active key version number.
	GetActiveVersion() uint32
}

KeyProvider is the interface for key management operations. This is a simplified interface for retrieving keys.

type KeyStatus

type KeyStatus string

KeyStatus represents the status of a key

const (
	KeyStatusActive     KeyStatus = "active"     // Currently in use for new encryption
	KeyStatusRotated    KeyStatus = "rotated"    // Rotated out, but still used for decryption
	KeyStatusDeprecated KeyStatus = "deprecated" // Scheduled for removal
	KeyStatusRevoked    KeyStatus = "revoked"    // Should not be used
)

type StreamDecryptor

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

StreamDecryptor provides streaming decryption for large files

func (*StreamDecryptor) Close

func (sd *StreamDecryptor) Close() error

Close closes the stream decryptor

func (*StreamDecryptor) GetHeader

func (sd *StreamDecryptor) GetHeader() *FileHeader

GetHeader returns the file header

func (*StreamDecryptor) ReadBlock

func (sd *StreamDecryptor) ReadBlock(maxSize int) ([]byte, error)

ReadBlock reads and decrypts the next data block

type StreamEncryptor

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

StreamEncryptor provides streaming encryption for large files

func (*StreamEncryptor) Close

func (se *StreamEncryptor) Close() error

Close closes the stream encryptor (currently a no-op, for future use)

func (*StreamEncryptor) WriteBlock

func (se *StreamEncryptor) WriteBlock(plaintext []byte) error

WriteBlock encrypts and writes a data block

Jump to

Keyboard shortcuts

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