core

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: MPL-2.0 Imports: 18 Imported by: 0

Documentation

Overview

decryptor.go: Chunked streaming decryption logic for go-fileencrypt

encryptor.go: Chunked streaming encryption logic for go-fileencrypt

format.go: File format constants and algorithm ID support for go-fileencrypt

key.go: Key derivation and management for go-fileencrypt

options.go: Configuration options for go-fileencrypt

Index

Constants

View Source
const (
	// MagicBytes is the file signature "GFE" (Go File Encrypt).
	MagicBytes = "GFE"
	// Version is the current file format version (1).
	Version = 1
	// NonceSize is the size of the nonce for AES-GCM.
	NonceSize = 12
	// HeaderSize is the total size of the file header.
	// File format: [3 bytes magic][1 byte version][12 bytes nonce][8 bytes file size][chunks...]
	HeaderSize = len(MagicBytes) + 1 + NonceSize + 8
	// MaxChunkSize is the maximum size for a single chunk of data.
	MaxChunkSize = 10 * 1024 * 1024
)
View Source
const (
	// DefaultPBKDF2Iterations is the default iteration count for PBKDF2
	DefaultPBKDF2Iterations = 600000 // OWASP recommendation (2023)

	// MinPBKDF2Iterations is the minimum safe iteration count
	MinPBKDF2Iterations = 210000 // OWASP minimum

	// DefaultSaltSize is the default salt size in bytes
	DefaultSaltSize = 32

	// DefaultKeySize is the default derived key size (32 bytes for AES-256)
	DefaultKeySize = 32

	// DefaultArgon2Time is the number of iterations (time cost)
	DefaultArgon2Time = 3

	// DefaultArgon2Memory is the memory cost in KiB (64 MB)
	DefaultArgon2Memory = 64 * 1024

	// DefaultArgon2Threads is the parallelism factor
	DefaultArgon2Threads = 4

	// MinArgon2Memory is the minimum memory cost (19 MB per OWASP minimum)
	MinArgon2Memory = 19 * 1024
)
View Source
const (
	MinChunkSize = 1 // Minimum valid chunk size
	// DefaultChunkSize is the default chunk size used by the library
	// for streaming operations. It is intentionally smaller than
	// `MaxChunkSize` (format limit) so the library uses sensible
	// default buffering without reaching the format's absolute max.
	DefaultChunkSize = 1 * 1024 * 1024 // 1MB default chunk size
)

Variables

View Source
var (
	ErrInvalidKey      = fmt.Errorf("invalid key")
	ErrInvalidNonce    = fmt.Errorf("invalid nonce")
	ErrChunkSize       = fmt.Errorf("invalid chunk size")
	ErrChecksum        = fmt.Errorf("checksum mismatch")
	ErrContextCanceled = fmt.Errorf("context canceled")
)

Error types for file encryption

Functions

func CalculateChecksum

func CalculateChecksum(path string) ([]byte, error)

CalculateChecksum computes the SHA-256 checksum of a file.

func CalculateChecksumHex

func CalculateChecksumHex(path string) (string, error)

CalculateChecksumHex computes the SHA-256 checksum of a file and returns it as hex string.

func DeriveKeyArgon2

func DeriveKeyArgon2(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) ([]byte, error)

DeriveKeyArgon2 derives a key from a password using Argon2id. Argon2id is the recommended password hashing algorithm as of 2023 (winner of Password Hashing Competition). It provides better resistance to GPU/ASIC attacks compared to PBKDF2.

Parameters:

  • password: The password bytes (will not be modified)
  • salt: The salt bytes (must be at least 16 bytes, recommended 32 bytes)
  • time: Time cost (number of iterations), minimum 1, recommended 3+
  • memory: Memory cost in KiB (minimum 19456 = 19 MB, recommended 65536 = 64 MB)
  • threads: Parallelism factor (recommended: number of CPU cores, typically 4)
  • keyLen: Length of the derived key in bytes (typically 32 for AES-256)

OWASP 2023 Recommendations:

  • Interactive logins: memory=64MB, time=3, threads=4
  • Background operations: memory=256MB, time=4, threads=4
  • Minimum acceptable: memory=19MB, time=2, threads=1

Example:

salt, _ := GenerateSalt(DefaultSaltSize)
key, err := DeriveKeyArgon2(
    []byte("password"),
    salt,
    DefaultArgon2Time,     // 3 iterations
    DefaultArgon2Memory,   // 64 MB
    DefaultArgon2Threads,  // 4 threads
    DefaultKeySize,        // 32 bytes
)
if err != nil {
    return err
}
defer secure.Zero(key)

func DeriveKeyPBKDF2

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

DeriveKeyPBKDF2 derives a key from a password using PBKDF2-HMAC-SHA256. Returns the derived key. The caller must securely zero the key after use.

Parameters:

  • password: The password bytes (will not be modified)
  • salt: The salt bytes (must be at least 16 bytes, recommended 32 bytes)
  • iterations: Number of iterations (must be >= MinPBKDF2Iterations)
  • keyLen: Length of the derived key in bytes (typically 32 for AES-256)

Example:

salt := make([]byte, DefaultSaltSize)
if _, err := rand.Read(salt); err != nil {
    return err
}
key, err := DeriveKeyPBKDF2([]byte("password"), salt, DefaultPBKDF2Iterations, DefaultKeySize)
if err != nil {
    return err
}
defer secure.Zero(key)

func GenerateSalt

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

GenerateSalt generates a cryptographically secure random salt.

func SanitizeError added in v0.1.4

func SanitizeError(err error) error

SanitizeError removes sensitive details for external consumption

func VerifyChecksum

func VerifyChecksum(path string, sum []byte) (bool, error)

VerifyChecksum checks if the file matches the given checksum

func VerifyChecksumHex

func VerifyChecksumHex(path string, hexSum string) (bool, error)

VerifyChecksumHex checks if the file matches the given hex-encoded checksum

func WrapError added in v0.1.4

func WrapError(context string, err error) error

WrapError adds context to an error

Types

type Algorithm

type Algorithm uint8

Algorithm represents a cryptographic algorithm

const (
	// AlgorithmAESGCM is AES-256-GCM (default, currently supported)
	AlgorithmAESGCM Algorithm = 1

	// AlgorithmChaCha20Poly1305 is ChaCha20-Poly1305 (reserved for future)
	AlgorithmChaCha20Poly1305 Algorithm = 2

	// AlgorithmMLKEMHybrid is ML-KEM hybrid post-quantum (reserved for future)
	AlgorithmMLKEMHybrid Algorithm = 3
)

func (Algorithm) IsSupported

func (a Algorithm) IsSupported() bool

IsSupported returns true if the algorithm is currently implemented

func (Algorithm) String

func (a Algorithm) String() string

String returns the algorithm name

type Config

type Config struct {
	ChunkSize int
	Progress  func(float64)
	Checksum  bool
	Algorithm Algorithm
}

type Decryptor

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

Decryptor handles chunked decryption of files and streams.

func NewDecryptor

func NewDecryptor(key []byte, opts ...Option) (*Decryptor, error)

func (*Decryptor) DecryptFile

func (d *Decryptor) DecryptFile(ctx context.Context, srcPath, dstPath string) error

DecryptFile performs chunked decryption of a file.

func (*Decryptor) DecryptStream

func (d *Decryptor) DecryptStream(ctx context.Context, src io.Reader, dst io.Writer, sizeHint ...int64) error

DecryptStream performs chunked decryption of a stream.

func (*Decryptor) Destroy

func (d *Decryptor) Destroy()

Destroy zeroes key material and unlocks memory

type EncryptionError added in v0.1.4

type EncryptionError struct {
	Op       string // Operation: "encrypt", "decrypt", "generate_key", etc.
	Path     string // File path being operated on
	ChunkNum int    // Chunk number if applicable (-1 if not chunked operation)
	Err      error  // Underlying error
}

EncryptionError represents an encryption/decryption error with context

func NewEncryptionError added in v0.1.4

func NewEncryptionError(op, path string, chunkNum int, err error) *EncryptionError

NewEncryptionError creates a new EncryptionError

func (*EncryptionError) Error added in v0.1.4

func (e *EncryptionError) Error() string

func (*EncryptionError) Unwrap added in v0.1.4

func (e *EncryptionError) Unwrap() error

type Encryptor

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

Encryptor handles chunked encryption of files and streams.

func NewEncryptor

func NewEncryptor(key []byte, opts ...Option) (*Encryptor, error)

func (*Encryptor) Destroy

func (e *Encryptor) Destroy()

Destroy zeroes key material and unlocks memory

func (*Encryptor) EncryptFile

func (e *Encryptor) EncryptFile(ctx context.Context, srcPath, dstPath string) error

EncryptFile performs chunked encryption of a file.

func (*Encryptor) EncryptStream

func (e *Encryptor) EncryptStream(ctx context.Context, src io.Reader, dst io.Writer, sizeHint ...int64) error

EncryptStream performs chunked encryption of a stream. If sizeHint > 0, it is used for progress reporting only.

type Option

type Option func(*Config)

Option defines functional options for encryption/decryption (chunk size, progress, checksum, algorithm, etc.)

func WithAlgorithm

func WithAlgorithm(alg Algorithm) Option

WithAlgorithm sets the encryption algorithm (default: AES-256-GCM). Currently only AlgorithmAESGCM is supported; others return an error.

func WithChecksum

func WithChecksum(enable bool) Option

WithChecksum enables checksum calculation/verification.

func WithChunkSize

func WithChunkSize(size int) (Option, error)

WithChunkSize sets the chunk size for streaming operations.

func WithProgress

func WithProgress(cb func(float64)) Option

WithProgress sets a progress callback (called at every 20% interval).

The callback receives a fraction between 0.0 and 1.0 (inclusive), where 0.0 means no progress and 1.0 means complete. Examples and documentation should use fractional progress (not percentages).

Jump to

Keyboard shortcuts

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