gencryption

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 15, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package gencryption provides cryptographic primitives for encrypting files, packets, and binary data. It wraps Go's standard library and golang.org/x/crypto packages into reusable, tested helpers.

Symmetric Encryption

Two authenticated encryption ciphers are provided:

  • AES — AES-256-GCM with a hex-encoded key. Hardware-accelerated on platforms with AES-NI. Uses a 12-byte random nonce; callers must limit usage to fewer than 2^32 messages per key to avoid nonce collision.
  • XChaCha — XChaCha20-Poly1305 with a raw 32-byte key. Uses a 24-byte random nonce, making nonce collision negligible even at very high volume. Preferred for ARM, embedded, and cross-platform workloads.

Both ciphers produce output in nonce||ciphertext format and expose Encrypt, Decrypt, EncryptFile, and DecryptFile methods.

Key Derivation

  • Argon2 — Argon2id password-based key derivation. Returns a derived key and a random salt; both must be stored for later re-derivation. Parameters are validated against OWASP minimums (≥19 MiB memory, ≥2 iterations).
  • HKDFDeriveKey / HKDFDeriveKeys — HKDF (RFC 5869) for deriving sub-keys from a shared secret. Use HKDFDeriveKeySHA256 for the common SHA-256 case.

Key Exchange

  • GenerateX25519KeyPair / X25519SharedSecret — X25519 Elliptic Curve Diffie-Hellman for establishing a shared secret between two parties. Always pass the resulting shared secret through HKDF before using it as an encryption key.

Digital Signatures

  • Signer / Verifier — Ed25519 signing and verification for ensuring integrity and authenticity of files and data. Signatures are 64 bytes.

Memory Safety

Use Wipe to zero sensitive data (keys, plaintext) after use:

key, salt, _ := a.DeriveKey(password)
defer gencryption.Wipe(key)

Security Notes

  • AES-GCM has a ~2^32 message limit per key before nonce collision becomes probable. For high-volume use cases, prefer XChaCha20-Poly1305.
  • Argon2id parameters are validated at construction time to enforce OWASP-recommended minimums.
  • Derived keys and plaintext buffers should be wiped after use.
  • X25519 shared secrets must be passed through HKDF, never used directly.

Index

Constants

View Source
const (
	AES_EXT     = "aes"
	XCHACHA_EXT = "xchacha"
)

File extensions appended by EncryptFile helpers.

View Source
const (
	FILE_PERMISSION_0600 = 0o600
	DIR_PERMISSION_0700  = 0o700
)

Default filesystem permissions used when writing encrypted files.

Variables

View Source
var (
	ErrCiphertextTooShort = errors.New("gencryption: ciphertext too short")
	ErrInvalidKeySize     = errors.New("gencryption: invalid key size")
	ErrInvalidSaltSize    = errors.New("gencryption: invalid salt size")
	ErrInvalidSignature   = errors.New("gencryption: invalid signature")
)

Sentinel errors returned by the gencryption package.

Functions

func GenerateEd25519KeyPair

func GenerateEd25519KeyPair() (ed25519.PublicKey, ed25519.PrivateKey, error)

GenerateEd25519KeyPair generates a new Ed25519 signing keypair.

func GenerateX25519KeyPair

func GenerateX25519KeyPair() (*ecdh.PrivateKey, error)

GenerateX25519KeyPair generates a new X25519 private key. The public key can be obtained via the returned key's PublicKey() method.

func HKDFDeriveKey

func HKDFDeriveKey(hashFunc func() hash.Hash, secret, salt, info []byte, keyLen int) ([]byte, error)

HKDFDeriveKey derives a single key of keyLen bytes from the given secret using HKDF (RFC 5869). The hash function, salt, and info parameters control the derivation. Pass nil for salt to use a zero-length salt. The info parameter differentiates derived keys for different purposes.

func HKDFDeriveKeySHA256

func HKDFDeriveKeySHA256(secret, salt, info []byte, keyLen int) ([]byte, error)

HKDFDeriveKeySHA256 is a convenience wrapper around HKDFDeriveKey that uses SHA-256 as the hash function.

func HKDFDeriveKeys

func HKDFDeriveKeys(hashFunc func() hash.Hash, secret, salt []byte, infos [][]byte, keyLen int) ([][]byte, error)

HKDFDeriveKeys derives multiple keys from a single secret, each with a distinct info value. All keys are keyLen bytes. This is useful for separating an encryption key and an authentication key from one shared secret.

func MarshalX25519PrivateKey

func MarshalX25519PrivateKey(priv *ecdh.PrivateKey) []byte

MarshalX25519PrivateKey returns the raw 32-byte encoding of an X25519 private key.

func MarshalX25519PublicKey

func MarshalX25519PublicKey(pub *ecdh.PublicKey) []byte

MarshalX25519PublicKey returns the raw 32-byte encoding of an X25519 public key, suitable for transmission to a peer.

func UnmarshalX25519PrivateKey

func UnmarshalX25519PrivateKey(data []byte) (*ecdh.PrivateKey, error)

UnmarshalX25519PrivateKey parses a raw 32-byte X25519 private key.

func UnmarshalX25519PublicKey

func UnmarshalX25519PublicKey(data []byte) (*ecdh.PublicKey, error)

UnmarshalX25519PublicKey parses a raw 32-byte X25519 public key.

func Wipe

func Wipe(b []byte)

Wipe zeroes the contents of b, overwriting every byte with 0. Uses crypto/subtle.ConstantTimeCopy to prevent compiler optimization from eliding the writes.

Use this to clear sensitive material (keys, plaintext, nonces) from memory as soon as it is no longer needed.

key, salt, _ := a.DeriveKey(password)
defer gencryption.Wipe(key)

func X25519SharedSecret

func X25519SharedSecret(privateKey *ecdh.PrivateKey, peerPublicKey *ecdh.PublicKey) ([]byte, error)

X25519SharedSecret performs an X25519 Diffie-Hellman exchange and returns the raw 32-byte shared secret. The caller should derive actual encryption keys from this secret using HKDF rather than using it directly.

Types

type AES

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

AES is a reusable AES-GCM helper that avoids re-deriving the key/GCM per call.

func NewAES

func NewAES(hexKey string) (*AES, error)

NewAES creates a reusable AES instance from a hex-encoded key.

func (*AES) Decrypt

func (a *AES) Decrypt(data []byte) ([]byte, error)

Decrypt expects data as nonce||ciphertext using the cached GCM.

func (*AES) DecryptFile

func (a *AES) DecryptFile(configPath string) ([]byte, error)

DecryptFile reads an AES-encrypted file (nonce|ciphertext) and decrypts it.

func (*AES) Encrypt

func (a *AES) Encrypt(data []byte) ([]byte, error)

Encrypt returns nonce||ciphertext using the cached GCM.

func (*AES) EncryptFile

func (a *AES) EncryptFile(configPath string, content []byte) error

EncryptFile encrypts content and writes nonce|ciphertext to <path>.aes.

type Argon2

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

Argon2 derives encryption keys from passwords using Argon2id.

func NewArgon2

func NewArgon2(params Argon2Params) (*Argon2, error)

NewArgon2 creates a new Argon2 instance with the given parameters. Returns an error if any parameter is zero or below OWASP-recommended minimums (≥2 iterations, ≥19 MiB memory, ≥16 byte key, ≥8 byte salt).

func (*Argon2) DeriveKey

func (a *Argon2) DeriveKey(password []byte) (key, salt []byte, err error)

DeriveKey generates a random salt and derives a key from the password. Returns the derived key and the salt (which must be stored alongside any ciphertext for later re-derivation).

func (*Argon2) DeriveKeyWithSalt

func (a *Argon2) DeriveKeyWithSalt(password, salt []byte) ([]byte, error)

DeriveKeyWithSalt re-derives a key from a password and a known salt. This is used during decryption when the salt was stored alongside the ciphertext.

type Argon2Params

type Argon2Params struct {
	Time    uint32 // Number of iterations (passes over memory).
	Memory  uint32 // Memory usage in KiB.
	Threads uint8  // Degree of parallelism.
	KeyLen  uint32 // Desired key length in bytes.
	SaltLen uint32 // Salt length in bytes.
}

Argon2Params controls the Argon2id key derivation cost parameters.

func DefaultArgon2Params

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params returns OWASP-recommended Argon2id parameters: 3 iterations, 64 MiB memory, 4 threads, 32-byte key, 16-byte salt.

type Signer

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

Signer signs data using an Ed25519 private key.

func NewSigner

func NewSigner(privateKey ed25519.PrivateKey) (*Signer, error)

NewSigner creates a Signer from an Ed25519 private key. The key must be 64 bytes (ed25519.PrivateKeySize).

func (*Signer) Sign

func (s *Signer) Sign(data []byte) []byte

Sign returns a 64-byte Ed25519 signature of data.

func (*Signer) SignFile

func (s *Signer) SignFile(path string) ([]byte, error)

SignFile reads a file and returns its Ed25519 signature.

type Verifier

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

Verifier verifies Ed25519 signatures using a public key.

func NewVerifier

func NewVerifier(publicKey ed25519.PublicKey) (*Verifier, error)

NewVerifier creates a Verifier from an Ed25519 public key. The key must be 32 bytes (ed25519.PublicKeySize).

func (*Verifier) Verify

func (v *Verifier) Verify(data, sig []byte) bool

Verify returns true if the signature is valid for the given data.

func (*Verifier) VerifyFile

func (v *Verifier) VerifyFile(path string, sig []byte) (bool, error)

VerifyFile reads a file and verifies its signature.

type XChaCha

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

XChaCha is a reusable XChaCha20-Poly1305 helper that caches the AEAD instance to avoid re-creating it on every call. XChaCha20-Poly1305 uses a 24-byte nonce which makes random nonce generation safe even at high volume.

func NewXChaCha

func NewXChaCha(key []byte) (*XChaCha, error)

NewXChaCha creates a reusable XChaCha instance from a raw 32-byte key.

func (*XChaCha) Decrypt

func (x *XChaCha) Decrypt(data []byte) ([]byte, error)

Decrypt expects data as nonce||ciphertext and returns the plaintext.

func (*XChaCha) DecryptFile

func (x *XChaCha) DecryptFile(path string) ([]byte, error)

DecryptFile reads an XChaCha20-encrypted file (nonce|ciphertext) and decrypts it.

func (*XChaCha) Encrypt

func (x *XChaCha) Encrypt(data []byte) ([]byte, error)

Encrypt returns nonce||ciphertext using XChaCha20-Poly1305. The 24-byte nonce is randomly generated and prepended to the output.

func (*XChaCha) EncryptFile

func (x *XChaCha) EncryptFile(path string, content []byte) error

EncryptFile encrypts content and writes nonce|ciphertext to <path>.xchacha.

Jump to

Keyboard shortcuts

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