Overview

As early as 2013, many people online were already researching the structure of WeChat’s database. Overall, WeChat has consistently used WCDB—a database built on top of SQLite and SQLCipher—for many years. Prior to 2023, WeChat’s encryption algorithm followed a single approach: concatenating IMEI + UID into bytes[], generating an MD5 hash, and taking the first 7 characters to derive an AES-256 key for encryption. I find this approach somewhat amusing, as anyone could reverse-engineer WeChat to understand the algorithm and obtain the key. If someone gained control over a user’s device, they could simply pull the files out and decrypt them, exporting all WeChat chat history without needing the account password.

In the past, a large number of WeChat chat history export tools on the internet were based on this method. Tools like WeChat Clean were widely praised; the developer’s original intention was to analyze what was taking up space when WeChat consumed too much storage, and to clean up unnecessary cache and group data accordingly. However, Tencent’s legal team later sent DMCA takedown notices to GitHub demanding the removal of the project. This didn’t just affect one project—over thirty similar repositories for chat history analysis and export were taken down.

Subsequently, WeChat changed its encryption method: it first generates a random password, derives a key from it along with a salt via PBKDF2, encrypts the chat records using AES-256-CBC, and finally processes it with HMAC to generate a Message Authentication Code, which is stored at the end of each page. This time, it is finally a legitimate encryption scheme; however, we can still read the key directly from memory to decrypt and export our chat history.

This article will first explain the database encryption principles in the current Windows version of WeChat. In future articles, I will continue to untangle and explain the decryption principles, and finally demonstrate how to read the key from memory to decrypt the WeChat database and export chat history.

WeChat’s Encryption Principles

In this chapter, we will directly inspect the source code of WCDB: Tencent/wcdb master branch, version 2.1.16.
All paths mentioned in this article use the WCDB repository as the root.
The WCDB source code paths are src/common/... and src/cpp/....
The SQLCipher source code path is sqlcipher/src/....

What is the Relationship Between WCDB, SQLCipher, and SQLite?

  1. SQLite: SQLite is a lightweight, self-contained, serverless, zero-configuration, transactional relational database management system (RDBMS), and it serves as WeChat’s database engine. The entire database is a single file. Vanilla SQLite is unencrypted; its files can be opened with any SQLite tool, or even directly in a text editor.
  2. SQLCipher: SQLCipher is an SQLite extension that provides transparent 256-bit AES encryption of the entire database file.
  3. WCDB: An open-source database framework developed by the WeChat team. It embeds Tencent’s own maintained fork of SQLCipher and provides features such as ORM, repair, compression, and migration—encryption is just one of its capabilities.

Where is WeChat’s Encryption Entry Point?

WeChat 4.x first uses a randomly generated value as the database password, and then passes it to WCDB via setCipherKey.

Looking through its source code, we can see:

void Database::setCipherKey(const UnsafeData& cipherKey, int cipherPageSize, CipherVersion cipherVersion)
{
    if (cipherKey.size() > 0) {
        m_innerDatabase->setConfig(    // Create a CipherConfig object inside InnerDatabase
        CipherConfigName,
        std::static_pointer_cast<Config>(std::make_shared<CipherConfig>(
        cipherKey, cipherPageSize, cipherVersion)),
        Configs::Priority::Highest);
    } else {
        m_innerDatabase->removeConfig(CipherConfigName);
    }
}

This code is used to set the database password while creating a CipherConfig object to store all encryption configurations.
The three parameters of Database::setCipherKey are the password, the page size (defaulting to 4096), and the cipher version. The first parameter, cipherKey, is the password. Its type, UnsafeData, is essentially the starting address of a byte buffer plus its length, defined as follows:

class WCDB_API UnsafeData : protected SharedThreadedErrorProne {
...
protected:
	unsigned char *m_buffer;
	size_t m_size;
...
};

If we can locate UnsafeData& cipherKey and derive the key via PBKDF2, we will have the exact AES-256 key needed to decrypt the database. However, since we are only discussing encryption principles right now, we will revisit this variable later.

Every time SQLite opens a database file, it creates a handle , and all subsequent SQL statements are executed through that handle. Internally, WCDB maintains a handle pool and only creates a new handle when multiple threads are reading or writing concurrently and no idle handle is available.

Whenever a new handle is created, WCDB executes all registered configurations in order of priority. The encryption configuration has the highest priority and passes the password to SQLCipher by calling sqlite3_key during connection initialization:

int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) {
  return sqlite3_key_v2(db, "main", pKey, nKey);              // Defaults to the main database ("main")
}

int sqlite3_key_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
  if(db && pKey && nKey) {
    int db_index = sqlcipher_find_db_index(db, zDb);
    return sqlite3CodecAttach(db, db_index, pKey, nKey);
  }
  return SQLITE_ERROR;
}

int sqlite3CodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) {
  ...
  rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, zKey, nKey);  // 1. Create ctx and store the password
  ...
  sqlite3PagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL,
                       sqlite3FreeCodecArg, (void *) ctx);                       // 2. Register the codec hook and cleanup callback
  ...
}

SQLite’s Page Mechanism and Hook Interception Timing

SQLite uses a page as its smallest unit of storage, dividing the database file into contiguous, equal-sized blocks of data (where tables, indexes, and free space are all stored on disk). The WeChat database uses a fixed page size of 4096 bytes: Page 1 starts at byte offset 0, Page 2 at 4096, and so on.

The internal SQLite module responsible for whole-page disk I/O is called the pager, which exposes a reserved Codec Hook. Once sqlite3PagerSetCodec in the code snippet above mounts sqlite3Codec (SQLCipher’s encryption/decryption callback function) onto this hook, SQLCipher is seamlessly integrated into the entire read/write pipeline:

  • On disk read: After the pager reads an entire encrypted page from disk, it triggers sqlite3Codec to decrypt the page before passing it up to upper layers for parsing.

  • On disk write: Before flushing to disk, the pager invokes sqlite3Codec to encrypt the entire page and then writes the ciphertext to disk.

  • On connection close: The sqlite3FreeCodecArg callback passed during registration is automatically triggered to clean up and free the entire ctx context (for details on the exact field in ctx where the password is stored, see the “Before and After Key Derivation” section below).

Layout of a Page (using the default 4096-byte page and cipher version 4 as an example)

Page 1 (4096 bytes)
salt0–15
AES-256-CBC Ciphertext16–4015
IV4016–4031
HMAC4032–4095
Reserve Area (80 bytes)
Page 2 and Subsequent Pages (4096 bytes)
AES-256-CBC Ciphertext0–4015
IV4016–4031
HMAC4032–4095
Reserve Area (80 bytes)
Plaintext Ciphertext IV (16 bytes, random) HMAC-SHA512 (64 bytes)

This region at the end of the page storing the IV and HMAC is called the reserve area. Its size is calculated by sqlcipher_codec_ctx_reserve_setup: the IV length plus the HMAC length, rounded up to a multiple of 16. For Cipher 4, its size is 80 bytes. It stores two things:

  • IV (first 16 bytes): The random Initialization Vector required for AES-256-CBC encryption. A new random IV is generated every time this page is written, so encrypting the exact same content produces different ciphertext each time, preventing attackers from telling whether the content has changed by comparing ciphertexts. Since the same IV must be used for decryption, it is stored alongside the ciphertext; the IV does not need to be kept secret, as it cannot decrypt anything without the key.
  • HMAC (last 64 bytes): The authentication code computed using the HMAC key over “the page’s ciphertext + IV + page number”. When reading the page, SQLCipher recalculates and compares it: if they do not match, it indicates the page was tampered with, corrupted, or swapped to another location, and an error is raised immediately without attempting decryption.
Cipher Version HMAC Algorithm IV + HMAC Reserve Area Size
4 (WCDB default) HMAC-SHA512 16 + 64 = 80 80 bytes
2, 3 HMAC-SHA1 16 + 20 = 36 Rounded up to 48 bytes
1 No HMAC 16 16 bytes

What Happens After the Hook is Called, and How is the Key Derived?

When the hook is invoked for the first time, SQLCipher first reads the salt from the beginning of the file and combines it with the previously stored password as input to derive the AES-256 key via PBKDF2. Next, it packs the AES-256 key and the salt into a keyspec, and then derives the HMAC key from the AES-256 key. Once the computation is complete, the raw password is wiped. From then on, every time a page is read or written, SQLCipher uses the AES-256 key and that page’s IV to encrypt or decrypt the page, and uses the HMAC key to compute or verify the authentication code.

Let’s briefly break down what each of these terms means:

salt: A 16-byte random number combined with the password during derivation

Hashing the same password with algorithms like MD5 or SHA-256 always yields the exact same hash value. Therefore, adding a different salt to the same password produces different results. Deriving the key requires the salt, and no page can be decrypted without the key, so the salt must be readable before decryption and can only be stored in plaintext. The first 16 bytes of a standard SQLite file contain a fixed magic header SQLite format 3\0, which carries no unique information and can be restored verbatim upon decryption. Consequently, SQLCipher stores the salt right here. This is why WeChat 4.x database files begin with 16 bytes of random data instead of the SQLite magic header.

PBKDF2: Turning the password into 32 bytes

AES-256 requires a key that is exactly 32 bytes long and appears completely random. PBKDF2 (Password-Based Key Derivation Function 2) is responsible for turning “password + salt” into such a key. It works by mixing the password and salt together through HMAC, feeding the result as the input to the next round, and repeating this process 256,000 times to obtain the final 32-byte AES-256 key.

AES-256-CBC

A symmetric encryption algorithm where the same key is used for both encryption and decryption. AES processes data in 16-byte blocks, and “256” refers to the key length of 256 bits (32 bytes). CBC (Cipher Block Chaining) is the mode used to link data blocks: before encryption, each block is XORed with the previous ciphertext block, while the first block is XORed with a 16-byte Initialization Vector (IV). Thus, the same plaintext paired with different IVs yields completely different ciphertexts. SQLCipher uses it to encrypt every page.

HMAC

A keyed hash used to verify whether data has been altered. It takes a key and a piece of input data, outputting a fixed-length authentication code; anyone without the key cannot compute a valid authentication code for modified data. SQLCipher uses HMAC-SHA512, which outputs 64 bytes. HMAC is strictly responsible for detecting tampering, not for confidentiality.

keyspec: Key cache

keyspec is a 99-character string. It converts the AES key and salt into hexadecimal and concatenates them directly. Its format consists of four segments:

Segment Content Character Count
x' Fixed prefix indicating “hexadecimal follows” 2
Encryption Key 32 bytes written in hexadecimal 64
salt 16 bytes written in hexadecimal 32
' Fixed suffix 1

It looks roughly like this:

x'
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855    ← Encryption key (64 chars)
1f8ac10f23c5b5bc1167bda84b833e5c                                    ← salt (32 chars)
'

The generation process of keyspec is straightforward: SQLCipher allocates a 99-byte block of memory via sqlcipher_malloc, writes x', the hex-encoded encryption key, the hex-encoded salt, and ' in sequence, and stores it in read_ctx->keyspec. Later, SQLCipher can directly parse keyspec to extract the key and salt for database encryption/decryption, skipping the derivation process to improve performance. However, this also makes it convenient for us to reverse-engineer the key, which we will discuss in future articles.

Overall, the key derivation process is illustrated in the following diagram:

Password + salt
PBKDF2-HMAC-SHA512, 256,000 iterations
Encryption Keyc_ctx->key (32 bytes) AES encrypts/decrypts each page
PBKDF2, 2 iterations HMAC Keyc_ctx->hmac_key (32 bytes) Verifies each page
Convert to hex & concatenate with salt keyspec99 bytes Cached in CipherConfig::m_rawKey

Before and After Derivation: Where is the Raw Password Stored and When is it Deleted?

Before derivation, the raw password is stored in two places.

The first place is WCDB’s CipherConfig::m_key. When setCipherKey creates CipherConfig, the constructor copies the password into m_key:

CipherConfig::CipherConfig(const UnsafeData& cipher, int pageSize, int cipherVersion)
: Config(), m_key(cipher), m_pageSize(pageSize), m_cipherVersion(cipherVersion)
{
}

The second place is SQLCipher’s read_ctx->pass and write_ctx->pass. When sqlite3_key is called, sqlcipher_codec_ctx_init first copies the password into read_ctx->pass, and then copies the entire read_ctx over to write_ctx:

/* set the key material on one of the sub cipher contexts and sync them up */
sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0);               // Password → read_ctx->pass
sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx);  // read_ctx → write_ctx

At this point, both sides only hold the raw password; the AES-256 key, HMAC key, and keyspec have not been computed yet.

Once derivation is complete, the raw password is deleted twice in succession.

The first deletion is performed by SQLCipher: derivation occurs when the hook is invoked for the first time, and the final step of the derivation function is to wipe the password stored in read_ctx and write_ctx. The second deletion is performed by WCDB: after all configurations for this connection have finished executing, WCDB first caches the keyspec into CipherConfig::m_rawKey, and then clears m_key. The detailed process is shown in the next section.

Where is keyspec Cached? WCDB’s CipherConfig

WCDB subsequently caches the keyspec into CipherConfig—the exact one created by setCipherKey earlier.

for (const auto &element : m_pendings) {
    if (!element.value()->invoke(this)) { ... return false; }   // Execute configurations one by one
    ...
    if (element.key().compare(CipherConfigName) == 0) {
        cipherConfig = element.value();                         // Record the encryption configuration
    }
}
...
convertedConfig->trySaveRawKey(this);                           // Called after all configurations finish executing

trySaveRawKey is the core function here:

void CipherConfig::trySaveRawKey(InnerHandle* handle)
{
    LockGuard lockGuard(m_lock);
    if (!m_rawKey.empty()) {
        return;                                // Already cached, return directly
    }
    m_rawKey = handle->getRawCipherKey();      // Save a copy of keyspec
    if (!m_rawKey.empty()) {
        m_key = Data();                        // Clear the raw password
    }
}

Both m_rawKey and m_key are members of CipherConfig:

class CipherConfig final : public Config {
    ...
protected:
    Data m_key;      // Raw password, cleared once keyspec is cached
    Data m_rawKey;   // Copy of keyspec
    ...
};

trySaveRawKey calls getRawCipherKey():

Data AbstractHandle::getRawCipherKey(const Schema &schema)
{
    void *rawCipher = NULL;
    int rawCipherSize = 0;
    int index = sqlcipher_find_db_index(m_handle, schema.syntax().name.data());
    sqlite3CodecGetKey(m_handle, index, &rawCipher, &rawCipherSize);  // Request keyspec from SQLCipher

    if (rawCipher == NULL || rawCipherSize == 0) {
        return Data();
    }
    WCTAssert(rawCipherSize == 99);
    return Data((unsigned char *) rawCipher, rawCipherSize);
}

sqlite3CodecGetKey ultimately calls:

void sqlcipher_codec_get_keyspec(codec_ctx *ctx, void **zKey, int *nKey) {
  *zKey = ctx->read_ctx->keyspec;
  *nKey = ctx->keyspec_sz;
}

At this stage, CipherConfig’s m_key (the raw password) has been cleared, leaving only m_rawKey (the copy of keyspec). Inside SQLCipher’s codec context, read_ctx->keyspec holds the original keyspec, and write_ctx holds another copy; the encryption key and HMAC key are also stored in these two contexts. The raw password no longer exists in either WCDB or SQLCipher.

Storage Locations of the Raw Password and the Three Keys

Item Before Derivation After Derivation
Raw Password CipherConfig::m_key; read_ctx->pass, write_ctx->pass Completely cleared
AES-256 Key Not yet generated read_ctx->key, write_ctx->key
HMAC Key Not yet generated read_ctx->hmac_key, write_ctx->hmac_key
keyspec Not yet generated read_ctx->keyspec (original), write_ctx->keyspec (copy), CipherConfig::m_rawKey (WCDB’s copy)

Viewed by their containing objects:

InnerDatabase (one per database, shared across all connections)
 └─ CipherConfig
     ├─ m_key      Raw password → cleared after keyspec is cached
     └─ m_rawKey   Copy of keyspec (99 bytes)

Per-connection codec_ctx (freed when the connection closes)
 ├─ read_ctx
 │   ├─ pass       Raw password → zeroed out and freed after derivation
 │   ├─ key        AES-256 key (32 bytes)
 │   ├─ hmac_key   HMAC key (32 bytes)
 │   └─ keyspec    Original keyspec (99 bytes)
 └─ write_ctx      Identical to read_ctx, copied from read_ctx during derivation

The difference between the two lies in their lifetimes: codec_ctx belongs to a single connection and is freed as soon as that connection closes, whereas CipherConfig belongs to the entire database and is shared by all connections. That is why WCDB copies keyspec into CipherConfig—so that newly opened connections can reuse it later.

As long as we can read any one of the raw password, the AES-256 key, or the keyspec from memory, we can directly or indirectly decrypt the WeChat database. We will continue exploring this in future articles.

How SQLCipher Encrypts and Decrypts Each Page

Once the keys are derived, SQLCipher no longer needs the raw password. From then on, every time SQLite reads or writes a page, the pager invokes the sqlite3Codec hook: before writing to disk, it encrypts the page with the AES-256 key and computes the authentication code with the HMAC key; after reading from disk, it first verifies the authentication code with the HMAC key, and only decrypts with the AES-256 key if verification succeeds.

Writing a Page: Encryption
int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode,
                          int page_sz, unsigned char *in, unsigned char *out) {
  cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;  // Retrieve keys from ctx
  int size = page_sz - ctx->reserve_sz;               // Usable payload = page size - reserve area
  unsigned char *iv_out    = out + size;              // Write IV right after the usable payload
  unsigned char *hmac_out  = out + size + ctx->iv_sz; // HMAC immediately follows IV

  // Fill the reserve area with random bytes; the first 16 bytes become this write's IV
  ctx->provider->random(ctx->provider_ctx, iv_out, ctx->reserve_sz);

  // Encrypt the usable payload with AES-256-CBC using c_ctx->key and this IV
  ctx->provider->cipher(ctx->provider_ctx, mode, c_ctx->key, ctx->key_sz,
                        iv_out, in, size, out);

  // Compute HMAC over "ciphertext + IV + page number" using HMAC key, and write it after IV
  sqlcipher_page_hmac(ctx, c_ctx, pgno, out, size + ctx->iv_sz, hmac_out);
  return SQLITE_OK;
}

Taking the default 4096-byte page as an example, the usable payload is 4096 − 80 = 4016 bytes (minus an additional 16 bytes at the beginning for Page 1). Once these three steps are complete, the page becomes “ciphertext + IV + authentication code”, matching the page layout diagram shown earlier. The pager writes this ciphertext to disk, while the copy of the page in its in-memory cache remains plaintext.

Reading a Page: Decryption

The decryption path follows the exact reverse order of encryption (abridged):

  // Extract the IV stored at the end of the page during write
  memcpy(iv_out, iv_in, ctx->iv_sz);

  // Recompute the authentication code using the HMAC key and compare with the one stored at the end of the page
  sqlcipher_page_hmac(ctx, c_ctx, pgno, in, size + ctx->iv_sz, hmac_out);
  if(sqlcipher_memcmp(hmac_in, hmac_out, ctx->hmac_sz) != 0) {
    goto error;                                      // Mismatch: tampered or corrupted, abort immediately without decrypting
  }

  // Verification passed; decrypt using the AES-256 key and the same IV
  ctx->provider->cipher(ctx->provider_ctx, mode, c_ctx->key, ctx->key_sz,
                        iv_out, in, size, out);

Conclusion

To summarize, WeChat’s database encryption process works as follows:

  1. WeChat generates a random value as the raw password and passes it to WCDB via setCipherKey, which stores it in CipherConfig::m_key.
  2. When a connection is established, the raw password is passed to SQLCipher. SQLCipher stores the raw password in the codec context ctx and attaches sqlite3Codec to the pager’s hook.
  3. When the hook is called for the first time, SQLCipher derives the AES-256 key, HMAC key, and keyspec from “raw password + salt”, stores them in read_ctx and write_ctx, and then wipes the raw password.
  4. WCDB copies keyspec into CipherConfig::m_rawKey and clears m_key. Subsequent newly opened connections use keyspec directly, skipping PBKDF2.
  5. Thereafter, on every page read or write, SQLCipher encrypts/decrypts using a random IV and the AES-256 key, and verifies page integrity using the HMAC key.

Clearly, WeChat’s scheme suffers from a limitation inherent to all transparent encryption systems: while the database is open, the keys must remain in memory. Obtaining any one of the raw password, the AES-256 key, or the keyspec allows us to directly or indirectly decrypt the corresponding database. In the next article, I will attempt to extract these variables from memory via reverse engineering in order to decrypt the WeChat database.

References

Further Reading