Skip to content

Instantly share code, notes, and snippets.

@mhrlife
Created June 12, 2024 15:30
Show Gist options
  • Save mhrlife/7c6e04e506e7c9577a16aa0a92566c23 to your computer and use it in GitHub Desktop.
Save mhrlife/7c6e04e506e7c9577a16aa0a92566c23 to your computer and use it in GitHub Desktop.
func validateInitData(inputData, botToken string) (bool, error) {
initData, err := url.ParseQuery(inputData)
if err != nil {
logrus.WithError(err).Errorln("couldn't parse web app input data")
return false, err
}
dataCheckString := make([]string, 0, len(initData))
for k, v := range initData {
if k == "hash" {
continue
}
if len(v) > 0 {
dataCheckString = append(dataCheckString, fmt.Sprintf("%s=%s", k, v[0]))
}
}
sort.Strings(dataCheckString)
secret := hmac.New(sha256.New, []byte("WebAppData"))
secret.Write([]byte(botToken))
hHash := hmac.New(sha256.New, secret.Sum(nil))
hHash.Write([]byte(strings.Join(dataCheckString, "\n")))
hash := hex.EncodeToString(hHash.Sum(nil))
if initData.Get("hash") != hash {
return false, nil
}
return true, nil
}
@Danyalss
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment