kdbxtool

kdbxtool - A modern, secure Python library for KeePass KDBX databases.

This library provides a clean, type-safe API for reading and writing KeePass database files (KDBX format). It prioritizes security with: - Secure memory handling (zeroization of sensitive data) - Constant-time comparisons for authentication - Modern cryptographic defaults (Argon2d, ChaCha20)

Example

from kdbxtool import Database

db = Database.open(“vault.kdbx”, password=”secret”) entry = db.find_entries(title=”Gmail”)[0] print(entry.username)

# Create new entry db.root_group.create_entry(

title=”New Site”, username=”user”, password=”pass123”,

) db.save()

class kdbxtool.AesKdfConfig(rounds, salt)[source]

Bases: object

Configuration for AES-KDF key derivation.

AES-KDF is supported in both KDBX3 and KDBX4. While Argon2 is generally recommended for new databases, AES-KDF may be preferred for compatibility with older KeePass clients or on systems where Argon2 is slow.

Parameters:
rounds

Number of AES encryption rounds (higher = slower but more secure)

Type:

int

salt

32-byte salt

Type:

bytes

rounds: int
salt: bytes
__init__(rounds, salt)
Parameters:
Return type:

None

classmethod fast(salt=None)[source]

Create configuration for fast operations (testing only).

WARNING: Uses only 60,000 rounds which provides minimal security. Only use for testing or development.

Parameters:

salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

Returns:

AesKdfConfig with minimal parameters

Return type:

AesKdfConfig

classmethod high_security(salt=None)[source]

Create configuration for high-security applications.

Uses 6,000,000 rounds for stronger protection at the cost of longer unlock times.

Parameters:

salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

Returns:

AesKdfConfig with high security parameters

Return type:

AesKdfConfig

classmethod standard(salt=None)[source]

Create configuration with balanced security/performance.

Uses 600,000 rounds which provides reasonable security while keeping unlock times acceptable on most hardware.

Parameters:

salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

Returns:

AesKdfConfig with standard parameters

Return type:

AesKdfConfig

class kdbxtool.Argon2Config(memory_kib, iterations, parallelism, salt, variant=KdfType.ARGON2D)[source]

Bases: object

Configuration for Argon2 key derivation.

Parameters:
memory_kib

Memory usage in KiB

Type:

int

iterations

Number of iterations (time cost)

Type:

int

parallelism

Degree of parallelism

Type:

int

salt

Random salt (must be at least 16 bytes)

Type:

bytes

variant

Argon2 variant (Argon2d or Argon2id)

Type:

kdbxtool.security.kdf.KdfType

memory_kib: int
iterations: int
parallelism: int
salt: bytes
variant: KdfType
__init__(memory_kib, iterations, parallelism, salt, variant=KdfType.ARGON2D)
Parameters:
Return type:

None

classmethod default(salt=None, variant=KdfType.ARGON2D)[source]

Create configuration with secure defaults.

Alias for standard(). Provides balanced security and performance.

Parameters:
  • salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

  • variant (KdfType) – Argon2 variant (ARGON2D or ARGON2ID). Default is ARGON2D which provides better GPU resistance for local password databases.

Returns:

Argon2Config with recommended security parameters

Return type:

Argon2Config

classmethod fast(salt=None, variant=KdfType.ARGON2D)[source]

Create configuration for fast operations (testing only).

WARNING: This provides minimal security and should only be used for testing or development. Not suitable for production databases.

Parameters: 16 MiB memory, 3 iterations, 2 parallelism

Parameters:
  • salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

  • variant (KdfType) – Argon2 variant (ARGON2D or ARGON2ID). Default is ARGON2D.

Returns:

Argon2Config with minimal parameters

Return type:

Argon2Config

classmethod high_security(salt=None, variant=KdfType.ARGON2D)[source]

Create configuration for high-security applications.

Use for sensitive data where longer unlock times are acceptable. Provides stronger protection against brute-force attacks.

Parameters: 256 MiB memory, 10 iterations, 4 parallelism

Parameters:
  • salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

  • variant (KdfType) – Argon2 variant (ARGON2D or ARGON2ID). Default is ARGON2D which provides better GPU resistance for local password databases.

Returns:

Argon2Config with high security parameters

Return type:

Argon2Config

classmethod standard(salt=None, variant=KdfType.ARGON2D)[source]

Create configuration with balanced security/performance.

Suitable for most use cases. Provides good security with reasonable unlock times on modern hardware.

Parameters: 64 MiB memory, 3 iterations, 4 parallelism

Parameters:
  • salt (bytes | None) – Optional salt (32 random bytes generated if not provided)

  • variant (KdfType) – Argon2 variant (ARGON2D or ARGON2ID). Default is ARGON2D which provides better GPU resistance for local password databases. Use ARGON2ID if timing attack resistance is needed.

Returns:

Argon2Config with standard security parameters

Return type:

Argon2Config

validate_security()[source]

Check that parameters meet minimum security requirements.

Raises:

ValueError – If parameters are below security minimums

Return type:

None

class kdbxtool.Attachment(filename, id, entry)[source]

Bases: object

An attachment (binary file) associated with an entry.

Attachments represent files attached to entries in the database. The binary data is stored at the database level and referenced by ID.

Parameters:
filename

Name of the attached file

Type:

str

id

Reference ID to the binary data in the database

Type:

int

entry

The entry this attachment belongs to

Type:

Entry

__init__(filename, id, entry)
Parameters:
Return type:

None

property data: bytes | None

Get the binary data for this attachment.

Returns:

Binary data if available, None if not found or entry has no database

filename: str
id: int
entry: Entry
class kdbxtool.Database(root_group, settings=None, header=None, inner_header=None, binaries=None)[source]

Bases: object

High-level interface for KDBX databases.

This class provides the main API for working with KeePass databases. It handles encryption/decryption, XML parsing, and model management.

Example usage:

# Open existing database db = Database.open(“passwords.kdbx”, password=”secret”)

# Find entries entries = db.find_entries(title=”GitHub”)

# Create entry entry = db.root_group.create_entry(

title=”New Site”, username=”user”, password=”pass123”,

)

# Save changes db.save()

Parameters:
__init__(root_group, settings=None, header=None, inner_header=None, binaries=None)[source]

Initialize database.

Usually you should use Database.open() or Database.create() instead.

Parameters:
  • root_group (Group) – Root group containing all entries/groups

  • settings (DatabaseSettings | None) – Database settings

  • header (KdbxHeader | None) – KDBX header (for existing databases)

  • inner_header (InnerHeader | None) – Inner header (for existing databases)

  • binaries (dict[int, bytes] | None) – Binary attachments

Return type:

None

add_attachment(entry, name, data, protected=True)[source]

Add an attachment to an entry.

Parameters:
  • entry (Entry) – Entry to add attachment to

  • name (str) – Filename for the attachment

  • data (bytes) – Attachment data

  • protected (bool) – Whether the attachment should be memory-protected

Return type:

None

add_binary(data, protected=True)[source]

Add a new binary attachment to the database.

Parameters:
  • data (bytes) – Binary data

  • protected (bool) – Whether the binary should be memory-protected

Returns:

Reference ID for the new binary

Return type:

int

add_custom_icon(data, name=None)[source]

Add a custom icon to the database.

Parameters:
  • data (bytes) – PNG image data

  • name (str | None) – Optional display name for the icon

Returns:

UUID of the new custom icon

Return type:

UUID

apply_protection_policy(entry)[source]

Apply the database’s memory protection policy to an entry.

Updates the protected flag on the entry’s string fields according to the database’s memory_protection settings.

This is automatically applied when saving the database, but can be called manually if you need protection applied immediately for in-memory operations.

Parameters:

entry (Entry) – Entry to apply policy to

Return type:

None

apply_protection_policy_all()[source]

Apply memory protection policy to all entries in the database.

Updates all entries’ string field protection flags according to the database’s memory_protection settings.

Return type:

None

property attachments: list[Attachment]

Get all attachments in the database.

classmethod create(filepath=None, password=None, keyfile=None, database_name='Database', cipher=Cipher.AES256_CBC, kdf_config=None)[source]

Create a new KDBX database.

Parameters:
  • filepath (str | Path | None) – Path to save the database (optional)

  • password (str | None) – Database password

  • keyfile (str | Path | None) – Path to keyfile (optional)

  • database_name (str) – Name for the database

  • cipher (Cipher) – Encryption cipher to use

  • kdf_config (Argon2Config | AesKdfConfig | None) – KDF configuration (Argon2Config or AesKdfConfig). Defaults to Argon2Config.standard() with Argon2d variant.

Returns:

New Database instance

Return type:

Database

property custom_icons: dict[UUID, CustomIcon]

Get dictionary of custom icons (UUID -> CustomIcon).

deref(value)[source]

Resolve KeePass field references in a value.

Parses field references in the format {REF:X@Y:Z} and replaces them with the actual values from the referenced entries: - X = Field to retrieve (T=Title, U=Username, P=Password, A=URL, N=Notes, I=UUID) - Y = Field to search by (T, U, P, A, N, I) - Z = Search value

References are resolved recursively, so a reference that resolves to another reference will continue resolving until a final value is found.

Parameters:

value (str | None) – String potentially containing field references

Returns:

  • The resolved string with all references replaced

  • A UUID if the final result is a UUID reference

  • None if any referenced entry cannot be found

  • The original value if it contains no references or is None

Return type:

str | UUID | None

Example

>>> # Entry with password = '{REF:P@I:ABCD1234...}'
>>> db.deref(entry.password)  # Returns the referenced password
>>>
>>> # With prefix/suffix: 'prefix{REF:U@I:...}suffix'
>>> db.deref(value)  # Returns 'prefix<username>suffix'
dump()[source]

Return a human-readable summary of the database for debugging.

Returns:

Multi-line string with database metadata and statistics.

Return type:

str

dump_xml(filepath, *, pretty_print=True)[source]

Write database XML payload to a file.

Writes the decrypted, decompressed XML payload to a file. Protected values (passwords, etc.) are shown in plaintext. Useful for debugging and migration.

Parameters:
  • filepath (str | Path) – Path to write the XML file

  • pretty_print (bool) – If True (default), format XML with indentation

Return type:

None

empty_group(group)[source]

Delete all entries and subgroups from a group.

This permanently deletes all contents (does not use recycle bin). The group itself is not deleted.

Parameters:

group (Group) – Group to empty

Raises:

ValueError – If group is not in this database

Return type:

None

property filepath: Path | None

Get the file path (if opened from file).

find_attachments(id=None, filename=None, regex=False, recursive=True, history=False, first=False)[source]

Find attachments in the database.

Parameters:
  • id (int | None) – Match attachments with this binary reference ID

  • filename (str | None) – Match attachments with this filename (exact or regex)

  • regex (bool) – If True, treat filename as a regex pattern

  • recursive (bool) – Search in subgroups

  • history (bool) – Include history entries in search

  • first (bool) – If True, return first match or None. If False, return list.

Returns:

Attachment or None If first=False: List of matching attachments

Return type:

If first=True

find_custom_icon_by_name(name)[source]

Find a custom icon by name.

Parameters:

name (str) – Name of the icon to find (must match exactly one icon)

Returns:

UUID of the matching icon, or None if not found

Raises:

ValueError – If multiple icons have the same name

Return type:

UUID | None

find_entries(title=None, username=None, password=None, url=None, notes=None, otp=None, tags=None, string=None, autotype_enabled=None, autotype_sequence=None, autotype_window=None, uuid=None, path=None, recursive=True, history=False, first=False)[source]

Find entries matching criteria.

Parameters:
  • title (str | None) – Match entries with this title

  • username (str | None) – Match entries with this username

  • password (str | None) – Match entries with this password

  • url (str | None) – Match entries with this URL

  • notes (str | None) – Match entries with these notes

  • otp (str | None) – Match entries with this OTP

  • tags (list[str] | None) – Match entries with all these tags

  • string (dict[str, str] | None) – Match entries with custom properties (dict of key:value)

  • autotype_enabled (bool | None) – Filter by AutoType enabled state

  • autotype_sequence (str | None) – Match entries with this AutoType sequence

  • autotype_window (str | None) – Match entries with this AutoType window

  • uuid (UUID | None) – Match entry with this UUID

  • path (list[str] | str | None) – Path to entry as list of group names ending with entry title, or as a ‘/’-separated string. When specified, other criteria are ignored.

  • recursive (bool) – Search in subgroups

  • history (bool) – Include history entries in search

  • first (bool) – If True, return first match or None. If False, return list.

Returns:

Entry or None If first=False: List of matching entries

Return type:

If first=True

find_entries_contains(title=None, username=None, password=None, url=None, notes=None, otp=None, recursive=True, case_sensitive=False, history=False)[source]

Find entries where fields contain the given substrings.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Match entries whose title contains this substring

  • username (str | None) – Match entries whose username contains this substring

  • password (str | None) – Match entries whose password contains this substring

  • url (str | None) – Match entries whose URL contains this substring

  • notes (str | None) – Match entries whose notes contain this substring

  • otp (str | None) – Match entries whose OTP contains this substring

  • recursive (bool) – Search in subgroups

  • case_sensitive (bool) – If False (default), matching is case-insensitive

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Return type:

list[Entry]

find_entries_regex(title=None, username=None, password=None, url=None, notes=None, otp=None, recursive=True, case_sensitive=False, history=False)[source]

Find entries where fields match the given regex patterns.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Regex pattern to match against title

  • username (str | None) – Regex pattern to match against username

  • password (str | None) – Regex pattern to match against password

  • url (str | None) – Regex pattern to match against URL

  • notes (str | None) – Regex pattern to match against notes

  • otp (str | None) – Regex pattern to match against OTP

  • recursive (bool) – Search in subgroups

  • case_sensitive (bool) – If False (default), matching is case-insensitive

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Raises:

re.error – If any pattern is not a valid regex

Return type:

list[Entry]

find_groups(name=None, uuid=None, path=None, recursive=True, first=False)[source]

Find groups matching criteria.

Parameters:
  • name (str | None) – Match groups with this name

  • uuid (UUID | None) – Match group with this UUID

  • path (list[str] | str | None) – Path to group as list of group names or as a ‘/’-separated string. When specified, other criteria are ignored.

  • recursive (bool) – Search in nested subgroups

  • first (bool) – If True, return first matching group or None instead of list

Returns:

List of matching groups, or single Group/None if first=True

Return type:

list[Group] | Group | None

get_attachment(entry, name)[source]

Get an attachment from an entry by filename.

Parameters:
  • entry (Entry) – Entry to get attachment from

  • name (str) – Filename of the attachment

Returns:

Attachment data or None if not found

Return type:

bytes | None

get_binary(ref)[source]

Get binary attachment data by reference ID.

Parameters:

ref (int) – Binary reference ID

Returns:

Binary data or None if not found

Return type:

bytes | None

get_custom_icon(uuid)[source]

Get custom icon data by UUID.

Parameters:

uuid (UUID) – UUID of the custom icon

Returns:

PNG image data, or None if not found

Return type:

bytes | None

iter_entries(recursive=True)[source]

Iterate over all entries in the database.

Parameters:

recursive (bool) – Include entries from all subgroups

Yields:

Entry objects

Return type:

Iterator[Entry]

iter_groups(recursive=True)[source]

Iterate over all groups in the database.

Parameters:

recursive (bool) – Include nested subgroups

Yields:

Group objects

Return type:

Iterator[Group]

property kdf_salt: bytes | None

Get the KDF salt used for key derivation.

The salt is used together with credentials to derive the transformed key. If the salt changes (e.g., after save with regenerate_seeds=True), any cached transformed_key becomes invalid.

Returns:

The KDF salt, or None if no header is set

list_attachments(entry)[source]

List all attachment filenames for an entry.

Parameters:

entry (Entry) – Entry to list attachments for

Returns:

List of attachment filenames

Return type:

list[str]

merge(source, *, mode=None)[source]

Merge another database into this one.

Combines entries, groups, history, attachments, and custom icons from the source database into this database using UUID-based matching and timestamp-based conflict resolution.

Parameters:
  • source (Database) – Database to merge from (read-only)

  • mode (MergeMode | None) – Merge mode (STANDARD or SYNCHRONIZE). Defaults to STANDARD. - STANDARD: Add and update only, never deletes - SYNCHRONIZE: Full sync including deletions

Returns:

MergeResult with counts and statistics about the merge

Raises:

MergeError – If merge cannot be completed

Return type:

MergeResult

Example

>>> target_db = Database.open("main.kdbx", password="secret")
>>> source_db = Database.open("branch.kdbx", password="secret")
>>> result = target_db.merge(source_db)
>>> print(f"Added {result.entries_added} entries")
>>> target_db.save()
move_entry(entry, destination)[source]

Move an entry to a different group.

This is a convenience method that calls entry.move_to(). It validates that both the entry and destination belong to this database.

Parameters:
  • entry (Entry) – Entry to move

  • destination (Group) – Target group to move the entry to

Raises:
  • ValueError – If entry or destination is not in this database

  • ValueError – If entry has no parent

  • ValueError – If destination is the current parent

Return type:

None

move_group(group, destination)[source]

Move a group to a different parent group.

This is a convenience method that calls group.move_to(). It validates that both the group and destination belong to this database.

Parameters:
  • group (Group) – Group to move

  • destination (Group) – Target parent group to move the group to

Raises:
  • ValueError – If group or destination is not in this database

  • ValueError – If group is the root group

  • ValueError – If group has no parent

  • ValueError – If destination is the current parent

  • ValueError – If destination is the group itself or a descendant

Return type:

None

classmethod open(filepath, password=None, keyfile=None, yubikey_slot=None, yubikey_serial=None)[source]

Open an existing KDBX database.

Parameters:
  • filepath (str | Path) – Path to the .kdbx file

  • password (str | None) – Database password

  • keyfile (str | Path | None) – Path to keyfile (optional)

  • yubikey_slot (int | None) – YubiKey slot for challenge-response (1 or 2, optional). If provided, the database’s KDF salt is used as challenge and the 20-byte HMAC-SHA1 response is incorporated into key derivation. Requires yubikey-manager package: pip install kdbxtool[yubikey]

  • yubikey_serial (int | None) – Serial number of specific YubiKey to use when multiple devices are connected. Use list_yubikeys() to discover serials.

Returns:

Database instance

Raises:
Return type:

Database

classmethod open_bytes(data, password=None, keyfile_data=None, filepath=None, transformed_key=None, yubikey_slot=None, yubikey_serial=None)[source]

Open a KDBX database from bytes.

Supports both KDBX3 and KDBX4 formats. KDBX3 databases are opened read-only and will be automatically upgraded to KDBX4 on save.

Parameters:
  • data (bytes) – KDBX file contents

  • password (str | None) – Database password

  • keyfile_data (bytes | None) – Keyfile contents (optional)

  • filepath (Path | None) – Original file path (for save)

  • transformed_key (bytes | None) – Precomputed transformed key (skips KDF, faster opens)

  • yubikey_slot (int | None) – YubiKey slot for challenge-response (1 or 2, optional). If provided, the database’s KDF salt is used as challenge and the 20-byte HMAC-SHA1 response is incorporated into key derivation. Requires yubikey-manager package: pip install kdbxtool[yubikey]

  • yubikey_serial (int | None) – Serial number of specific YubiKey to use when multiple devices are connected. Use list_yubikeys() to discover serials.

Returns:

Database instance

Raises:

YubiKeyError – If YubiKey operation fails

Return type:

Database

classmethod open_interactive(filepath, keyfile=None, yubikey_slot=None, yubikey_serial=None, prompt='Password: ', max_attempts=3)[source]

Open a KDBX database with interactive password prompt.

Prompts the user for a password using secure input (no echo). If the password is incorrect, allows retrying up to max_attempts times.

This is a convenience method for CLI applications that need to securely prompt for database credentials.

Parameters:
  • filepath (str | Path) – Path to the .kdbx file

  • keyfile (str | Path | None) – Path to keyfile (optional)

  • yubikey_slot (int | None) – YubiKey slot for challenge-response (1 or 2, optional)

  • yubikey_serial (int | None) – Serial number of specific YubiKey to use

  • prompt (str) – Custom prompt string (default: “Password: “)

  • max_attempts (int) – Maximum password attempts before raising (default: 3)

Returns:

Database instance

Raises:
Return type:

Database

Example

>>> db = Database.open_interactive("vault.kdbx")
Password:
>>> db = Database.open_interactive("vault.kdbx", keyfile="vault.key")
Password:
property recyclebin_group: Group | None

Get the recycle bin group, or None if disabled.

If recycle_bin_enabled is True but no recycle bin exists yet, this creates one automatically.

Returns:

Recycle bin Group, or None if recycle bin is disabled

reload()[source]

Reload the database from disk using stored credentials.

Re-reads the database file and replaces all in-memory state with the current file contents. Useful for discarding unsaved changes or syncing with external modifications.

Raises:
Return type:

None

remove_attachment(entry, name)[source]

Remove an attachment from an entry by filename.

Parameters:
  • entry (Entry) – Entry to remove attachment from

  • name (str) – Filename of the attachment

Returns:

True if removed, False if not found

Return type:

bool

remove_binary(ref)[source]

Remove a binary attachment from the database.

Parameters:

ref (int) – Binary reference ID

Returns:

True if removed, False if not found

Return type:

bool

remove_custom_icon(uuid)[source]

Remove a custom icon from the database.

Note: This does not update entries/groups that reference this icon. They will continue to reference the now-missing UUID.

Parameters:

uuid (UUID) – UUID of the custom icon to remove

Returns:

True if removed, False if not found

Return type:

bool

property root_group: Group

Get the root group of the database.

save(filepath=None, *, allow_upgrade=False, regenerate_seeds=True, kdf_config=None, cipher=None, yubikey_slot=None, yubikey_serial=None)[source]

Save the database to a file.

KDBX3 databases are automatically upgraded to KDBX4 on save. When saving a KDBX3 database to its original file, explicit confirmation is required via the allow_upgrade parameter.

Parameters:
  • filepath (str | Path | None) – Path to save to (uses original path if not specified)

  • allow_upgrade (bool) – Must be True to confirm KDBX3 to KDBX4 upgrade when saving to the original file. Not required when saving to a new file.

  • regenerate_seeds (bool) – If True (default), regenerate all cryptographic seeds (master_seed, encryption_iv, kdf_salt, random_stream_key) on save. Set to False only for testing or when using pre-computed transformed keys.

  • kdf_config (Argon2Config | AesKdfConfig | None) – Optional KDF configuration for KDBX3 upgrade. Use presets like: - Argon2Config.standard() / high_security() / fast() - AesKdfConfig.standard() / high_security() / fast() Defaults to Argon2Config.standard() with Argon2d variant.

  • cipher (Cipher | None) – Optional encryption cipher. Use one of: - Cipher.AES256_CBC (default, widely compatible) - Cipher.CHACHA20 (modern, faster in software) - Cipher.TWOFISH256_CBC (requires oxifish package) If not specified, preserves existing cipher.

  • yubikey_slot (int | None) – YubiKey slot for challenge-response (1 or 2, optional). If provided (or if database was opened with yubikey_slot), the new KDF salt is used as challenge and the response is incorporated into key derivation. Requires yubikey-manager package.

  • yubikey_serial (int | None) – Serial number of specific YubiKey to use when multiple devices are connected. Use list_yubikeys() to discover serials.

Raises:
Return type:

None

set_credentials(password=None, keyfile_data=None)[source]

Set or update database credentials.

Parameters:
  • password (str | None) – New password (None to remove)

  • keyfile_data (bytes | None) – New keyfile data (None to remove)

Raises:

ValueError – If both password and keyfile are None

Return type:

None

property settings: DatabaseSettings

Get database settings.

to_bytes(*, regenerate_seeds=True, kdf_config=None, cipher=None, yubikey_slot=None, yubikey_serial=None)[source]

Serialize the database to KDBX4 format.

KDBX3 databases are automatically upgraded to KDBX4 on save. This includes converting to the specified KDF and ChaCha20 protected stream.

Parameters:
  • regenerate_seeds (bool) – If True (default), regenerate all cryptographic seeds (master_seed, encryption_iv, kdf_salt, random_stream_key) on save. This prevents precomputation attacks where an attacker can derive the encryption key in advance. Set to False only for testing or when using pre-computed transformed keys.

  • kdf_config (Argon2Config | AesKdfConfig | None) – Optional KDF configuration for KDBX3 upgrade. Use presets like: - Argon2Config.standard() / high_security() / fast() - AesKdfConfig.standard() / high_security() / fast() Defaults to Argon2Config.standard() with Argon2d variant.

  • cipher (Cipher | None) – Optional encryption cipher. Use one of: - Cipher.AES256_CBC (default, widely compatible) - Cipher.CHACHA20 (modern, faster in software) - Cipher.TWOFISH256_CBC (requires oxifish package) If not specified, preserves existing cipher.

  • yubikey_slot (int | None) – YubiKey slot for challenge-response (1 or 2, optional). If provided, the (new) KDF salt is used as challenge and the 20-byte HMAC-SHA1 response is incorporated into key derivation. Requires yubikey-manager package: pip install kdbxtool[yubikey]

  • yubikey_serial (int | None) – Serial number of specific YubiKey to use when multiple devices are connected. Use list_yubikeys() to discover serials.

Returns:

KDBX4 file contents as bytes

Raises:
Return type:

bytes

property transformed_key: bytes | None

Get the transformed key for caching.

The transformed key is the result of applying the KDF (Argon2) to the credentials. Caching this allows fast repeated database opens without re-running the expensive KDF.

Security note: The transformed key is as sensitive as the password. Anyone with this key can decrypt the database. Store securely and zeroize when done.

Returns:

The transformed key, or None if not available (e.g., newly created DB)

trash_entry(entry)[source]

Move an entry to the recycle bin.

If the entry is already in the recycle bin, it is permanently deleted.

Parameters:

entry (Entry) – Entry to trash

Raises:
Return type:

None

trash_group(group)[source]

Move a group to the recycle bin.

If the group is already in the recycle bin, it is permanently deleted. Cannot trash the root group or the recycle bin itself.

Parameters:

group (Group) – Group to trash

Raises:
Return type:

None

xml(*, pretty_print=False)[source]

Export database XML payload.

Returns the decrypted, decompressed XML payload of the database. Protected values (passwords, etc.) are shown in plaintext. Useful for debugging and migration.

Parameters:

pretty_print (bool) – If True, format XML with indentation for readability

Returns:

XML payload as bytes (UTF-8 encoded)

Return type:

bytes

zeroize_credentials()[source]

Explicitly zeroize stored credentials from memory.

Call this when done with the database to minimize the time credentials remain in memory. Note that Python’s string interning may retain copies; for maximum security, use SecureBytes for credential input.

Return type:

None

class kdbxtool.DatabaseSettings(generator='kdbxtool', database_name='Database', database_description='', default_username='', maintenance_history_days=365, color=None, master_key_change_rec=-1, master_key_change_force=-1, memory_protection=<factory>, recycle_bin_enabled=True, recycle_bin_uuid=None, history_max_items=10, history_max_size=6291456, custom_icons=<factory>, deleted_objects=<factory>)[source]

Bases: object

Settings for a KDBX database.

Parameters:
  • generator (str)

  • database_name (str)

  • database_description (str)

  • default_username (str)

  • maintenance_history_days (int)

  • color (str | None)

  • master_key_change_rec (int)

  • master_key_change_force (int)

  • memory_protection (dict[str, bool])

  • recycle_bin_enabled (bool)

  • recycle_bin_uuid (uuid_module.UUID | None)

  • history_max_items (int)

  • history_max_size (int)

  • custom_icons (dict[uuid_module.UUID, CustomIcon])

  • deleted_objects (list[DeletedObject])

generator

Generator application name

Type:

str

database_name

Name of the database

Type:

str

database_description

Description of the database

Type:

str

default_username

Default username for new entries

Type:

str

maintenance_history_days

Days to keep deleted items

Type:

int

color

Database color (hex)

Type:

str | None

master_key_change_rec

Days until master key change recommended

Type:

int

master_key_change_force

Days until master key change forced

Type:

int

memory_protection

Which fields to protect in memory

Type:

dict[str, bool]

recycle_bin_enabled

Whether recycle bin is enabled

Type:

bool

recycle_bin_uuid

UUID of recycle bin group

Type:

uuid_module.UUID | None

history_max_items

Max history entries per entry

Type:

int

history_max_size

Max history size in bytes

Type:

int

custom_icons

Dictionary of custom icons (UUID -> CustomIcon)

Type:

dict[uuid_module.UUID, CustomIcon]

__init__(generator='kdbxtool', database_name='Database', database_description='', default_username='', maintenance_history_days=365, color=None, master_key_change_rec=-1, master_key_change_force=-1, memory_protection=<factory>, recycle_bin_enabled=True, recycle_bin_uuid=None, history_max_items=10, history_max_size=6291456, custom_icons=<factory>, deleted_objects=<factory>)
Parameters:
  • generator (str)

  • database_name (str)

  • database_description (str)

  • default_username (str)

  • maintenance_history_days (int)

  • color (str | None)

  • master_key_change_rec (int)

  • master_key_change_force (int)

  • memory_protection (dict[str, bool])

  • recycle_bin_enabled (bool)

  • recycle_bin_uuid (uuid_module.UUID | None)

  • history_max_items (int)

  • history_max_size (int)

  • custom_icons (dict[uuid_module.UUID, CustomIcon])

  • deleted_objects (list[DeletedObject])

Return type:

None

color: str | None = None
database_description: str = ''
database_name: str = 'Database'
default_username: str = ''
generator: str = 'kdbxtool'
history_max_items: int = 10
history_max_size: int = 6291456
maintenance_history_days: int = 365
master_key_change_force: int = -1
master_key_change_rec: int = -1
recycle_bin_enabled: bool = True
recycle_bin_uuid: uuid_module.UUID | None = None
memory_protection: dict[str, bool]
custom_icons: dict[uuid_module.UUID, CustomIcon]
deleted_objects: list[DeletedObject]
class kdbxtool.Entry(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)[source]

Bases: object

A password entry in a KDBX database.

Entries store credentials and associated metadata. Each entry has standard fields (title, username, password, url, notes) plus support for custom string fields and binary attachments.

Parameters:
uuid

Unique identifier for the entry

Type:

uuid_module.UUID

times

Timestamps (creation, modification, access, expiry)

Type:

Times

icon_id

Icon ID for display (standard icon)

Type:

str

custom_icon_uuid

UUID of custom icon (overrides icon_id if set)

Type:

uuid_module.UUID | None

tags

List of tags for categorization

Type:

list[str]

strings

Dictionary of string fields (key -> StringField)

Type:

dict[str, StringField]

binaries

List of binary attachment references

Type:

list[BinaryRef]

autotype

AutoType settings

Type:

AutoType

history

List of previous versions of this entry

Type:

list[HistoryEntry]

foreground_color

Custom foreground color (hex)

Type:

str | None

background_color

Custom background color (hex)

Type:

str | None

override_url

URL override for AutoType

Type:

str | None

quality_check

Whether to check password quality

Type:

bool

__init__(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)
Parameters:
Return type:

None

background_color: str | None = None
clear_history()[source]

Clear all history entries.

This is a convenience method equivalent to delete_history(all=True).

Return type:

None

classmethod create(title=None, username=None, password=None, url=None, notes=None, tags=None, icon_id='0', expires=False, expiry_time=None)[source]

Create a new entry with common fields.

Parameters:
  • title (str | None) – Entry title

  • username (str | None) – Username

  • password (str | None) – Password

  • url (str | None) – URL

  • notes (str | None) – Notes

  • tags (list[str] | None) – List of tags

  • icon_id (str) – Icon ID

  • expires (bool) – Whether entry expires

  • expiry_time (datetime | None) – Expiration time

Returns:

New Entry instance

Return type:

Entry

property custom_icon: UUID | None

Get or set custom icon by UUID or name.

When setting, accepts either a UUID or an icon name (string). If a string is provided, it must match exactly one icon name in the database. Requires the entry to be associated with a database for name-based lookup.

Returns:

UUID of the custom icon, or None if not set

custom_icon_uuid: uuid_module.UUID | None = None
property custom_properties: dict[str, str | None]

Get all custom properties as a dictionary.

property database: Database | None

Get the database this entry belongs to.

delete_custom_property(key)[source]

Delete a custom property.

Parameters:

key (str) – Property name to delete

Raises:
Return type:

None

delete_history(history_entry=None, *, all=False)[source]

Delete history entries.

Either deletes a specific history entry or all history entries. At least one of history_entry or all=True must be specified.

Parameters:
  • history_entry (HistoryEntry | None) – Specific history entry to delete

  • all (bool) – If True, delete all history entries

Raises:
  • ValueError – If neither history_entry nor all=True is specified

  • ValueError – If history_entry is not in this entry’s history

Return type:

None

deref(field)[source]

Resolve any field references in the given field’s value.

If the field’s value contains KeePass field references ({REF:X@Y:Z}), resolves them to the actual values from the referenced entries.

Parameters:

field (str) – One of ‘title’, ‘username’, ‘password’, ‘url’, ‘notes’

Returns:

The resolved value with all references replaced, a UUID if the referenced field is ‘uuid’, or None if a referenced entry is not found

Raises:

ValueError – If no database reference is available

Return type:

str | UUID | None

Example

>>> # If entry.password contains '{REF:P@I:...UUID...}'
>>> actual_password = entry.deref('password')
dump()[source]

Return a human-readable summary of the entry for debugging.

Returns:

Multi-line string with entry details (passwords are masked).

Return type:

str

property expired: bool

Check if entry has expired.

foreground_color: str | None = None
get_custom_property(key)[source]

Get a custom property value.

Parameters:

key (str) – Property name (must not be a reserved key)

Returns:

Property value, or None if not set

Raises:

ValueError – If key is a reserved key

Return type:

str | None

icon_id: str = '0'
property index: int

Get the index of this entry within its parent group.

Returns:

Zero-based index of this entry in the parent’s entries list.

Raises:

ValueError – If entry has no parent group.

move_to(destination)[source]

Move this entry to a different group.

Removes the entry from its current parent and adds it to the destination group. Updates the location_changed timestamp.

Parameters:

destination (Group) – Target group to move the entry to

Raises:
  • ValueError – If entry has no parent (not yet added to a group)

  • ValueError – If destination is the current parent (no-op would be confusing)

Return type:

None

property notes: str | None

Get or set entry notes.

property otp: str | None

Get or set OTP secret (TOTP/HOTP).

override_url: str | None = None
property parent: Group | None

Get parent group.

property password: str | None

Get or set entry password.

quality_check: bool = True
ref(field)[source]

Create a reference string pointing to a field of this entry.

Creates a KeePass field reference string that can be used in other entries to reference values from this entry. References use the entry’s UUID for lookup.

Parameters:

field (str) – One of ‘title’, ‘username’, ‘password’, ‘url’, ‘notes’, or ‘uuid’

Returns:

X@I:UUID}

Return type:

Field reference string in format {REF

Raises:

ValueError – If field is not a valid field name

Example

>>> main_entry = db.find_entries(title='Main Account', first=True)
>>> ref_string = main_entry.ref('password')
>>> # Returns '{REF:P@I:...UUID...}'
>>> other_entry.password = ref_string
reindex(new_index)[source]

Move this entry to a new position within its parent group.

Parameters:

new_index (int) – Target position (zero-based). Negative indices are supported (e.g., -1 for last position).

Raises:
Return type:

None

save_history()[source]

Save current state to history before making changes.

Return type:

None

set_custom_property(key, value, protected=False)[source]

Set a custom property.

Parameters:
  • key (str) – Property name (must not be a reserved key)

  • value (str) – Property value

  • protected (bool) – Whether to mark as protected in memory

Raises:

ValueError – If key is a reserved key

Return type:

None

property title: str | None

Get or set entry title.

totp(*, at=None)[source]

Generate current TOTP code from the entry’s otp field.

Supports both standard otpauth:// URIs and KeePassXC legacy format (TOTP Seed / TOTP Settings custom fields).

Parameters:

at (datetime | float | None) – Optional timestamp for code generation. Can be a datetime or Unix timestamp float. Defaults to current time.

Returns:

TotpCode object with code and expiration info, or None if no OTP configured.

Raises:

ValueError – If OTP configuration is invalid

Return type:

TotpCode | None

Example

>>> result = entry.totp()
>>> print(f"Code: {result.code}")
Code: 123456
>>> print(f"Expires in {result.remaining}s")
Expires in 15s
>>> # TotpCode also works as a string
>>> print(result)
123456
touch(modify=False)[source]

Update access time, optionally modification time.

Parameters:

modify (bool)

Return type:

None

property url: str | None

Get or set entry URL.

property username: str | None

Get or set entry username.

uuid: uuid_module.UUID
times: Times
tags: list[str]
strings: dict[str, StringField]
binaries: list[BinaryRef]
autotype: AutoType
history: list[HistoryEntry]
class kdbxtool.Group(uuid=<factory>, name=None, notes=None, times=<factory>, icon_id='48', custom_icon_uuid=None, is_expanded=True, default_autotype_sequence=None, enable_autotype=None, enable_searching=None, last_top_visible_entry=None, entries=<factory>, subgroups=<factory>, _parent=None, _is_root=False, _database=None)[source]

Bases: object

A group (folder) in a KDBX database.

Groups organize entries into a hierarchical structure. Each group can contain entries and subgroups.

Parameters:
  • uuid (uuid_module.UUID)

  • name (str | None)

  • notes (str | None)

  • times (Times)

  • icon_id (str)

  • custom_icon_uuid (uuid_module.UUID | None)

  • is_expanded (bool)

  • default_autotype_sequence (str | None)

  • enable_autotype (bool | None)

  • enable_searching (bool | None)

  • last_top_visible_entry (uuid_module.UUID | None)

  • entries (list[Entry])

  • subgroups (list[Group])

  • _parent (Group | None)

  • _is_root (bool)

  • _database (Database | None)

uuid

Unique identifier for the group

Type:

uuid_module.UUID

name

Display name of the group

Type:

str | None

notes

Optional notes/description

Type:

str | None

times

Timestamps (creation, modification, access, expiry)

Type:

Times

icon_id

Icon ID for display (standard icon)

Type:

str

custom_icon_uuid

UUID of custom icon (overrides icon_id if set)

Type:

uuid_module.UUID | None

is_expanded

Whether group is expanded in UI

Type:

bool

default_autotype_sequence

Default AutoType sequence for entries

Type:

str | None

enable_autotype

Whether AutoType is enabled for this group

Type:

bool | None

enable_searching

Whether entries in this group are searchable

Type:

bool | None

last_top_visible_entry

UUID of last visible entry (UI state)

Type:

uuid_module.UUID | None

entries

List of entries in this group

Type:

list[Entry]

subgroups

List of subgroups

Type:

list[Group]

__init__(uuid=<factory>, name=None, notes=None, times=<factory>, icon_id='48', custom_icon_uuid=None, is_expanded=True, default_autotype_sequence=None, enable_autotype=None, enable_searching=None, last_top_visible_entry=None, entries=<factory>, subgroups=<factory>, _parent=None, _is_root=False, _database=None)
Parameters:
  • uuid (uuid_module.UUID)

  • name (str | None)

  • notes (str | None)

  • times (Times)

  • icon_id (str)

  • custom_icon_uuid (uuid_module.UUID | None)

  • is_expanded (bool)

  • default_autotype_sequence (str | None)

  • enable_autotype (bool | None)

  • enable_searching (bool | None)

  • last_top_visible_entry (uuid_module.UUID | None)

  • entries (list[Entry])

  • subgroups (list[Group])

  • _parent (Group | None)

  • _is_root (bool)

  • _database (Database | None)

Return type:

None

add_entry(entry)[source]

Add an entry to this group.

Parameters:

entry (Entry) – Entry to add

Returns:

The added entry

Return type:

Entry

add_subgroup(group)[source]

Add a subgroup to this group.

Parameters:

group (Group) – Group to add

Returns:

The added group

Return type:

Group

create_entry(title=None, username=None, password=None, url=None, notes=None, tags=None, *, template=None)[source]

Create and add a new entry to this group.

Parameters:
  • title (str | None) – Entry title

  • username (str | None) – Username

  • password (str | None) – Password

  • url (str | None) – URL

  • notes (str | None) – Notes

  • tags (list[str] | None) – Tags

  • template (EntryTemplate | None) – Optional entry template instance with field values

Returns:

Newly created entry

Return type:

Entry

Example

>>> # Standard entry (no template)
>>> entry = group.create_entry(title="Site", username="user", password="pass")
>>> # Using a template with typed fields
>>> from kdbxtool import Templates
>>> entry = group.create_entry(
...     title="My Visa",
...     template=Templates.CreditCard(
...         card_number="4111111111111111",
...         expiry_date="12/25",
...         cvv="123",
...     ),
... )
>>> # Server template with standard fields
>>> entry = group.create_entry(
...     title="prod-server",
...     username="admin",
...     password="secret",
...     template=Templates.Server(
...         hostname="192.168.1.1",
...         port="22",
...     ),
... )
classmethod create_root(name='Root')[source]

Create a root group for a new database.

Parameters:

name (str) – Name for the root group

Returns:

New root Group instance

Return type:

Group

create_subgroup(name, notes=None, icon_id='48')[source]

Create and add a new subgroup.

Parameters:
  • name (str) – Group name

  • notes (str | None) – Optional notes

  • icon_id (str) – Icon ID

Returns:

Newly created group

Return type:

Group

property custom_icon: UUID | None

Get or set custom icon by UUID or name.

When setting, accepts either a UUID or an icon name (string). If a string is provided, it must match exactly one icon name in the database. Requires the group to be associated with a database for name-based lookup.

Returns:

UUID of the custom icon, or None if not set

custom_icon_uuid: uuid_module.UUID | None = None
property database: Database | None

Get the database this group belongs to.

default_autotype_sequence: str | None = None
dump(recursive=False)[source]

Return a human-readable summary of the group for debugging.

Parameters:

recursive (bool) – If True, include subgroups and entries recursively

Returns:

Multi-line string with group details.

Return type:

str

enable_autotype: bool | None = None
enable_searching: bool | None = None
property expired: bool

Check if group has expired.

find_entries(title=None, username=None, password=None, url=None, notes=None, otp=None, tags=None, string=None, autotype_enabled=None, autotype_sequence=None, autotype_window=None, recursive=True, history=False)[source]

Find entries matching criteria.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Match entries with this title (exact)

  • username (str | None) – Match entries with this username (exact)

  • password (str | None) – Match entries with this password (exact)

  • url (str | None) – Match entries with this URL (exact)

  • notes (str | None) – Match entries with these notes (exact)

  • otp (str | None) – Match entries with this OTP (exact)

  • tags (list[str] | None) – Match entries containing all these tags

  • string (dict[str, str] | None) – Match entries with custom properties (dict of key:value)

  • autotype_enabled (bool | None) – Filter by AutoType enabled state

  • autotype_sequence (str | None) – Match entries with this AutoType sequence (exact)

  • autotype_window (str | None) – Match entries with this AutoType window (exact)

  • recursive (bool) – Search in subgroups

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Return type:

list[Entry]

find_entries_contains(title=None, username=None, password=None, url=None, notes=None, otp=None, recursive=True, case_sensitive=False, history=False)[source]

Find entries where fields contain the given substrings.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Match entries whose title contains this substring

  • username (str | None) – Match entries whose username contains this substring

  • password (str | None) – Match entries whose password contains this substring

  • url (str | None) – Match entries whose URL contains this substring

  • notes (str | None) – Match entries whose notes contain this substring

  • otp (str | None) – Match entries whose OTP contains this substring

  • recursive (bool) – Search in subgroups

  • case_sensitive (bool) – If False (default), matching is case-insensitive

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Return type:

list[Entry]

find_entries_regex(title=None, username=None, password=None, url=None, notes=None, otp=None, recursive=True, case_sensitive=False, history=False)[source]

Find entries where fields match the given regex patterns.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Regex pattern to match against title

  • username (str | None) – Regex pattern to match against username

  • password (str | None) – Regex pattern to match against password

  • url (str | None) – Regex pattern to match against URL

  • notes (str | None) – Regex pattern to match against notes

  • otp (str | None) – Regex pattern to match against OTP

  • recursive (bool) – Search in subgroups

  • case_sensitive (bool) – If False (default), matching is case-insensitive

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Raises:

re.error – If any pattern is not a valid regex

Return type:

list[Entry]

find_entry_by_uuid(uuid, recursive=True)[source]

Find an entry by UUID.

Parameters:
  • uuid (UUID) – Entry UUID to find

  • recursive (bool) – Search in subgroups

Returns:

Entry if found, None otherwise

Return type:

Entry | None

find_group_by_uuid(uuid, recursive=True)[source]

Find a group by UUID.

Parameters:
  • uuid (UUID) – Group UUID to find

  • recursive (bool) – Search in nested subgroups

Returns:

Group if found, None otherwise

Return type:

Group | None

find_groups(name=None, recursive=True, first=False)[source]

Find groups matching criteria.

Parameters:
  • name (str | None) – Match groups with this name (exact)

  • recursive (bool) – Search in nested subgroups

  • first (bool) – If True, return first matching group or None instead of list

Returns:

List of matching groups, or single Group/None if first=True

Return type:

list[Group] | Group | None

icon_id: str = '48'
property index: int

Get the index of this group within its parent group.

Returns:

Zero-based index of this group in the parent’s subgroups list.

Raises:

ValueError – If group has no parent (is root group).

is_expanded: bool = True
property is_root_group: bool

Check if this is the database root group.

iter_entries(recursive=True, history=False)[source]

Iterate over entries in this group.

Parameters:
  • recursive (bool) – If True, include entries from all subgroups

  • history (bool) – If True, include history entries

Yields:

Entry objects

Return type:

Iterator[Entry]

iter_groups(recursive=True)[source]

Iterate over subgroups.

Parameters:

recursive (bool) – If True, include nested subgroups

Yields:

Group objects

Return type:

Iterator[Group]

last_top_visible_entry: uuid_module.UUID | None = None
move_to(destination)[source]

Move this group to a different parent group.

Removes the group from its current parent and adds it to the destination group. Updates the location_changed timestamp.

Parameters:

destination (Group) – Target parent group to move this group to

Raises:
  • ValueError – If this is the root group (cannot be moved)

  • ValueError – If group has no parent (not yet added to a database)

  • ValueError – If destination is the current parent

  • ValueError – If destination is this group (cannot move into self)

  • ValueError – If destination is a descendant of this group (would create cycle)

Return type:

None

name: str | None = None
notes: str | None = None
property parent: Group | None

Get parent group, or None if this is the root.

property path: list[str]

Get path from root to this group.

Returns:

List of group names from root (exclusive) to this group (inclusive). Empty list for the root group.

reindex(new_index)[source]

Move this group to a new position within its parent group.

Parameters:

new_index (int) – Target position (zero-based). Negative indices are supported (e.g., -1 for last position).

Raises:
  • ValueError – If group has no parent (is root group).

  • IndexError – If new_index is out of range.

Return type:

None

remove_entry(entry)[source]

Remove an entry from this group.

Parameters:

entry (Entry) – Entry to remove

Raises:

ValueError – If entry is not in this group

Return type:

None

remove_subgroup(group)[source]

Remove a subgroup from this group.

Parameters:

group (Group) – Group to remove

Raises:

ValueError – If group is not a subgroup of this group

Return type:

None

touch(modify=False)[source]

Update access time, optionally modification time.

Parameters:

modify (bool)

Return type:

None

uuid: uuid_module.UUID
times: Times
entries: list[Entry]
subgroups: list[Group]
class kdbxtool.HistoryEntry(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)[source]

Bases: Entry

A historical version of an entry.

History entries are snapshots of an entry at a previous point in time. They share the same UUID as their parent entry.

Parameters:
__init__(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)
Parameters:
Return type:

None

classmethod from_entry(entry)[source]

Create a history entry from an existing entry.

Parameters:

entry (Entry) – Entry to create history from

Returns:

New HistoryEntry with copied data

Return type:

HistoryEntry

class kdbxtool.Times(creation_time=<factory>, last_modification_time=<factory>, last_access_time=<factory>, expiry_time=None, expires=False, usage_count=0, location_changed=None)[source]

Bases: object

Timestamps associated with entries and groups.

All times are stored as timezone-aware UTC datetimes.

Parameters:
creation_time

When the element was created

Type:

datetime.datetime

last_modification_time

When the element was last modified

Type:

datetime.datetime

last_access_time

When the element was last accessed

Type:

datetime.datetime

expiry_time

When the element expires (if expires is True)

Type:

datetime.datetime | None

expires

Whether the element can expire

Type:

bool

usage_count

Number of times the element has been used

Type:

int

location_changed

When the element was moved to a different group

Type:

datetime.datetime | None

__init__(creation_time=<factory>, last_modification_time=<factory>, last_access_time=<factory>, expiry_time=None, expires=False, usage_count=0, location_changed=None)
Parameters:
Return type:

None

classmethod create_new(expires=False, expiry_time=None)[source]

Create timestamps for a new element.

Parameters:
  • expires (bool) – Whether the element can expire

  • expiry_time (datetime | None) – When the element expires

Returns:

New Times instance with current timestamps

Return type:

Times

property expired: bool

Check if the element has expired.

Returns:

True if expires is True and expiry_time is in the past

expires: bool = False
expiry_time: datetime | None = None
increment_usage()[source]

Increment usage count and update access time.

Return type:

None

location_changed: datetime | None = None
touch(modify=False)[source]

Update access time, and optionally modification time.

Parameters:

modify (bool) – If True, also update modification time

Return type:

None

update_location()[source]

Update location_changed timestamp when element is moved.

Return type:

None

usage_count: int = 0
creation_time: datetime
last_modification_time: datetime
last_access_time: datetime
class kdbxtool.Cipher(*values)[source]

Bases: Enum

Supported ciphers for KDBX encryption.

KDBX supports three ciphers: - AES-256-CBC: Traditional cipher, widely supported - ChaCha20: Modern stream cipher, faster in software - Twofish-256-CBC: Legacy cipher, requires oxifish package

Note: KDBX uses plain ChaCha20, not ChaCha20-Poly1305. Authentication is provided by the HMAC block stream.

The UUID values are defined in the KDBX specification.

property key_size: int

Return the key size in bytes for this cipher.

property iv_size: int

Return the IV/nonce size in bytes for this cipher.

property display_name: str

Human-readable cipher name.

classmethod from_uuid(uuid_bytes)[source]

Look up cipher by its KDBX UUID.

Parameters:

uuid_bytes (bytes) – 16-byte cipher identifier from KDBX header

Returns:

The corresponding Cipher enum value

Raises:

ValueError – If the UUID doesn’t match any known cipher

Return type:

Cipher

AES256_CBC = b'1\xc1\xf2\xe6\xbfqCP\xbeX\x05!j\xfcZ\xff'
CHACHA20 = b'\xd6\x03\x8a+\x8boL\xb5\xa5$3\x9a1\xdb\xb5\x9a'
TWOFISH256_CBC = b'\xadh\xf2\x9fWoK\xb9\xa3j\xd4z\xf9e4l'
class kdbxtool.KdfType(*values)[source]

Bases: Enum

Supported Key Derivation Functions in KDBX.

The UUID values are defined in the KDBX specification.

property display_name: str

Human-readable KDF name.

classmethod from_uuid(uuid_bytes)[source]

Look up KDF by its KDBX UUID.

Parameters:

uuid_bytes (bytes) – 16-byte KDF identifier from KDBX header

Returns:

The corresponding KdfType enum value

Raises:

ValueError – If the UUID doesn’t match any known KDF

Return type:

KdfType

ARGON2D = b'\xefcm\xdf\x8c)DK\x91\xf7\xa9\xa4\x03\xe3\n\x0c'
ARGON2ID = b'\x9e)\x8b\x19V\xdbGs\xb2=\xfc>\xc6\xf0\xa1\xe6'
AES_KDF = b'\xc9\xd9\xf3\x9ab\x8aD`\xbft\r\x08\xc1\x8aO\xea'
class kdbxtool.MergeMode(*values)[source]

Bases: Enum

Merge mode determining how conflicts and deletions are handled.

STANDARD

Add and update entries/groups from source. Does not delete anything from target. This is the default and safest mode.

SYNCHRONIZE

Full bidirectional sync including deletions. Items deleted in source (tracked in DeletedObjects) will be deleted from target if they haven’t been modified after the deletion time.

STANDARD = 1
SYNCHRONIZE = 2
class kdbxtool.MergeResult(entries_added=0, entries_updated=0, entries_relocated=0, entries_deleted=0, groups_added=0, groups_updated=0, groups_relocated=0, groups_deleted=0, history_entries_merged=0, binaries_added=0, custom_icons_added=0)[source]

Bases: object

Result of a database merge operation.

Contains detailed statistics about what was changed during the merge.

Parameters:
  • entries_added (int)

  • entries_updated (int)

  • entries_relocated (int)

  • entries_deleted (int)

  • groups_added (int)

  • groups_updated (int)

  • groups_relocated (int)

  • groups_deleted (int)

  • history_entries_merged (int)

  • binaries_added (int)

  • custom_icons_added (int)

entries_added

Number of new entries added from source

Type:

int

entries_updated

Number of existing entries updated (source was newer)

Type:

int

entries_relocated

Number of entries moved to different groups

Type:

int

entries_deleted

Number of entries deleted (SYNCHRONIZE mode only)

Type:

int

groups_added

Number of new groups added from source

Type:

int

groups_updated

Number of existing groups updated (source was newer)

Type:

int

groups_relocated

Number of groups moved to different parents

Type:

int

groups_deleted

Number of groups deleted (SYNCHRONIZE mode only)

Type:

int

history_entries_merged

Number of history entries added

Type:

int

binaries_added

Number of new binary attachments added

Type:

int

custom_icons_added

Number of new custom icons added

Type:

int

__init__(entries_added=0, entries_updated=0, entries_relocated=0, entries_deleted=0, groups_added=0, groups_updated=0, groups_relocated=0, groups_deleted=0, history_entries_merged=0, binaries_added=0, custom_icons_added=0)
Parameters:
  • entries_added (int)

  • entries_updated (int)

  • entries_relocated (int)

  • entries_deleted (int)

  • groups_added (int)

  • groups_updated (int)

  • groups_relocated (int)

  • groups_deleted (int)

  • history_entries_merged (int)

  • binaries_added (int)

  • custom_icons_added (int)

Return type:

None

binaries_added: int = 0
custom_icons_added: int = 0
entries_added: int = 0
entries_deleted: int = 0
entries_relocated: int = 0
entries_updated: int = 0
groups_added: int = 0
groups_deleted: int = 0
groups_relocated: int = 0
groups_updated: int = 0
property has_changes: bool

Check if any changes were made during the merge.

history_entries_merged: int = 0
summary()[source]

Get a human-readable summary of the merge result.

Return type:

str

property total_changes: int

Total number of changes made.

class kdbxtool.DeletedObject(uuid, deletion_time)[source]

Bases: object

Record of a deleted entry or group.

Used in SYNCHRONIZE mode to track deletions that should propagate to other databases during merge.

Parameters:
uuid

UUID of the deleted entry or group

Type:

uuid.UUID

deletion_time

When the deletion occurred

Type:

datetime.datetime

__init__(uuid, deletion_time)
Parameters:
Return type:

None

uuid: UUID
deletion_time: datetime
class kdbxtool.EntryTemplate[source]

Bases: object

Base class for entry templates. Subclass to create custom templates.

Class variables to override:

_icon_id: Icon for entries using this template (default: KEY) _include_standard: Whether to populate username/password/url (default: True) _protected_fields: Field names that should be memory-protected

Example

>>> @dataclass
... class VPNConnection(EntryTemplate):
...     _icon_id: ClassVar[int] = IconId.TERMINAL_ENCRYPTED
...     _protected_fields: ClassVar[frozenset[str]] = frozenset({"certificate"})
...
...     server: str | None = None
...     protocol: str = "OpenVPN"
...     certificate: str | None = None
...
>>> entry = group.create_entry(
...     title="Work VPN",
...     template=VPNConnection(server="vpn.company.com"),
... )
__init__()
Return type:

None

class kdbxtool.IconId(*values)[source]

Bases: IntEnum

KeePass standard icon IDs.

These correspond to the PwIcon enumeration in KeePass. There are 69 standard icons (0-68) built into KeePass/KeePassXC.

KEY = 0
WORLD = 1
WARNING = 2
NETWORK_SERVER = 3
MARKED_DIRECTORY = 4
USER_COMMUNICATION = 5
PARTS = 6
NOTEPAD = 7
WORLD_SOCKET = 8
IDENTITY = 9
PAPER_READY = 10
DIGICAM = 11
IR_COMMUNICATION = 12
MULTI_KEYS = 13
ENERGY = 14
SCANNER = 15
WORLD_STAR = 16
CDROM = 17
MONITOR = 18
EMAIL = 19
CONFIGURATION = 20
CLIPBOARD_READY = 21
PAPER_NEW = 22
SCREEN = 23
ENERGY_CAREFUL = 24
EMAIL_BOX = 25
DISK = 26
DRIVE = 27
PAPER_Q = 28
TERMINAL_ENCRYPTED = 29
CONSOLE = 30
PRINTER = 31
PROGRAM_ICONS = 32
RUN = 33
SETTINGS = 34
WORLD_COMPUTER = 35
ARCHIVE = 36
HOMEBANKING = 37
DRIVE_WINDOWS = 38
CLOCK = 39
PAPER_FLAG = 41
MEMORY = 42
TRASH_BIN = 43
NOTE = 44
EXPIRED = 45
INFO = 46
PACKAGE = 47
FOLDER = 48
FOLDER_OPEN = 49
FOLDER_PACKAGE = 50
LOCK_OPEN = 51
PAPER_LOCKED = 52
CHECKED = 53
PEN = 54
THUMBNAIL = 55
BOOK = 56
LIST = 57
USER_KEY = 58
TOOL = 59
HOME = 60
STAR = 61
TUX = 62
FEATHER = 63
APPLE = 64
WIKI = 65
MONEY = 66
CERTIFICATE = 67
BLACKBERRY = 68
class kdbxtool.Templates[source]

Bases: object

Namespace containing all built-in entry templates.

Provides discoverability via IDE autocompletion.

Usage:
>>> from kdbxtool import Templates
>>>
>>> entry = group.create_entry(
...     title="My Card",
...     template=Templates.CreditCard(
...         card_number="4111111111111111",
...         cvv="123",
...     ),
... )
Available templates:
  • Login: Standard login (username, password, url)

  • CreditCard: Card number, expiry, CVV, cardholder, PIN

  • SecureNote: Notes-only entry

  • Identity: Personal information (name, address, etc.)

  • BankAccount: Account and routing numbers

  • Server: Hostname, port, SSH key

  • WirelessRouter: SSID, security type, admin credentials

  • Email: Email address and server settings

  • SoftwareLicense: License key and registration info

  • Database: Database connection details

class BankAccount(bank_name=None, account_type=None, account_number=None, routing_number=None, swift_bic=None, iban=None, pin=None)

Bases: EntryTemplate

Bank account entry template.

Includes account details and routing information. Sensitive fields (account_number, iban, pin) are memory-protected. Does not use standard username/password fields.

Parameters:
  • bank_name (str | None)

  • account_type (str | None)

  • account_number (str | None)

  • routing_number (str | None)

  • swift_bic (str | None)

  • iban (str | None)

  • pin (str | None)

__init__(bank_name=None, account_type=None, account_number=None, routing_number=None, swift_bic=None, iban=None, pin=None)
Parameters:
  • bank_name (str | None)

  • account_type (str | None)

  • account_number (str | None)

  • routing_number (str | None)

  • swift_bic (str | None)

  • iban (str | None)

  • pin (str | None)

Return type:

None

account_number: str | None = None
account_type: str | None = None
bank_name: str | None = None
iban: str | None = None
pin: str | None = None
routing_number: str | None = None
swift_bic: str | None = None
class CreditCard(card_number=None, expiry_date=None, cvv=None, cardholder_name=None, pin=None)

Bases: EntryTemplate

Credit card entry template.

Includes card number, expiry date, CVV, cardholder name, and PIN. Sensitive fields (card_number, cvv, pin) are memory-protected. Does not use standard username/password fields.

Parameters:
  • card_number (str | None)

  • expiry_date (str | None)

  • cvv (str | None)

  • cardholder_name (str | None)

  • pin (str | None)

__init__(card_number=None, expiry_date=None, cvv=None, cardholder_name=None, pin=None)
Parameters:
  • card_number (str | None)

  • expiry_date (str | None)

  • cvv (str | None)

  • cardholder_name (str | None)

  • pin (str | None)

Return type:

None

card_number: str | None = None
cardholder_name: str | None = None
cvv: str | None = None
expiry_date: str | None = None
pin: str | None = None
Database

alias of DatabaseConnection

class Email(email_address=None, imap_server=None, imap_port='993', smtp_server=None, smtp_port='587')

Bases: EntryTemplate

Email account entry template.

Includes email address and server settings. Uses standard username/password fields for credentials.

Parameters:
  • email_address (str | None)

  • imap_server (str | None)

  • imap_port (str)

  • smtp_server (str | None)

  • smtp_port (str)

__init__(email_address=None, imap_server=None, imap_port='993', smtp_server=None, smtp_port='587')
Parameters:
  • email_address (str | None)

  • imap_server (str | None)

  • imap_port (str)

  • smtp_server (str | None)

  • smtp_port (str)

Return type:

None

email_address: str | None = None
imap_port: str = '993'
imap_server: str | None = None
smtp_port: str = '587'
smtp_server: str | None = None
class Identity(first_name=None, last_name=None, email=None, phone=None, address=None, city=None, state=None, postal_code=None, country=None)

Bases: EntryTemplate

Identity/personal information entry template.

Includes name, contact, and address fields. Does not use standard username/password fields.

Parameters:
  • first_name (str | None)

  • last_name (str | None)

  • email (str | None)

  • phone (str | None)

  • address (str | None)

  • city (str | None)

  • state (str | None)

  • postal_code (str | None)

  • country (str | None)

__init__(first_name=None, last_name=None, email=None, phone=None, address=None, city=None, state=None, postal_code=None, country=None)
Parameters:
  • first_name (str | None)

  • last_name (str | None)

  • email (str | None)

  • phone (str | None)

  • address (str | None)

  • city (str | None)

  • state (str | None)

  • postal_code (str | None)

  • country (str | None)

Return type:

None

address: str | None = None
city: str | None = None
country: str | None = None
email: str | None = None
first_name: str | None = None
last_name: str | None = None
phone: str | None = None
postal_code: str | None = None
state: str | None = None
class Login

Bases: EntryTemplate

Standard login entry template.

Uses standard fields (title, username, password, url) without additional custom fields.

__init__()
Return type:

None

class SecureNote

Bases: EntryTemplate

Secure note entry template.

For storing text without standard credential fields. Use the notes parameter in create_entry() for content.

__init__()
Return type:

None

class Server(hostname=None, port='22', ssh_key=None)

Bases: EntryTemplate

Server/SSH entry template.

Includes hostname, port, and SSH key fields. Uses standard username/password fields for credentials. SSH key is memory-protected.

Parameters:
  • hostname (str | None)

  • port (str)

  • ssh_key (str | None)

__init__(hostname=None, port='22', ssh_key=None)
Parameters:
  • hostname (str | None)

  • port (str)

  • ssh_key (str | None)

Return type:

None

hostname: str | None = None
port: str = '22'
ssh_key: str | None = None
class SoftwareLicense(license_key=None, registered_email=None, registered_name=None, purchase_date=None, download_url=None)

Bases: EntryTemplate

Software license entry template.

Includes license key and registration information. License key is memory-protected. Does not use standard username/password fields.

Parameters:
  • license_key (str | None)

  • registered_email (str | None)

  • registered_name (str | None)

  • purchase_date (str | None)

  • download_url (str | None)

__init__(license_key=None, registered_email=None, registered_name=None, purchase_date=None, download_url=None)
Parameters:
  • license_key (str | None)

  • registered_email (str | None)

  • registered_name (str | None)

  • purchase_date (str | None)

  • download_url (str | None)

Return type:

None

download_url: str | None = None
license_key: str | None = None
purchase_date: str | None = None
registered_email: str | None = None
registered_name: str | None = None
class WirelessRouter(ssid=None, security_type='WPA2', admin_url=None, admin_username=None, admin_password=None)

Bases: EntryTemplate

Wireless router entry template.

Includes SSID, security type, and admin credentials. Admin password is memory-protected.

Parameters:
  • ssid (str | None)

  • security_type (str)

  • admin_url (str | None)

  • admin_username (str | None)

  • admin_password (str | None)

__init__(ssid=None, security_type='WPA2', admin_url=None, admin_username=None, admin_password=None)
Parameters:
  • ssid (str | None)

  • security_type (str)

  • admin_url (str | None)

  • admin_username (str | None)

  • admin_password (str | None)

Return type:

None

admin_password: str | None = None
admin_url: str | None = None
admin_username: str | None = None
security_type: str = 'WPA2'
ssid: str | None = None
class kdbxtool.KeyFileVersion(*values)[source]

Bases: StrEnum

Supported KeePass keyfile formats.

XML_V2

XML format v2.0 with hex-encoded key and SHA-256 hash verification. This is the recommended format for new keyfiles. Uses .keyx extension.

XML_V1

Legacy XML format v1.0 with base64-encoded key. Supported for compatibility. Uses .key extension.

RAW_32

Raw 32-byte binary key. Simple but no integrity verification.

HEX_64

64-character hex string (32 bytes encoded as hex).

XML_V2 = 'xml_v2'
XML_V1 = 'xml_v1'
RAW_32 = 'raw_32'
HEX_64 = 'hex_64'
kdbxtool.create_keyfile(path, version=KeyFileVersion.XML_V2)[source]

Create a new keyfile at the specified path.

Generates a cryptographically secure 32-byte random key and saves it in the specified format.

Parameters:
  • path (str | Path) – Path where the keyfile will be created.

  • version (KeyFileVersion) – Keyfile format to use. Defaults to XML_V2 (recommended).

Raises:

OSError – If the file cannot be written.

Return type:

None

Example

# Create XML v2.0 keyfile (recommended) create_keyfile(“vault.keyx”)

# Create raw binary keyfile create_keyfile(“vault.key”, version=KeyFileVersion.RAW_32)

kdbxtool.create_keyfile_bytes(version=KeyFileVersion.XML_V2)[source]

Create a new keyfile and return its contents as bytes.

Generates a cryptographically secure 32-byte random key and encodes it in the specified format.

Parameters:

version (KeyFileVersion) – Keyfile format to use. Defaults to XML_V2 (recommended).

Returns:

Keyfile contents as bytes, ready to write to a file.

Return type:

bytes

Example

keyfile_data = create_keyfile_bytes(KeyFileVersion.XML_V2) with open(“my.keyx”, “wb”) as f:

f.write(keyfile_data)

kdbxtool.parse_keyfile(keyfile_data)[source]

Parse keyfile data and extract the 32-byte key.

KeePass supports several keyfile formats: 1. XML keyfile (v1.0 or v2.0) - key is base64/hex encoded in XML 2. 32-byte raw binary - used directly 3. 64-byte hex string - decoded from hex 4. Any other size - SHA-256 hashed

Parameters:

keyfile_data (bytes) – Raw keyfile contents.

Returns:

32-byte key derived from keyfile.

Raises:

InvalidKeyFileError – If keyfile format is invalid or hash verification fails.

Return type:

bytes

class kdbxtool.YubiKeyConfig(slot=2, serial=None, timeout_seconds=15.0)[source]

Bases: object

Configuration for YubiKey challenge-response.

Parameters:
  • slot (int)

  • serial (int | None)

  • timeout_seconds (float)

slot

YubiKey slot to use (1 or 2). Slot 2 is typically used for challenge-response as slot 1 is often used for OTP.

Type:

int

serial

Optional serial number to select a specific YubiKey when multiple devices are connected. If None, uses the first device. Use list_yubikeys() to discover available devices and serials.

Type:

int | None

timeout_seconds

Timeout for challenge-response operation in seconds. If touch is required, this is the time to wait for the button press.

Type:

float

slot: int
serial: int | None
timeout_seconds: float
__init__(slot=2, serial=None, timeout_seconds=15.0)
Parameters:
  • slot (int)

  • serial (int | None)

  • timeout_seconds (float)

Return type:

None

kdbxtool.check_slot_configured(slot=2, serial=None)[source]

Check if a YubiKey slot is configured for HMAC-SHA1.

This is a convenience function to verify that a slot is properly configured before attempting to use it.

Parameters:
  • slot (int) – YubiKey slot to check (1 or 2).

  • serial (int | None) – Optional serial number to select a specific YubiKey when multiple devices are connected.

Returns:

True if the slot is configured for HMAC-SHA1, False otherwise.

Raises:
Return type:

bool

kdbxtool.list_yubikeys()[source]

List connected YubiKey devices.

Returns:

  • serial: Device serial number (if available)

  • name: Device name/model

Return type:

List of dictionaries containing device info

Raises:

YubiKeyNotAvailableError – If yubikey-manager is not installed.

exception kdbxtool.KdbxError[source]

Bases: Exception

Base exception for all kdbxtool errors.

All exceptions raised by kdbxtool inherit from this class, making it easy to catch all library-specific errors.

exception kdbxtool.FormatError[source]

Bases: KdbxError

Error in KDBX file format or structure.

Raised when the file doesn’t conform to the KDBX specification.

exception kdbxtool.InvalidSignatureError[source]

Bases: FormatError

Invalid KDBX file signature (magic bytes).

The file doesn’t start with the expected KDBX magic bytes, indicating it’s not a valid KeePass database file.

exception kdbxtool.UnsupportedVersionError(version_major, version_minor)[source]

Bases: FormatError

Unsupported KDBX version.

The file uses a KDBX version that this library doesn’t support.

Parameters:
  • version_major (int)

  • version_minor (int)

Return type:

None

__init__(version_major, version_minor)[source]
Parameters:
  • version_major (int)

  • version_minor (int)

Return type:

None

exception kdbxtool.CorruptedDataError[source]

Bases: FormatError

Database file is corrupted or truncated.

The file structure is invalid, possibly due to incomplete download, disk corruption, or other data integrity issues.

exception kdbxtool.CryptoError[source]

Bases: KdbxError

Error in cryptographic operations.

Base class for all cryptographic errors including encryption, decryption, and key derivation.

exception kdbxtool.DecryptionError(message='Decryption failed')[source]

Bases: CryptoError

Failed to decrypt database content.

This typically indicates wrong credentials (password/keyfile), but the message is kept generic to avoid confirming which credential component is incorrect.

Parameters:

message (str)

Return type:

None

__init__(message='Decryption failed')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.AuthenticationError(message='Authentication failed - wrong credentials or corrupted data')[source]

Bases: CryptoError

HMAC or integrity verification failed.

The database’s authentication code doesn’t match, indicating either wrong credentials or data tampering.

Parameters:

message (str)

Return type:

None

__init__(message='Authentication failed - wrong credentials or corrupted data')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.KdfError[source]

Bases: CryptoError

Error in key derivation function.

Problems with KDF parameters, unsupported KDF types, or KDF computation failures.

exception kdbxtool.TwofishNotAvailableError[source]

Bases: CryptoError

Twofish cipher requested but oxifish package not installed.

The database uses Twofish encryption, which requires the optional oxifish package. Install it with: pip install kdbxtool[twofish]

Return type:

None

__init__()[source]
Return type:

None

exception kdbxtool.UnknownCipherError(cipher_uuid)[source]

Bases: CryptoError

Unknown or unsupported cipher algorithm.

The database uses a cipher that this library doesn’t recognize.

Parameters:

cipher_uuid (bytes)

Return type:

None

__init__(cipher_uuid)[source]
Parameters:

cipher_uuid (bytes)

Return type:

None

exception kdbxtool.CredentialError[source]

Bases: KdbxError

Error with database credentials.

Base class for credential-related errors. Messages are kept generic to avoid information disclosure about which credential component is incorrect.

exception kdbxtool.InvalidPasswordError(message='Invalid password')[source]

Bases: CredentialError

Invalid or missing password.

Note: This is only raised when we can definitively determine the password is wrong without revealing information about other credential components.

Parameters:

message (str)

Return type:

None

__init__(message='Invalid password')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.InvalidKeyFileError(message='Invalid keyfile')[source]

Bases: CredentialError

Invalid or missing keyfile.

The keyfile is malformed, has wrong format, or failed hash verification.

Parameters:

message (str)

Return type:

None

__init__(message='Invalid keyfile')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.MergeError(message='Merge operation failed')[source]

Bases: DatabaseError

Error during database merge operation.

Raised when a merge operation fails due to incompatible databases, invalid state, or other merge-specific issues.

Parameters:

message (str)

Return type:

None

__init__(message='Merge operation failed')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.MissingCredentialsError[source]

Bases: CredentialError

No credentials provided.

At least one credential (password or keyfile) is required to open or create a database.

Return type:

None

__init__()[source]
Return type:

None

exception kdbxtool.DatabaseError[source]

Bases: KdbxError

Error in database operations.

Base class for errors that occur during database manipulation after successful decryption.

exception kdbxtool.EntryNotFoundError(message='Entry not found')[source]

Bases: DatabaseError

Entry not found in database.

The requested entry doesn’t exist or was not found in the specified location.

Parameters:

message (str)

Return type:

None

__init__(message='Entry not found')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.GroupNotFoundError(message='Group not found')[source]

Bases: DatabaseError

Group not found in database.

The requested group doesn’t exist or was not found in the database hierarchy.

Parameters:

message (str)

Return type:

None

__init__(message='Group not found')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.InvalidXmlError(message='Invalid KDBX XML structure')[source]

Bases: DatabaseError

Invalid or malformed XML payload.

The decrypted XML content doesn’t conform to the expected KDBX XML schema.

Parameters:

message (str)

Return type:

None

__init__(message='Invalid KDBX XML structure')[source]
Parameters:

message (str)

Return type:

None

exception kdbxtool.Kdbx3UpgradeRequired[source]

Bases: DatabaseError

KDBX3 database requires explicit upgrade confirmation.

When saving a KDBX3 database to its original file, explicit confirmation is required since the save will upgrade it to KDBX4. Use save(allow_upgrade=True) to confirm the upgrade.

Return type:

None

__init__()[source]
Return type:

None

exception kdbxtool.YubiKeyError[source]

Bases: CredentialError

Error communicating with YubiKey.

Base class for YubiKey-related errors. These occur during challenge-response authentication with a hardware YubiKey.

exception kdbxtool.YubiKeyNotAvailableError[source]

Bases: YubiKeyError

YubiKey support requested but yubikey-manager not installed.

The yubikey-manager package is required for YubiKey challenge-response authentication. Install it with: pip install kdbxtool[yubikey]

Return type:

None

__init__()[source]
Return type:

None

exception kdbxtool.YubiKeyNotFoundError(message=None)[source]

Bases: YubiKeyError

No YubiKey detected.

No YubiKey device was found connected to the system. Ensure the YubiKey is properly inserted.

Parameters:

message (str | None)

Return type:

None

__init__(message=None)[source]
Parameters:

message (str | None)

Return type:

None

exception kdbxtool.YubiKeySlotError(slot)[source]

Bases: YubiKeyError

YubiKey slot not configured for HMAC-SHA1.

The specified slot on the YubiKey is not configured for HMAC-SHA1 challenge-response authentication.

Parameters:

slot (int)

Return type:

None

__init__(slot)[source]
Parameters:

slot (int)

Return type:

None

exception kdbxtool.YubiKeyTimeoutError(timeout_seconds=15.0)[source]

Bases: YubiKeyError

YubiKey operation timed out.

The YubiKey operation timed out, typically because touch was required but not received within the timeout period.

Parameters:

timeout_seconds (float)

Return type:

None

__init__(timeout_seconds=15.0)[source]
Parameters:

timeout_seconds (float)

Return type:

None

Modules

database

High-level Database API for KDBX files.

exceptions

Custom exception hierarchy for kdbxtool.

merge

Database merge functionality for combining KDBX databases.

models

Data models for KDBX database elements.

parsing

KDBX binary format parsing and building.

security

Security-critical components for kdbxtool.

templates

Entry templates for common account types.