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:
objectConfiguration 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.
- 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:
- 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:
- 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:
- class kdbxtool.Argon2Config(memory_kib, iterations, parallelism, salt, variant=KdfType.ARGON2D)[source]¶
Bases:
objectConfiguration for Argon2 key derivation.
- variant¶
Argon2 variant (Argon2d or Argon2id)
- __init__(memory_kib, iterations, parallelism, salt, variant=KdfType.ARGON2D)¶
- classmethod default(salt=None, variant=KdfType.ARGON2D)[source]¶
Create configuration with secure defaults.
Alias for standard(). Provides balanced security and performance.
- Parameters:
- Returns:
Argon2Config with recommended security parameters
- Return type:
- 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:
- Returns:
Argon2Config with minimal parameters
- Return type:
- 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:
- Returns:
Argon2Config with high security parameters
- Return type:
- 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:
- Returns:
Argon2Config with standard security parameters
- Return type:
- 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:
objectAn 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.
- class kdbxtool.Database(root_group, settings=None, header=None, inner_header=None, binaries=None)[source]¶
Bases:
objectHigh-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:
root_group (Group)
settings (DatabaseSettings | None)
header (KdbxHeader | None)
inner_header (InnerHeader | None)
- __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)
- Return type:
None
- 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
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:
- 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:
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:
- 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.
- 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
- 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
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:
- 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:
- 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:
- 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
- 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:
- Returns:
MergeResult with counts and statistics about the merge
- Raises:
MergeError – If merge cannot be completed
- Return type:
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:
- 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:
- 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:
password (str | None) – Database password
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:
FileNotFoundError – If file doesn’t exist
ValueError – If credentials are wrong or file is corrupted
YubiKeyError – If YubiKey operation fails
- Return type:
- 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:
- 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:
- Returns:
Database instance
- Raises:
FileNotFoundError – If file or keyfile doesn’t exist
AuthenticationError – If max_attempts exceeded with wrong password
YubiKeyError – If YubiKey operation fails
- Return type:
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:
DatabaseError – If database wasn’t opened from a file
MissingCredentialsError – If no credentials are stored
- Return type:
None
- 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.
- 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:
DatabaseError – If no filepath specified and database wasn’t opened from file
Kdbx3UpgradeRequired – If saving KDBX3 to original file without allow_upgrade=True
YubiKeyError – If YubiKey operation fails
- Return type:
None
- set_credentials(password=None, keyfile_data=None)[source]¶
Set or update database credentials.
- Parameters:
- 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:
MissingCredentialsError – If no credentials are set
YubiKeyError – If YubiKey operation fails
- Return type:
- 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:
ValueError – If entry is not in this database
ValueError – If recycle bin is disabled
- 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:
ValueError – If group is not in this database
ValueError – If group is the root group
ValueError – If group is the recycle bin
ValueError – If recycle bin is disabled
- 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.
- 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:
objectSettings 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)
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])
- recycle_bin_uuid¶
UUID of recycle bin group
- Type:
uuid_module.UUID | None
- 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)
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
- 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:
objectA 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 (uuid_module.UUID)
times (Times)
icon_id (str)
custom_icon_uuid (uuid_module.UUID | None)
strings (dict[str, StringField])
autotype (AutoType)
history (list[HistoryEntry])
foreground_color (str | None)
background_color (str | None)
override_url (str | None)
quality_check (bool)
_parent (Group | None)
_database (Database | None)
- uuid¶
Unique identifier for the entry
- Type:
uuid_module.UUID
- custom_icon_uuid¶
UUID of custom icon (overrides icon_id if set)
- Type:
uuid_module.UUID | None
- strings¶
Dictionary of string fields (key -> StringField)
- Type:
- history¶
List of previous versions of this entry
- Type:
- __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:
uuid (uuid_module.UUID)
times (Times)
icon_id (str)
custom_icon_uuid (uuid_module.UUID | None)
strings (dict[str, StringField])
autotype (AutoType)
history (list[HistoryEntry])
foreground_color (str | None)
background_color (str | None)
override_url (str | None)
quality_check (bool)
_parent (Group | None)
_database (Database | None)
- Return type:
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:
- Returns:
New Entry instance
- Return type:
- 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
- delete_custom_property(key)[source]¶
Delete a custom property.
- Parameters:
key (str) – Property name to delete
- Raises:
ValueError – If key is a reserved key
KeyError – If property doesn’t exist
- 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:
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:
- 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
- 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
- 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:
ValueError – If entry has no parent group.
IndexError – If new_index is out of range.
- Return type:
None
- set_custom_property(key, value, protected=False)[source]¶
Set a custom property.
- Parameters:
- Raises:
ValueError – If key is a reserved key
- Return type:
None
- 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
- uuid: uuid_module.UUID¶
- strings: dict[str, StringField]¶
- 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:
objectA 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)
_parent (Group | None)
_is_root (bool)
_database (Database | None)
- uuid¶
Unique identifier for the group
- Type:
uuid_module.UUID
- custom_icon_uuid¶
UUID of custom icon (overrides icon_id if set)
- Type:
uuid_module.UUID | None
- last_top_visible_entry¶
UUID of last visible entry (UI state)
- Type:
uuid_module.UUID | None
- __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)
_parent (Group | None)
_is_root (bool)
_database (Database | None)
- Return type:
None
- 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:
- Returns:
Newly created entry
- Return type:
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", ... ), ... )
- 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
- 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:
- 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:
- 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:
- 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).
- 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
- 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¶
- 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:
EntryA 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:
uuid (uuid_module.UUID)
times (Times)
icon_id (str)
custom_icon_uuid (uuid_module.UUID | None)
strings (dict[str, StringField])
autotype (AutoType)
history (list[HistoryEntry])
foreground_color (str | None)
background_color (str | None)
override_url (str | None)
quality_check (bool)
_parent (Group | None)
_database (Database | None)
- __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:
uuid (uuid_module.UUID)
times (Times)
icon_id (str)
custom_icon_uuid (uuid_module.UUID | None)
strings (dict[str, StringField])
autotype (AutoType)
history (list[HistoryEntry])
foreground_color (str | None)
background_color (str | None)
override_url (str | None)
quality_check (bool)
_parent (Group | None)
_database (Database | None)
- Return type:
None
- 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:
objectTimestamps associated with entries and groups.
All times are stored as timezone-aware UTC datetimes.
- Parameters:
- creation_time¶
When the element was created
- Type:
- last_modification_time¶
When the element was last modified
- Type:
- last_access_time¶
When the element was last accessed
- Type:
- expiry_time¶
When the element expires (if expires is True)
- Type:
datetime.datetime | None
- 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)¶
- classmethod create_new(expires=False, expiry_time=None)[source]¶
Create timestamps for a new element.
- property expired: bool¶
Check if the element has expired.
- Returns:
True if expires is True and expiry_time is in the past
- touch(modify=False)[source]¶
Update access time, and optionally modification time.
- Parameters:
modify (bool) – If True, also update modification time
- Return type:
None
- class kdbxtool.Cipher(*values)[source]¶
Bases:
EnumSupported 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.
- 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:
- 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:
EnumSupported Key Derivation Functions in KDBX.
The UUID values are defined in the KDBX specification.
- 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:
- 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:
EnumMerge 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:
objectResult of a database merge operation.
Contains detailed statistics about what was changed during the merge.
- Parameters:
- __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)¶
- class kdbxtool.DeletedObject(uuid, deletion_time)[source]¶
Bases:
objectRecord of a deleted entry or group.
Used in SYNCHRONIZE mode to track deletions that should propagate to other databases during merge.
- deletion_time¶
When the deletion occurred
- Type:
- class kdbxtool.EntryTemplate[source]¶
Bases:
objectBase 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:
IntEnumKeePass 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¶
- EMAIL_SEARCH = 40¶
- 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:
objectNamespace 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:
EntryTemplateBank 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:
- __init__(bank_name=None, account_type=None, account_number=None, routing_number=None, swift_bic=None, iban=None, pin=None)¶
- class CreditCard(card_number=None, expiry_date=None, cvv=None, cardholder_name=None, pin=None)¶
Bases:
EntryTemplateCredit 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:
- __init__(card_number=None, expiry_date=None, cvv=None, cardholder_name=None, pin=None)¶
- Database¶
alias of
DatabaseConnection
- class Email(email_address=None, imap_server=None, imap_port='993', smtp_server=None, smtp_port='587')¶
Bases:
EntryTemplateEmail account entry template.
Includes email address and server settings. Uses standard username/password fields for credentials.
- Parameters:
- __init__(email_address=None, imap_server=None, imap_port='993', smtp_server=None, smtp_port='587')¶
- class Identity(first_name=None, last_name=None, email=None, phone=None, address=None, city=None, state=None, postal_code=None, country=None)¶
Bases:
EntryTemplateIdentity/personal information entry template.
Includes name, contact, and address fields. Does not use standard username/password fields.
- Parameters:
- __init__(first_name=None, last_name=None, email=None, phone=None, address=None, city=None, state=None, postal_code=None, country=None)¶
- class Login¶
Bases:
EntryTemplateStandard login entry template.
Uses standard fields (title, username, password, url) without additional custom fields.
- __init__()¶
- Return type:
None
- class SecureNote¶
Bases:
EntryTemplateSecure 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:
EntryTemplateServer/SSH entry template.
Includes hostname, port, and SSH key fields. Uses standard username/password fields for credentials. SSH key is memory-protected.
- __init__(hostname=None, port='22', ssh_key=None)¶
- class SoftwareLicense(license_key=None, registered_email=None, registered_name=None, purchase_date=None, download_url=None)¶
Bases:
EntryTemplateSoftware license entry template.
Includes license key and registration information. License key is memory-protected. Does not use standard username/password fields.
- Parameters:
- __init__(license_key=None, registered_email=None, registered_name=None, purchase_date=None, download_url=None)¶
- class WirelessRouter(ssid=None, security_type='WPA2', admin_url=None, admin_username=None, admin_password=None)¶
Bases:
EntryTemplateWireless router entry template.
Includes SSID, security type, and admin credentials. Admin password is memory-protected.
- Parameters:
- __init__(ssid=None, security_type='WPA2', admin_url=None, admin_username=None, admin_password=None)¶
- class kdbxtool.KeyFileVersion(*values)[source]¶
Bases:
StrEnumSupported 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:
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:
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:
- class kdbxtool.YubiKeyConfig(slot=2, serial=None, timeout_seconds=15.0)[source]¶
Bases:
objectConfiguration for YubiKey challenge-response.
- 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:
- 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:
- 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:
- Returns:
True if the slot is configured for HMAC-SHA1, False otherwise.
- Raises:
YubiKeyNotAvailableError – If yubikey-manager is not installed.
YubiKeyNotFoundError – If no YubiKey is connected (or specified serial not found).
- Return type:
- 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:
ExceptionBase 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:
KdbxErrorError in KDBX file format or structure.
Raised when the file doesn’t conform to the KDBX specification.
- exception kdbxtool.InvalidSignatureError[source]¶
Bases:
FormatErrorInvalid 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:
FormatErrorUnsupported KDBX version.
The file uses a KDBX version that this library doesn’t support.
- exception kdbxtool.CorruptedDataError[source]¶
Bases:
FormatErrorDatabase 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:
KdbxErrorError in cryptographic operations.
Base class for all cryptographic errors including encryption, decryption, and key derivation.
- exception kdbxtool.DecryptionError(message='Decryption failed')[source]¶
Bases:
CryptoErrorFailed 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
- exception kdbxtool.AuthenticationError(message='Authentication failed - wrong credentials or corrupted data')[source]¶
Bases:
CryptoErrorHMAC 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
- exception kdbxtool.KdfError[source]¶
Bases:
CryptoErrorError in key derivation function.
Problems with KDF parameters, unsupported KDF types, or KDF computation failures.
- exception kdbxtool.TwofishNotAvailableError[source]¶
Bases:
CryptoErrorTwofish 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
- exception kdbxtool.UnknownCipherError(cipher_uuid)[source]¶
Bases:
CryptoErrorUnknown or unsupported cipher algorithm.
The database uses a cipher that this library doesn’t recognize.
- Parameters:
cipher_uuid (bytes)
- Return type:
None
- exception kdbxtool.CredentialError[source]¶
Bases:
KdbxErrorError 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:
CredentialErrorInvalid 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
- exception kdbxtool.InvalidKeyFileError(message='Invalid keyfile')[source]¶
Bases:
CredentialErrorInvalid or missing keyfile.
The keyfile is malformed, has wrong format, or failed hash verification.
- Parameters:
message (str)
- Return type:
None
- exception kdbxtool.MergeError(message='Merge operation failed')[source]¶
Bases:
DatabaseErrorError 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
- exception kdbxtool.MissingCredentialsError[source]¶
Bases:
CredentialErrorNo credentials provided.
At least one credential (password or keyfile) is required to open or create a database.
- Return type:
None
- exception kdbxtool.DatabaseError[source]¶
Bases:
KdbxErrorError in database operations.
Base class for errors that occur during database manipulation after successful decryption.
- exception kdbxtool.EntryNotFoundError(message='Entry not found')[source]¶
Bases:
DatabaseErrorEntry not found in database.
The requested entry doesn’t exist or was not found in the specified location.
- Parameters:
message (str)
- Return type:
None
- exception kdbxtool.GroupNotFoundError(message='Group not found')[source]¶
Bases:
DatabaseErrorGroup not found in database.
The requested group doesn’t exist or was not found in the database hierarchy.
- Parameters:
message (str)
- Return type:
None
- exception kdbxtool.InvalidXmlError(message='Invalid KDBX XML structure')[source]¶
Bases:
DatabaseErrorInvalid or malformed XML payload.
The decrypted XML content doesn’t conform to the expected KDBX XML schema.
- Parameters:
message (str)
- Return type:
None
- exception kdbxtool.Kdbx3UpgradeRequired[source]¶
Bases:
DatabaseErrorKDBX3 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
- exception kdbxtool.YubiKeyError[source]¶
Bases:
CredentialErrorError communicating with YubiKey.
Base class for YubiKey-related errors. These occur during challenge-response authentication with a hardware YubiKey.
- exception kdbxtool.YubiKeyNotAvailableError[source]¶
Bases:
YubiKeyErrorYubiKey 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
- exception kdbxtool.YubiKeyNotFoundError(message=None)[source]¶
Bases:
YubiKeyErrorNo YubiKey detected.
No YubiKey device was found connected to the system. Ensure the YubiKey is properly inserted.
- Parameters:
message (str | None)
- Return type:
None
- exception kdbxtool.YubiKeySlotError(slot)[source]¶
Bases:
YubiKeyErrorYubiKey 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
- exception kdbxtool.YubiKeyTimeoutError(timeout_seconds=15.0)[source]¶
Bases:
YubiKeyErrorYubiKey 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
Modules
High-level Database API for KDBX files. |
|
Custom exception hierarchy for kdbxtool. |
|
Database merge functionality for combining KDBX databases. |
|
Data models for KDBX database elements. |
|
KDBX binary format parsing and building. |
|
Security-critical components for kdbxtool. |
|
Entry templates for common account types. |