You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Telegram登录时哈希校验失败问题求助

Telegram登录哈希校验失败(Python3.11适配)

问题:切换到Python3.11后,Telegram登录的哈希校验函数失效,哈希值始终不匹配,此前该函数可正常运行。

当前校验代码:

def check_hash(body):
    secret_key = sha256(os.environ.get("TG_TOKEN", "").encode()).digest()
    hash_string = body.pop("hash")
    data_string = [f"{key}={value}" for key, value in body.items()]
    data_string = "\n".join(sorted(data_string))
    return hmac.new(secret_key, data_string.encode(), sha256).hexdigest() == hash_string

解决步骤

1. 强制所有参数值转为字符串

Telegram哈希校验要求所有参数值必须以字符串形式参与计算,如果body中存在整数类型的参数(如id、auth_date),Python3.11的隐式类型转换逻辑可能导致结果与Telegram预期不一致。修改列表推导式,显式将值转为字符串:

data_string = [f"{key}={str(value)}" for key, value in sorted(body.items())]

2. 过滤非官方参数

如果body中包含自定义参数(如请求标识、csrf令牌等),会导致拼接的字符串与Telegram生成哈希时的原始数据不一致。只保留Telegram官方返回的字段:
id, first_name, last_name, username, photo_url, auth_date

示例过滤代码:

allowed_keys = {"id", "first_name", "last_name", "username", "photo_url", "auth_date"}
filtered_body = {k: v for k, v in body.items() if k in allowed_keys}

3. 验证Bot Token正确性

确认os.environ.get("TG_TOKEN")获取的是正确的Telegram Bot Token,无多余空格、大小写错误,且已正确配置到环境变量中。

4. 确认换行符格式

确保拼接字符串时使用**LF(\n)**分隔符,避免出现CRLF(\r\n),Telegram官方明确要求使用LF分隔参数。

修复后的完整函数

import os
import hmac
from hashlib import sha256

def check_hash(body):
    bot_token = os.environ.get("TG_TOKEN", "")
    if not bot_token:
        return False
    
    secret_key = sha256(bot_token.encode()).digest()
    hash_string = body.get("hash")
    if not hash_string:
        return False
    
    # 过滤并格式化官方参数
    allowed_keys = {"id", "first_name", "last_name", "username", "photo_url", "auth_date"}
    filtered_data = {k: str(v) for k, v in body.items() if k in allowed_keys and v is not None}
    
    # 按字典序排序拼接
    data_pairs = sorted([f"{k}={v}" for k, v in filtered_data.items()])
    data_string = "\n".join(data_pairs)
    
    # 计算哈希并对比
    computed_hash = hmac.new(secret_key, data_string.encode(), sha256).hexdigest()
    return computed_hash == hash_string

内容的提问来源于stack exchange,提问作者Artem Milosevic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:25:21