Skip to content

ruvn-1fgas/tgdesktop-cache-decrypt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Telegram Desktop Cache Decryptor

Python Version Tested Version

Python tool to decrypt and extract data from Telegram Desktop tdata:
recover cached media, export per-account local storage as JSON, and decrypt MTProto session authorization (auth keys per DC).

Features

  • Media cache - decrypt user_data cache files and collect images/videos into a flat folder
  • Account data - parse per-account tdata folders (16-hex IDs), map/LSK, TDF/binlog
  • MTProto authorization - user_id, main_dc_id, and auth_keys (256-byte keys per DC as hex), suitable for building a Telethon/Pyrogram-style client session without re-login
  • Structured JSON export - drafts, stickers, saved GIFs, locations, settings, map entries, and more

How It Works

Telegram Desktop stores encrypted data in tdata. This tool:

  1. Extracts the Local Encryption Key from Telegram's key_datas file
  2. Decrypts the Master Key using PBKDF2 and AES-IGE encryption
  3. Parses account folders in tdata (16-hex subdirectories) and reads LSK/map/TDF storage
  4. Decrypts MTProto authorization from per-account *s files and exports session fields as JSON
  5. Processes cache files in the user_data directory
  6. Decrypts each cache file using AES-CTR (and TDEF handling for labeled media paths)
  7. Identifies file types by analyzing file signatures
  8. Organizes output into three directories (recreated on each run)

The decryption process uses the same cryptographic algorithms that Telegram Desktop uses internally.

Prerequisites

  • Python 3.12 or higher
  • Telegram Desktop installed with cached data

Installation

1. Clone the Repository

git clone https://github.com/ruvn-1fgas/tgdesktop-cache-decrypt.git
cd tgdesktop-cache-decrypt

2. Install Dependencies

pip install -r requirements.txt

Usage

Basic Usage

Simply run the script:

python main.py

Custom Telegram Path

If Telegram is installed in a non-standard location, create a .env file:

TELEGRAM_PATH=C:/Custom/Path/To/Telegram Desktop/tdata

Or modify settings.py directly.

Output Structure

The tool creates three output directories:

1. decrypted_account/

Per-account JSON export. Folder name is user_id from MTProto auth, or the 16-hex tdata folder id if auth was not found.

decrypted_account/
└── <user_id>/
    ├── mtp_auth.json          # MTProto session (see below)
    ├── drafts.json
    ├── recent_stickers.json
    ├── faved_stickers.json
    ├── saved_gifs.json
    ├── installed_sticker_sets.json
    ├── featured_sticker_sets.json
    ├── user_settings.json
    ├── recent_hashtags_bots.json
    ├── locations.json
    └── map_entries.json

Only non-empty sections are written. After the run, the console prints a summary per account (drafts count, sticker sets, MTProto auth status, etc.).

mtp_auth.json

Decrypted MTProto authorization from Telegram Desktop's serialized MTP blob:

{
  "user_id": 123456789,
  "main_dc_id": 2,
  "auth_keys": [
    { "dc_id": 2, "auth_key_hex": "..." }
  ],
  "keys_to_destroy": []
}

Each auth_key_hex is a 256-byte MTProto auth key for that data center. You can use these fields to authorize API clients (e.g. Telethon) without scanning a QR code again.

2. decrypted/

Contains the full decrypted cache structure, preserving Telegram's original directory hierarchy:

decrypted/
├── user_data/
│   ├── media_cache/
│   │   ├── 0/
│   │   │   ├── 00/
│   │   │   │   ├── XXXXXXXXXXXX.png
│   │   │   │   ├── XXXXXXXXXXXX.jpg
│   │   │   │   └── ...
│   │   │   ├── 0A/
│   │   │   │   └── ...
│   └── ...

3. decrypted_combined/

Contains all media files (matching COMBINE_EXTENSIONS) in a single flat directory for easy browsing:

decrypted_combined/
├── XXXXXXXXXXXX.jpg
├── XXXXXXXXXXXX.png
├── XXXXXXXXXXXX.mp4
├── XXXXXXXXXXXX.gif
└── ...

Note: If files have identical names, automatic numbering is applied (e.g., XXXXXXXXXXXX_1.jpg, XXXXXXXXXXXX_2.jpg).


Telegram Desktop Cache Decryptor (RU)

Инструмент для расшифровки tdata Telegram Desktop: восстановление кеш-медиа, экспорт локальных данных аккаунта в JSON и расшифровка MTProto-авторизации.

Возможности

  • Кеш медиа - расшифровка файлов в user_data и сбор изображений/видео в плоскую папку
  • Данные аккаунта - разбор папок аккаунтов в tdata (16 hex), map/LSK, TDF/binlog
  • MTProto-авторизация - user_id, main_dc_id, auth_keys (256-байтные ключи по DC в hex); подходит для сессии Telethon/Pyrogram без повторного входа
  • JSON-экспорт - черновики, стикеры, сохранённые GIF, locations, настройки, записи map и др.

Как это работает

Telegram Desktop хранит зашифрованные данные в tdata. Инструмент:

  1. Извлекает локальный ключ шифрования из файла key_datas
  2. Расшифровывает мастер-ключ (PBKDF2 + AES-IGE)
  3. Разбирает папки аккаунтов в tdata (16 hex) и читает LSK/map/TDF
  4. Расшифровывает MTProto-авторизацию из файлов *s и сохраняет поля сессии в JSON
  5. Обрабатывает кеш в user_data
  6. Расшифровывает каждый файл кеша (AES-CTR, TDEF для размеченных media-путей)
  7. Определяет типы файлов по сигнатурам
  8. Сохраняет результат в три каталога (пересоздаются при каждом запуске)

Используются те же криптографические алгоритмы, что и в Telegram Desktop.

Требования

  • Python 3.12 или выше
  • Telegram Desktop установлен с кешированными данными

Установка

1. Клонируйте репозиторий

git clone https://github.com/ruvn-1fgas/tgdesktop-cache-decrypt.git
cd tgdesktop-cache-decrypt

2. Установите зависимости

pip install -r requirements.txt

Использование

Базовое

python main.py

Нестандартный путь к Telegram

Создайте .env:

TELEGRAM_PATH=C:/Custom/Path/To/Telegram Desktop/tdata

Или измените settings.py.

Структура результатов

Создаются три выходные директории:

1. decrypted_account/

JSON по каждому аккаунту. Имя папки - user_id из MTProto, либо 16-hex id папки в tdata, если авторизация не найдена.

decrypted_account/
└── <user_id>/
    ├── mtp_auth.json          # сессия MTProto (см. ниже)
    ├── drafts.json
    ├── recent_stickers.json
    ├── faved_stickers.json
    ├── saved_gifs.json
    ├── installed_sticker_sets.json
    ├── featured_sticker_sets.json
    ├── user_settings.json
    ├── recent_hashtags_bots.json
    ├── locations.json
    └── map_entries.json

Пустые разделы не записываются. В консоли выводится сводка по аккаунтам.

mtp_auth.json

Расшифрованная MTProto-авторизация:

{
  "user_id": 123456789,
  "main_dc_id": 2,
  "auth_keys": [
    { "dc_id": 2, "auth_key_hex": "..." }
  ],
  "keys_to_destroy": []
}

auth_key_hex - 256-байтный auth key для соответствующего DC. Эти данные можно использовать для входа через API-клиент (например, Telethon) без повторной авторизации.

2. decrypted/

Полная расшифрованная структура кеша:

decrypted/
├── user_data/
│   ├── media_cache/
│   │   ├── 0/
│   │   │   ├── 00/
│   │   │   │   ├── XXXXXXXXXXXX.png
│   │   │   │   └── ...
│   └── ...

3. decrypted_combined/

Медиафайлы (COMBINE_EXTENSIONS) в одной плоской директории:

decrypted_combined/
├── XXXXXXXXXXXX.jpg
├── XXXXXXXXXXXX.png
└── ...

Примечание: при совпадении имён добавляется нумерация (XXXXXXXXXXXX_1.jpg, …).

About

Decrypts Telegram Desktop media-cache and MTProto sessions

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages