Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Telegram website login widget, signature check sample using Node.js
// Copied by https://gist.github.com/dotcypress/8fd12d6e886cd74bba8f1aa8dbd346aa,
// thanks for improving code style
const { createHash, createHmac } = require('crypto');
const TOKEN = "ABC:12345...";
// I prefer get the secret's hash once but check the gist linked
// on line 1 if you prefer passing the bot token as a param
const secret = createHash('sha256')
.update(TOKEN)
.digest()
function checkSignature ({ hash, ...data }) {
const checkString = Object.keys(data)
.sort()
.map(k => (`${k}=${data[k]}`))
.join('\n');
const hmac = createHmac('sha256', secret)
.update(checkString)
.digest('hex');
return hmac === hash;
}
// Sample usage
const payload = {
id: '424242424242',
first_name: 'John',
last_name: 'Doe',
username: 'username',
photo_url: 'https://t.me/i/userpic/320/username.jpg',
auth_date: '1519400000',
hash: '87e5a7e644d0ee362334d92bc8ecc981ca11ffc11eca809505'
}
checkSignature(payload)
@Kradre

This comment has been minimized.

Copy link

Kradre commented Feb 19, 2018

Thanks for good string object.
Change one thing:
const hmac = crypto.createHmac('sha256', secret.digest('latin1'))
.update(checkString)
.digest('hex')
And everything should work
Node version: 4.2.6

@highfeed

This comment has been minimized.

Copy link

highfeed commented Feb 24, 2018

It's don't work for me.

@Pitasi

This comment has been minimized.

Copy link
Owner Author

Pitasi commented Feb 24, 2018

Updated.
I basically copied https://gist.github.com/dotcypress/8fd12d6e886cd74bba8f1aa8dbd346aa, thanks @highfeed for linking that to me.

@YuriyLitvin

This comment has been minimized.

Copy link

YuriyLitvin commented Apr 20, 2018

Thank you @Pitasi ! :-) 👍

@peramor

This comment has been minimized.

Copy link

peramor commented May 5, 2018

Nice, very helpful!

@rinovaonline

This comment has been minimized.

Copy link

rinovaonline commented Jan 19, 2019

Nice

@pitersky

This comment has been minimized.

Copy link

pitersky commented Jun 12, 2019

Thank you, But does not work for me either. Hashes does not match

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.