Skip to content

Instantly share code, notes, and snippets.

@mthri
Created May 12, 2024 11:39

Revisions

  1. mthri created this gist May 12, 2024.
    28 changes: 28 additions & 0 deletions verify.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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