Created
May 12, 2024 11:39
-
-
Save mthri/1696b8cbf1f70de3b4efe50f7220f7c1 to your computer and use it in GitHub Desktop.
Extracting and Verifying Telegram Web App Data in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import hmac | |
TELEGRAM_BOT_TOKEN = 'BOT_TOKEN | |
def extract_telegram_web_app_data(telegram_init_data: str) -> dict: | |
return dict(qc.split('=') for qc in telegram_init_data.split('&')) | |
def verify_telegram_web_app_data(telegram_init_data: str) -> bool: | |
init_data = dict(qc.split('=') for qc in telegram_init_data.split('&')) | |
hash_value = init_data.pop('hash', None) | |
data_to_check = '\n'.join(f'{key}={init_data[key]}' for key in sorted(init_data.keys()) if key != 'hash') | |
secret_key_stage1 = hmac.new( | |
key=bytes('WebAppData', 'utf-8'), | |
msg=bytes(TELEGRAM_BOT_TOKEN, 'utf-8'), | |
digestmod=hashlib.sha256 | |
).digest() | |
computed_hash = hmac.new( | |
key=secret_key_stage1, | |
msg=bytes(data_to_check, 'utf-8'), | |
digestmod=hashlib.sha256 | |
).hexdigest() | |
return computed_hash == hash_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment