← KeePass databases
KeePass·Format guide
All tools

KeePass databases (KDBX)

KeePass 2, KeePassXC, KeeWeb, Strongbox, KeePassDX, KeePassium and others store passwords in one encrypted file, .kdbx: an unencrypted header that says how to derive the key, then the encrypted (and usually gzip-compressed) XML of groups and entries. This page describes the format as the KeePass tool reads it, and its libraries.

Contents

  1. The file
  2. The outer header
  3. Credentials and keys
  4. Key derivation: AES-KDF and Argon2
  5. The encrypted data
  6. Inner header and protected values
  7. The XML
  8. What to look for
  9. What the tool shows, its limits, privacy
  10. Editing
  11. Saving: what is written
  12. The libraries

1The file

Part KDBX 3.x (and 2.x) KDBX 4.0 / 4.1
Signatures 03 D9 A2 9A then 67 FB 4B B5 (KeePass 1.x .kdb: 65 FB 4B B5; the 2.x pre-release: 66 FB 4B B5)
Version 32 bits: minor (low 16), major (high 16): 0x00030001 is 3.1, 0x00040001 is 4.1
Header fields type (1 byte), length (2), data type (1 byte), length (4), data
After the header the encrypted data SHA-256 of the header, HMAC-SHA-256 of the header, then HMAC blocks
Decrypted 32 stream start bytes, hashed blocks of (gzip) XML (gzip of) the inner header and the XML

3Credentials and keys

The composite key is SHA-256 of the concatenated parts that are used: SHA-256 of the password's UTF-8 bytes (an empty password is a part; "no password" isn't), the key file's 32-byte key, SHA-256 of a challenge-response. A key file is read the way KeePass reads it:

The transformed key is the KDF of the composite key. The encryption key is SHA-256(master seed ‖ transformed key). KDBX 4's HMAC key base is SHA-512(master seed ‖ transformed key ‖ 01); block i's HMAC key is SHA-512(i as 64-bit little-endian ‖ base), and the header's uses i = 264 − 1. A YubiKey's HMAC-SHA1 response to the KDF seed (KDBX 4) is part of the composite key; in KDBX 3 (the master seed as challenge) its hash sits between the master seed and the transformed key.

4Key derivation: AES-KDF and Argon2

AES-KDF encrypts the two 16-byte halves of the composite key rounds times with AES-256 in ECB mode, keyed by the seed, then hashes the 32 bytes with SHA-256. Its cost is time only: no memory. Argon2 (RFC 9106) fills M bytes of 1 KiB blocks in P lanes, I times; each block mixes the previous one with a reference block through a BLAKE2b-based compression. Argon2d chooses references from the data (fast, GPU-resistant), Argon2id does so only after the first half pass. Version 0x13 XORs new blocks into old ones on later passes, 0x10 overwrote them. The output is 32 bytes.

The tool estimates the time from a short measurement in its worker. In JavaScript, here, Argon2 runs about 160–200 MiB per second per pass on one core (64 MiB × 2 iterations: about 0.7 s in jsc and 0.8 s in Chromium on the machine it was built on), and AES-KDF about 12 million rounds per second; lanes are computed one after the other, so a parallelism of 4 doesn't make it faster here as it does in KeePass.

5The encrypted data

KDBX 3: everything after the header is encrypted (CBC with PKCS#7 padding, or ChaCha20). The plaintext starts with the 32 StreamStartBytes of the header: if they don't match, the key is wrong. Then hashed blocks: index (4 bytes), SHA-256 of the data (32), length (4), data; a block of length 0 with a zero hash ends it. Since KeePass 2.20 (KDBX 3.1) the XML's Meta/HeaderHash holds SHA-256 of the header, which is how a changed header is detected.

KDBX 4: the header's SHA-256 detects damage, its HMAC a wrong key (or a changed header). Then blocks of HMAC (32), length (4), data, each HMAC over (block index ‖ length ‖ data); the data of all blocks, joined, is the ciphertext. A changed byte anywhere fails an HMAC before anything is decrypted.

6Inner header and protected values

KDBX 4's decrypted (and decompressed) data starts with the inner header: type (1 byte), length (4), data: 1 the inner random stream (3 ChaCha20), 2 its key, 3 an attachment (a flags byte, bit 0 "protected", then the bytes), 0 the end. The XML follows.

Protected values — every element with Protected="True", usually passwords and fields marked "protect" — are base64 of the value XORed with the inner random stream, taken in the order the values appear in the document. KDBX 3: Salsa20 with key SHA-256(ProtectedStreamKey) and nonce E8 30 09 4B 97 20 5D 2A. KDBX 4: ChaCha20 with key and nonce the first 32 and next 12 bytes of SHA-512(the inner key). (ID 1, an RC4 variant, was KeePass's very first.) The layer keeps values encrypted in memory; it adds nothing against someone who has the decrypted XML and the key.

7The XML

<KeePassFile> holds <Meta> and <Root>. Meta: Generator, HeaderHash (3.1), database name, description, default user name and their change times, MaintenanceHistoryDays, Color, MasterKeyChanged, MasterKeyChangeRec / Force (days, −1 off), MemoryProtection (ProtectTitle, ProtectUserName, ProtectPassword, ProtectURL, ProtectNotes), CustomIcons (UUID, PNG data; KDBX 4.1 Name and LastModificationTime), RecycleBinEnabled / UUID, EntryTemplatesGroup, HistoryMaxItems / MaxSize, LastSelectedGroup, Binaries (KDBX 3's attachment pool: base64, optionally gzip, optionally protected), CustomData (KDBX 4.1 adds a time per item).

Root: one <Group> (UUID, Name, Notes, IconID, CustomIconUUID, Times, IsExpanded, DefaultAutoTypeSequence, EnableAutoType, EnableSearching, LastTopVisibleEntry, 4.1: Tags, PreviousParentGroup; then entries and subgroups) and <DeletedObjects> (UUID and DeletionTime). An <Entry>: UUID, IconID, colours, OverrideURL, 4.1 QualityCheck and PreviousParentGroup, Tags, Times (Creation, LastModification, LastAccess, Expiry, Expires, UsageCount, LocationChanged), <String>s (Key and Value: Title, UserName, Password, URL, Notes and custom fields), <Binary>s (Key and <Value Ref="n"/> into the pool), AutoType (Enabled, DataTransferObfuscation, DefaultSequence, Associations of Window and KeystrokeSequence), CustomData, and <History>: earlier versions of the entry. Times are ISO 8601 in KDBX 3 and base64 of a 64-bit count of seconds since 0001-01-01 in KDBX 4.

8What to look for

9What the tool shows, its limits, privacy

10Editing

Once unlocked, the database can be changed in the tab; nothing touches a file until Save. Every change goes to the worker's KdbxEditor, which changes the XML tree itself (unknown elements, custom data, custom icons, auto-type associations and everything else stay as they were) and reads the model again. The top bar shows ● Unsaved changes; Undo (or ⌘/Ctrl-Z outside a text field) goes back one change at a time, up to 50; closing the tab, locking or opening another file with unsaved changes asks first.

What KeePass does, and so does the tool

Change Effect
Edit an entry A copy of the entry without its history goes into <History> (only when something changed); LastModificationTime and LastAccessTime become now, UsageCount goes up by one. Then the oldest versions are removed while there are more than Meta/HistoryMaxItems, and while their size passes Meta/HistoryMaxSize (KeePass's estimate: 128 bytes plus the length of every field, attachment, tag, auto-type sequence and custom data). Missing settings mean KeePass's defaults, 10 versions and 6 MiB; −1 means no limit. Lowering the limits trims every entry at once.
Restore a version The current version first goes into the history; the entry takes the version's content (UUID, history and LocationChanged kept), then is touched as an edit.
Delete With the recycle bin on (KeePass's default): the entry or group moves into it; the bin is created when Meta names none (a group "Recycle Bin" under the root, icon 43, auto-type and searching off; Meta/RecycleBinUUID and RecycleBinChanged set). Inside the bin, with the bin off, or Empty the recycle bin: removed for good, and a <DeletedObject> (UUID, DeletionTime) is added for the object and everything in it, so that synchronising removes the other copies.
Move Times/LocationChanged becomes now; in KDBX 4.1 PreviousParentGroup records the group it came from.
New objects 16 random bytes as UUID; all times now. New entries: the standard fields protected as Meta/MemoryProtection says (the password by default), Meta/DefaultUserName as user name, auto-type on. New groups: icon 48, expanded, auto-type and searching inherited.
Attachments Kept in one pool: identical content (and protection) is stored once and referenced (<Value Ref="n"/>), history versions included. The pool written holds only what entries and history refer to.
Database settings DatabaseNameChanged, DatabaseDescriptionChanged, DefaultUserNameChanged, RecycleBinChanged and SettingsChanged set. Changing memory protection re-protects those fields in every entry and history version (KeePass applies it when writing).
Master key Used from the next save; Meta/MasterKeyChanged becomes now (MasterKeyChangeForceOnce off when present).

Versions

A file keeps the version it was opened with (2.x and 3.0 files are written as 3.1, as KeePass does). Argon2 and the ChaCha20 cipher need KDBX 4; custom data on groups and entries is KDBX 4's; group tags, entries excluded from the quality check, previous parent groups, custom icon names and times and custom data times are KDBX 4.1's. When a setting or the content needs a newer version, the tool says so and upgrades only if you agree: with KDBX 3.1 Argon2 can't be saved; 4.1 elements in a 4.0 file are kept (older readers skip them). A KDBX 3.1 file that already used ChaCha20 (kdbxweb writes those) is saved as it was. KDBX 4.1 is read by KeePass 2.48+, KeePassXC 2.7+, KeeWeb, Strongbox, KeePassDX and KeePassium; 3.1 by every KeePass 2.x reader.

11Saving: what is written

12The libraries

All are ES modules without DOM, so they run in pages, workers and jsc (tests/kdbx-test.js).

Call Gives
KdbxFile.parse(bytes) lib/keepass/kdbx.js. The unencrypted part: header, kdfCost ({ type, rounds } or { type, memoryKiB, iterations, parallelism, blocks }), layout [{ offset, length, label, kind }], supported, problems. Throws KdbxError notKeePass, keePass1 (details: the 1.x header), unsupportedVersion, damaged.
file.decrypt(credentials, { onProgress }) A KdbxDatabase: innerHeader, randomStream, xml (an XmlTree), model, protectedValues (Map element → bytes), checks, payload, problems, xmlText({ protectedValues: "stored" | "masked" | "revealed" }). onProgress(stage, done, total), stage kdf, decrypt, xml. Throws wrongCredentials, keyFile, damaged, unsupported.
new KdbxCredentials({ password, keyFile, challengeResponse }) lib/keepass/kdbx-credentials.js. keyFileInfo, compositeKey(challenge); KdbxCredentials.readKeyFile(bytes) → { key, type: xml-v1 | xml-v2 | binary | hex | hashed, version, hashChecked }.
KdbxHeader.parse(bytes) lib/keepass/kdbx-header.js. major, minor, version, fields [{ id, name, offset, length, dataOffset, data }], length, bytes, cipher, compression, masterSeed, encryptionIv, kdf { uuid, name, type, rounds, seed, salt, memory, iterations, parallelism, argonVersion, secret, associatedData, parameters }, KDBX 3's transformSeed, transformRounds, protectedStreamKey, streamStartBytes, innerRandomStream, KDBX 4's publicCustomData. KdbxHeader.identify(bytes), readKeePass1(bytes); VariantDictionary.parse(bytes) → { version, items [{ key, type, typeName, value, bytes }] }.
KdbxModel.read(tree, { protectedValues, binaries }) lib/keepass/kdbx-model.js. meta (KdbxMeta), root, groups, entries (KdbxGroup, KdbxEntry: every field of section 7, with element and the unknown element names), deletedObjects, binaries, problems; groupByUuid, entryByUuid; KdbxModel.parseTime(text), uuidText(base64).
KeyDerivation, OuterCipher, BlockStream, InnerRandomStream lib/keepass/kdbx-crypto.js. derive(kdf, compositeKey, onProgress), cost(kdf); decrypt(cipher, key, iv, data, { padding }); readHmacBlocks, readHashedBlocks, blockHmacKey; new InnerRandomStream(id, key).process(bytes).
KdbxReview.header(file), KdbxReview.database(database, { now, credentials }) lib/keepass/kdbx-review.js. Findings [{ id, level: high | medium | info, title, detail, items [{ entry, label }] }], never with secret values; THRESHOLDS; passwordChanged(entry).
XmlTree.parse(text), XmlTree.serialize(tree, { declaration, text }) lib/xml-tree.js: XML without DOMParser (works in workers): declaration, children, root; XmlElement name, attributes, children, parent, attribute(), child(), childElements(), text.
KdbxEditor.fromDatabase(database, { random, now }) lib/keepass/kdbx-editor.js. model, settings, dirty, canUndo, undoLabel, undo(), markSaved(), document() (for the writer), xmlText(mode), requirements() → { major, minor, version, reasons [{ version, reason }] }. Entries: createEntry(groupUuid, changes) → uuid, updateEntry(uuid, changes) → changed (changes: strings [{ key, value, protected }] or fields / removeFields / protect, tags, iconId, customIconUuid, foregroundColor, backgroundColor, overrideUrl, qualityCheck, expires, expiry, autoType { enabled, obfuscation, defaultSequence }, attachments [{ name, data, protected } | { name, from }]), deleteEntry(uuid) → "recycled" | "deleted", moveEntry(uuid, groupUuid), restoreHistory(uuid, index), deleteHistory(uuid, [index]). Groups: createGroup(parentUuid, { name, notes, iconId }), updateGroup(uuid, { name, notes, iconId, customIconUuid, tags, enableAutoType, enableSearching, defaultAutoTypeSequence, expires, expiry }), deleteGroup(uuid), moveGroup(uuid, parentUuid), emptyRecycleBin(). Database: updateMeta({ databaseName, databaseDescription, defaultUserName, color, recycleBinEnabled, historyMaxItems, historyMaxSize, maintenanceHistoryDays, masterKeyChangeRec, masterKeyChangeForce, memoryProtection }), recordMasterKeyChange(), setSettings({ major, minor, cipher, compression, kdf }). KdbxEditor.describe(model): every value as one canonical text, for comparisons. UUIDs are the base64 text the model uses.
KdbxWriter.write(document, credentials, { random, onProgress }) lib/keepass/kdbx-writer.js. → { bytes, header, xmlLength, compressedLength, binaries, settings }. settings: { major, minor, cipher: aes | chacha20 | twofish, compression, kdf: { type: "aes", rounds } or { type: "argon2d" | "argon2id", memoryKiB, iterations, parallelism, version }, kdfUuid, publicCustomData }. KdbxWriter.settingsOf(header), check(settings) → problems, headerBytes(settings, random). onProgress stages kdf, compress, encrypt. random(count) defaults to crypto.getRandomValues; tests pass a seeded one.
KdbxCredentials.createKeyFile(random) A new XML key file v2 (.keyx): { bytes, key, hash } — 32 random bytes as hex in two lines of four groups, with Hash = the first 4 bytes of their SHA-256.
PasswordGenerator.generate(options, random) lib/keepass/password-generator.js. options { length, upper, lower, digits, minus, underline, space, special, brackets, latin1, excludeLookAlike, everyGroup, custom }; entropy(options) → bits; strength(password) → { bits, label }.
Deflate.compress(bytes, { level }), Deflate.gzip, Deflate.zlib lib/compression/deflate.js: DEFLATE (RFC 1951) and its gzip and zlib wrappers; checked against Python's zlib by tests/check-deflate.py.
OuterCipher.encrypt, BlockStream.writeHmacBlocks / writeHashedBlocks, VariantDictionary.serialize, KdbxModel.formatTime The writing halves of kdbx-crypto.js, kdbx-header.js, kdbx-model.js. lib/xml-tree.js gained setText, setAttribute, append, insertBefore, remove, ensureChild, XmlElement.build, XmlTree.indent and XmlTree.clone.
Argon2.hash(options, onProgress) lib/crypto/argon2.js: { password, salt, memory (KiB), iterations, parallelism, length, type d | i | id, version 0x10 | 0x13, secret, associatedData }.
Blake2b.digest(bytes, length, key) lib/crypto/blake2b.js; also new Blake2b(length, key).update(bytes).finish().
new ChaCha20(key, nonce, counter).process(bytes) lib/crypto/chacha20.js (RFC 8439); ChaCha20.block(key, counter, nonce).
new Salsa20(key, nonce).process(bytes) lib/crypto/salsa20.js.
new Twofish(key) lib/crypto/twofish.js: encryptBlock, encryptBlockInto, decryptBlock, decryptBlockInto, blockSize.
aes.encryptRepeated(block, count), aes.encryptBlockInto / decryptBlockInto Table-driven additions to lib/crypto/aes.js (same results as encryptBlock / decryptBlock).
const file = KdbxFile.parse(bytes);
console.log(file.header.version, file.header.cipher.name, file.kdfCost);
const database = file.decrypt(new KdbxCredentials({ password: "secret", keyFile: keyBytes }),
	{ onProgress: (stage, done, total) => console.log(stage, done, total) });
for (const entry of database.model.entries) {
	console.log(entry.group.path.join("/"), entry.title, entry.userName);
}

/* editing and saving */
const editor = KdbxEditor.fromDatabase(database);
const uuid = editor.createEntry(editor.model.root.uuid, { fields: { Title: "Router", UserName: "admin", Password: "…" } });
editor.updateEntry(uuid, { fields: { Password: "new" } });          /* the old version goes to the history */
editor.setSettings({ major: 4, minor: 1, kdf: { type: "argon2id", memoryKiB: 65536, iterations: 3, parallelism: 2 } });
const { bytes } = KdbxWriter.write(editor.document(), credentials);