kdbxtool.security.memory

Secure memory handling for sensitive data.

This module provides SecureBytes, a mutable byte container that: - Stores data in a bytearray (mutable, can be zeroized) - Automatically zeroizes memory on destruction - Supports context manager protocol for guaranteed cleanup - Prevents accidental exposure through repr/str

Classes

SecureBytes(data)

A secure container for sensitive byte data that zeroizes on destruction.

class kdbxtool.security.memory.SecureBytes(data)[source]

Bases: object

A secure container for sensitive byte data that zeroizes on destruction.

Unlike Python’s immutable bytes, SecureBytes uses a mutable bytearray that can be explicitly zeroed when no longer needed. This prevents sensitive data like passwords and cryptographic keys from lingering in memory.

Usage:

# Basic usage key = SecureBytes(derived_key_bytes) # … use key.data for crypto operations … key.zeroize() # Explicit cleanup

# Context manager (recommended) with SecureBytes(password.encode()) as pwd:

hash = sha256(pwd.data)

# Automatically zeroized here

Note

While this provides defense-in-depth against memory disclosure attacks, Python’s memory management means copies may still exist. For maximum security, consider using specialized libraries like PyNaCl’s SecretBox.

Parameters:

data (bytes | bytearray)

__init__(data)[source]

Initialize with sensitive data.

Parameters:

data (bytes | bytearray) – The sensitive bytes to protect. Will be copied into internal buffer.

Return type:

None

property data: bytes

Access the underlying data as immutable bytes.

Returns:

The protected data as bytes.

Raises:

ValueError – If the buffer has already been zeroized.

zeroize()[source]

Overwrite the buffer with zeros.

This method overwrites every byte in the buffer with 0x00, making the original data unrecoverable from this object. Safe to call multiple times.

Return type:

None

classmethod from_str(s, encoding='utf-8')[source]

Create SecureBytes from a string.

Parameters:
  • s (str) – String to encode

  • encoding (str) – Character encoding (default: utf-8)

Returns:

SecureBytes containing the encoded string

Return type:

Self