0

Help, when checking the hash it gives the error “Invalid Telegram data hash.” Perhaps someone has encountered this, I would be very grateful for your help..............................................................................................................................................................................

import https from 'https';
import express from 'express';
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import cors from 'cors';

const app = express();
const PORT = process.env.PORT || 3005;
const TELEGRAM_BOT_TOKEN = '';
const JWT_SECRET = '123123';

app.use(cors());
app.use(express.json());

const verifyTelegramData = (data) => {
    const secret = crypto.createHash('sha256').update(TELEGRAM_BOT_TOKEN).digest();

    const checkString = Object.entries(data)
        .filter(([key]) => key !== 'hash')
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([key, value]) => `${key}=${typeof value === 'object' ? JSON.stringify(value) : value}`)
        .join('\n');

    const hash = crypto.createHmac('sha256', secret).update(checkString).digest('hex');

    console.log('Check String:', checkString);
    console.log('Calculated Hash:', hash);
    console.log('Received Hash:', data.hash);

    return hash === data.hash;
};

app.post('/auth/telegram', (req, res) => {
    const { id, first_name, username, photo_url, auth_date, hash } = req.body;

    console.log('Received Telegram data:', req.body);

    if (!verifyTelegramData(req.body)) {
        console.log('Invalid Telegram data hash');
        return res.status(401).send('Unauthorized');
    }

    const token = jwt.sign({ id, first_name, username, photo_url }, JWT_SECRET, { expiresIn: '1h' });
    res.json({ token, user: { id, first_name, username, photo_url } });
});

const options = {
  key: fs.readFileSync('/etc/letsencrypt/live/cloa.xyz/privkey.pem'),
  cert: fs.readFileSync('/etc/letsencrypt/live/cloa.xyz/fullchain.pem')
};

https.createServer(options, app).listen(PORT, () => {
  console.log(`Server is running on https://localhost:${PORT}`);
});

1
  • You created an api endpoint which receives some data, create a hash from the data and check against the hash included in the data itself. However, you have never mentioned how is the received data generated, and most importantly how is the received hash generated. Without that information, no one can give an accurate answer and the only thing can be told is the hashing method used to generate the received data might be different from that you used to verify.
    – Ricky Mo
    Commented Jul 9 at 2:26

0

Browse other questions tagged or ask your own question.