Last active
May 11, 2020 11:28
-
-
Save thebitrock/13abf1d0fef549a5d50204bc2ff34086 to your computer and use it in GitHub Desktop.
check_telegram_signature.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:crypto/crypto.dart'; | |
void main() { | |
final jsonMap = { | |
'id': 12312312, | |
'first_name': 'Elvis', | |
'username': 'user', | |
'auth_date': 1575754808, | |
'hash': '612bf9823a7eab38603d8cd7510c01e9cd74cf1688f139e850542057084ffca2' | |
}; | |
final botToken = '1233456:AAFZwKCq58c1p3Gd6fbBRJiguuIaBvTvraU'; | |
var dataMap = Map.from(jsonMap)..removeWhere((k, v) => k == 'hash'); | |
var list = dataMap | |
.map((key, value) => MapEntry(key, '$key=$value')) | |
.values | |
.toList() | |
..sort(); | |
var verifyString = list.join('\n'); | |
var secret = latin1.encode(botToken); | |
var checkString = latin1.encode(verifyString); | |
var secretSha256 = sha256.convert(secret); | |
var hmacSha256 = Hmac(sha256, secretSha256.bytes); | |
var stringHash = hmacSha256.convert(checkString); | |
if (stringHash != jsonMap['hash']) { | |
throw Exception('Data is invalid'); | |
} | |
final now = DateTime.now(); | |
final authTimestamp = (jsonMap['auth_date'] as int) * 1000; | |
final authDate = DateTime.fromMillisecondsSinceEpoch(authTimestamp); | |
final diff = now.difference(authDate); | |
if (diff > Duration(days: 1)) { | |
throw Exception('Data is outdated'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment