Skip to content

Instantly share code, notes, and snippets.

@xen
Last active May 3, 2024 21:19
Show Gist options
  • Save xen/e4bea72487d34caa28c762776cf655a3 to your computer and use it in GitHub Desktop.
Save xen/e4bea72487d34caa28c762776cf655a3 to your computer and use it in GitHub Desktop.
telegram site auth
# implementation of Telegram site authorization checking algorithm
# for more information https://core.telegram.org/widgets/login#checking-authorization
import collections
import hmac
import hashlib
def check_string(d, token):
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(d.items()))
param_hash = sorted_params.pop('hash')
msg = "\n".join(["{}={}".format(k, v) for k, v in sorted_params.items()])
if param_hash == hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest():
return True
return False
@vol1ura
Copy link

vol1ura commented Apr 2, 2023

Can't understand- code is OK, but it doesn't match the hash.

@iQiexie
Copy link

iQiexie commented Aug 22, 2023

it works ok for:

data = {
    "id": 12345678,
    "first_name": "first_name",
    "username": "username",
    "photo_url": "https://t.me/i/userpic/320/pic_idjpg",
    "auth_date": 1692687292,
    "hash": "99a21539180cc8999e96899284f62492b47495a5a32fdb45ca6140d85f7ae33b"
}

but it doesnt work for

data = {
  "query_id": "AAHf7M8DAAAAAN_szwNmQ4Lc",
  "user": {
    "id": 12345678,
    "first_name": "first_name",
    "last_name": "",
    "username": "username",
    "language_code": "en",
    "is_premium": True,
    "allows_write_to_pm": True
  },
  "auth_date": "1692686970",
  "hash": "4317efd665c01a62973e1abd82aabe4128ca73ac67d0dba57d80656b8150dca5"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment