libkeepass 0.2.0
KeePass key database importer/exporter library
Loading...
Searching...
No Matches
Worked examples

The snippets below use the public API from libkeepass/keepass.hh, database.hh, group.hh, entry.hh and key.hh. They assume C++17.

Round-trip through memory streams

#include <sstream>
using namespace keepass;
KeePass reader("correct horse battery staple");
std::unique_ptr<Database> db = reader.Open("vault.kdbx");
std::ostringstream encrypted;
reader.Save(encrypted, *db); // KDBX 3 or 4 chosen from KDF/cipher
std::istringstream input(encrypted.str());
KeePass reopened("correct horse battery staple");
std::unique_ptr<Database> copy = reopened.Open(input);
High-level entry point for opening and saving KeePass databases.
Definition keepass.hh:50
High-level unified KeePass database import/export API.

Non-seekable streams are buffered internally; seekable streams are parsed directly after an 8-byte signature sniff.

Create a database and change its password

auto db = KeePass::Create("initial password", KeePass::Format::kKdbx4);
Database::AddGroup(db->root(), Database::NewGroup("Internet"));
// The transformed key is cached on db, so a keyless save works.
KeePass keyless;
keyless.SetFormat(KeePass::Format::kKdbx4);
keyless.Save("new.kdbx", *db);
// Re-encrypt an existing database with a new key. SaveAs overrides any
// transformed key cached on the database.
KeePass rekey;
rekey.SaveAs("new.kdbx", *db, "new password");
void Save(const std::string &path, const Database &db)
Saves a database to a file.
void SetFormat(Format format)
Selects the output format.
Definition keepass.hh:192
void SaveAs(const std::string &path, const Database &db, const Key &new_key)
Saves a database to a file using a new key.

The CLI equivalents are kpx create and kpx passwd.

Attachments

Entry::Attachment attachment;
attachment.set_name("notes.txt");
attachment.set_binary(std::make_shared<Binary>(
protect<secure_string>(secure_string("payload"), false)));
auto entry = Database::NewEntry("Document");
entry->AddAttachment(std::make_shared<Entry::Attachment>(attachment));
Database::AddEntry(db->root(), entry);
A file attachment of an entry.
Definition entry.hh:62
void set_binary(std::shared_ptr< Binary > binary)
Sets the attachment binary payload.
Definition entry.hh:78
void set_name(const std::string &name)
Sets the attachment name.
Definition entry.hh:72
Wrapper that marks a value as sensitive and tracks the protection flag of a KeePass field.
Definition security.hh:41
String that is stored in wiped and best-effort locked memory.
Definition secure.hh:262

The convenience helpers use raw byte vectors and are easier for binary data:

entry->set_binary_property("report.pdf", file_bytes);
std::vector<uint8_t> restored = entry->get_binary_property("report.pdf");
entry->delete_binary_property("report.pdf");

Attachments are preserved through KDBX 3/4 import and export; KDB (1.x) has no attachment support.

Tags and custom fields

auto group = Database::NewGroup("Work");
group->set_tags("work internal"); // space-separated in the API
Database::AddGroup(db->root(), group);
auto entry = Database::NewEntry("Mail");
entry->set_tags("mail 2fa");
entry->set_custom_property("otp", "otpauth://totp/...");
std::string seed = entry->GetString("otp");

On the wire, KeePass 2.48+ stores tags semicolon-separated; the conversion is done at the XML boundary.

Recycle bin and history

db->EnableRecycleBin(true);
db->TrashEntry(entry); // move to the recycle bin (delete if disabled)
db->EmptyRecycleBin();
entry->save_history(); // snapshot the current field values
entry->set_notes(protect<secure_string>(secure_string("changed"), false));
entry->delete_old_history(10); // keep only the 10 newest versions
entry->delete_history(); // clear all previous versions

Entry history is preserved by import/export but hidden from the kpx print and audit output; use Entry::history() when you need it. Database::DeleteOldHistory() applies the HistoryMaxItems/HistoryMaxSize metadata limits to every entry, and kpx purge --keep <n> exposes the same policy on the command line.

TOTP custom fields

Entry::totp() parses the KeePass field variants (otp, TOTP Seed, TOTP Settings, including complete otpauth://totp/... URIs), and Totp::Generate() produces the current code:

if (auto config = entry->totp()) {
std::string code = Totp::Generate(*config);
uint32_t remaining = Totp::SecondsRemaining(*config);
std::cout << code << " (" << remaining << "s)\n";
}

kpx otp --code uses the same helpers.

Incremental backups

Database::DeltaSince() matches entries by UUID and compares their canonical JSON representation, so a backup tool can export only changed records:

DatabaseDelta delta = current->DeltaSince(*previous);
if (!delta.empty()) {
std::ofstream out("delta.json");
out << delta.ToJson();
}
Entry-level difference between two databases, for incremental backups.
Definition database.hh:51
std::string ToJson() const
Serializes the delta to JSON (entry payloads use Entry::ToJson()).
bool empty() const
Returns whether no change was detected.
Definition database.hh:59

added/modified carry the current entry object plus its group path; deleted entries are reported by UUID and path.

CSV layouts

Database::ToCsv() supports four schemas: kCsv (no passwords), kCsvWithPasswords, kCsvWithCustomFields (appends CustomFields) and kCsvKeePass2 (Account,Login Name,Password,Web Site,Comments).

Lazy attachments

KDBX 4 attachments are imported as views into one shared secure buffer. Binary::data() materializes a single payload on first access, while Binary::WriteTo() streams it without copying during export:

if (auto binary = entry->FindAttachment("large.bin")) {
std::ofstream out("large.bin", std::ios::binary);
binary->WriteTo(out);
}

Streams and resource limits

KdbxFile exposes the import budgets from libkeepass/detail/limits.hh. Tighten them for untrusted uploads:

limits.max_total_bytes = 64ULL * 1024 * 1024;
limits.max_binary_bytes = 16ULL * 1024 * 1024;
limits.max_xml_depth = 32;
KdbxFile file;
file.set_resource_limits(limits);
auto db = file.Import(stream, Key("password"));
Keepass2 database file representation.
Definition kdbx.hh:45
std::unique_ptr< Database > Import(const std::string &path, const Key &key)
Imports a KDBX database from a file path.
void set_resource_limits(const detail::ResourceLimits &limits)
Manages database encryption keys for KDB and KDBX formats.
Definition key.hh:45
Configurable resource budgets for database import and XML parsing.
Definition limits.hh:45
uint64_t max_total_bytes
Definition limits.hh:47
uint64_t max_binary_bytes
Definition limits.hh:71
uint32_t max_xml_depth
Definition limits.hh:56

Violations, including gzip bombs and oversized key files, surface as FormatError.

Error handling

try {
KeePass kp(password);
auto db = kp.Open(path);
} catch (const PasswordError&) {
// wrong password / composite key
} catch (const FormatError& error) {
// corrupt or unsupported database: error.what() has context
} catch (const IoError&) {
// file not found, truncated stream, write failure
}
Thrown when a database or stream has an invalid format.
Definition exception.hh:79
Thrown for input/output errors while reading or writing databases.
Definition exception.hh:147
Thrown when an invalid password is supplied while opening a database.
Definition exception.hh:64

what() never contains password or key material.