tdlib / td

Cross-platform library for building Telegram clients
https://core.telegram.org/tdlib
Boost Software License 1.0
7.06k stars 1.44k forks source link

Error:Validating data received via the Web App #2223

Closed prog-ape closed 1 year ago

prog-ape commented 1 year ago

public class CheckTelegramAuth { private final String botToken, dataCheck, hash; private final long authDate;

public CheckTelegramAuth(String botToken, String authQueryParams) throws Exception {
    String hash = null;
    long authDate = 0;
    String[] params = authQueryParams.split("&");
    Set<String> set = new TreeSet<>();
    for (String p : params) {
        if (p.startsWith("hash=")) {
            hash = p.substring(5);
        } else {
            set.add(p);
        }
        if (p.startsWith("auth_date=")) {
            authDate = Long.parseLong(p.substring(10));
        }
    }
    this.hash = hash;
    this.authDate = authDate;
    this.dataCheck = String.join("\n", set);
    this.botToken = botToken;

    boolean res=isFromTelegram();
    System.out.println(res);
}

public Date authDate() {
    return new Date(authDate * 1000L);
}

public boolean isFromTelegram() throws Exception {
    byte[] secret = sha256(botToken.getBytes());
    String result = hmacSha256(secret, dataCheck);
    return result.equals(hash);
}

private static byte[] sha256(byte[] string) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    return md.digest(string);
}

private static String hmacSha256(byte[] key, String data) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac hmacSha256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(key, "HmacSHA256");
    hmacSha256.init(secret_key);
    byte[] result = hmacSha256.doFinal(data.getBytes());
    return hex(result);
}

private static String hex(byte[] str) {
    return String.format("%040x", new BigInteger(1, str));
}

}

levlam commented 1 year ago

https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app: "with the secret key which is the HMAC-SHA-256 signature of the bot's token with the constant string WebAppData used as a key."

You use sha256(botToken) instead of that.

prog-ape commented 1 year ago

https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app:“使用密钥,它是[机器人令牌的](https://core.telegram.org/bots#creating-a-new-bot)[HMAC-SHA-256](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)签名,带有常量字符串用作钥匙。”[](https://core.telegram.org/bots#creating-a-new-bot)`WebAppData`

你用sha256(botToken)而不是那个。

Thank you, problem solved