Created
August 6, 2024 09:32
-
-
Save YokiToki/cb55dba6645b5abca00784ce055c1261 to your computer and use it in GitHub Desktop.
Telegram validating data received via the Mini App Kotlin
This file contains hidden or 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 java.security.MessageDigest | |
import javax.crypto.Mac | |
import javax.crypto.spec.SecretKeySpec | |
fun checkSignature(token: String, initData: String): Boolean { | |
// Convert the data string to a map | |
val initDataMap = initData.split('&') | |
.map { it.split('=') } | |
.associate { it[0] to it[1] } | |
.toMutableMap() | |
// Extract the hash from the data | |
val receivedHash = initDataMap.remove("hash") | |
// Sort the remaining data and concatenate the key-value pairs | |
val dataCheckString = initDataMap.toSortedMap().entries.joinToString("\n") { "${it.key}=${it.value}" } | |
// Calculate the HMAC-SHA256 hash | |
val secretKey = MessageDigest.getInstance("SHA-256").digest(token.toByteArray()) | |
val mac = Mac.getInstance("HmacSHA256") | |
mac.init(SecretKeySpec(secretKey, "HmacSHA256")) | |
val calculatedHash = mac.doFinal(dataCheckString.toByteArray()).joinToString("") { "%02x".format(it) } | |
// Compare the calculated hash with the received hash | |
return calculatedHash == receivedHash | |
} | |
// Example usage | |
fun main() { | |
val botToken = "YOUR_BOT_TOKEN" | |
val initData = "initDataReceivedFromMiniApp" | |
if (checkSignature(botToken, initData)) { | |
println("Data is valid.") | |
} else { | |
println("Data is invalid.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment