Skip to content

Instantly share code, notes, and snippets.

@Green-m
Last active November 28, 2023 03:50
Show Gist options
  • Save Green-m/6e3a6d2ffbb1b669d37b756572ca232f to your computer and use it in GitHub Desktop.
Save Green-m/6e3a6d2ffbb1b669d37b756572ca232f to your computer and use it in GitHub Desktop.
Telegram for macos parse tempkeyEncrypted
# install pycryptodome or pycryptodomex
# pip install mmh3 pycryptodome pycryptodomex
# From https://gist.github.com/stek29/8a7ac0e673818917525ec4031d77a713
import os
import sqlite3
import io
import struct
import enum
import mmh3
import pprint
import datetime
try:
from Cryptodome.Hash import SHA512
from Cryptodome.Cipher import AES
except ImportError:
from Cryptodome.Hash import SHA512
from Cryptodome.Cipher import AES
import binascii
DEFAULT_PASSWORD = 'no-matter-key'
def murmur(d):
# seed from telegram
return mmh3.hash(d, seed=-137723950)
def tempkey_kdf(password):
h = SHA512.new()
h.update(password.encode('utf-8')) # never tried on non-ascii passwords tho
digest = h.digest()
key, iv = digest[0:32], digest[-16:]
return key, iv
def tempkey_parse(dataEnc, pwd):
aesKey, aesIV = tempkey_kdf(DEFAULT_PASSWORD)
cipher = AES.new(key=aesKey, iv=aesIV, mode=AES.MODE_CBC)
data = cipher.decrypt(dataEnc)
dbKey = data[0:32]
dbSalt = data[32:48]
dbHash = struct.unpack('<i', data[48:52])[0]
dbPad = data[52:]
if len(dbPad) != 12 and any(dbPad):
print('warn: dbPad not 12 zeros')
calcHash = murmur(dbKey+dbSalt)
if dbHash != calcHash:
raise Exception(f'hash mismatch: {dbHash} != {calcHash}')
return dbKey, dbSalt
def tempkey_pragma(dbKey, dbSalt):
key = binascii.hexlify(dbKey+dbSalt).decode('utf-8')
return '''PRAGMA key="x'{}'"'''.format(key);
#with open('tempkeyEncrypted', 'rb') as f:
# tempkeyEnc = f.read()
#dbKey, dbSalt = tempkey_parse(tempkeyEnc, DEFAULT_PASSWORD)
#print(tempkey_pragma(dbKey, dbSalt))
# extract key
key_file = os.path.expanduser(
'/Users/yourname/Library/Group Containers/6N38VWS5BX.ru.keepcoder.Telegram/stable/.tempkeyEncrypted'
)
with open(key_file, 'rb') as f:
tempkeyEnc = f.read()
dbKey, dbSalt = tempkey_parse(tempkeyEnc, DEFAULT_PASSWORD)
print(tempkey_pragma(dbKey, dbSalt))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment