Keychain File Format

The `.keychain` format is a self-contained and self-described database.

The format was implemented for an operating system with limited memory and using approaches less commonly used today.

The keychain file format has been published by Apple, see libsecurity_filedb. These files describe the layout of the database but not the meaning of the contents.

Keychain is a Database

The keychain file is a database. The database contains tables. The tables contain items.

Keysafe works through the tables and exports what it finds. The tool’s emphasis is on reading and exporting all that can be exported.

Below are a few notes about the format.

Unexpected Order

The order of Keysafe’s exported items can appear random. This is a function of the file’s format.

When new items are added, the items are written either to the end of a table – or in the first free location within the table.

When items are removed, the table’s item is cleared but left empty for a new item to fill.

So, if three items are added to an empty table, the table look likes:

If item 2 is deleted, the table becomes:

The next item to be added may either be added to the end of the table or in the first free location:

Not collapsing empty locations avoids reading and writing data that is not changing. Using free locations avoids extending the file size.

Over time this behaviour can leave a table with empty entries and newer entries before older.

The contents within a .keychain file are not well defined. The file itself describes itself. This was initially difficult for me to understand. The first table, describes both itself and the tables to come. This design has allowed the format to be extended and extended over time by Apple’s engineers.

This self-described format also means that your Keychain files may contain tables and formats that another user’s file does not. It depends on which versions of macOS used the file.

Secure Notes

A secure note has been found to be a table item with an attribute value called “type” set to 0x6e6f7465 (four char code note). There must be associated data and it must be encrypted. If all this is true, Keysafe attempts to decode the item first as a property list containing multiple formats (txt, rtf, rtfd, …) or if the data is not clearly a property list, the note is assumed to be plain text (txt).