Skip to content

Instantly share code, notes, and snippets.

@ibarchenkov
Last active July 8, 2022 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibarchenkov/95a71660efa6d5934d899c51a8a6c4d6 to your computer and use it in GitHub Desktop.
Save ibarchenkov/95a71660efa6d5934d899c51a8a6c4d6 to your computer and use it in GitHub Desktop.
Telegram Bot API Web App initData validation in Elixir
def validate_web_app_init_data(tg_init_data, bot_api_token) do
{received_hash, decoded_map} =
tg_init_data
|> URI.decode_query()
|> Map.pop!("hash")
data_check_string =
decoded_map
|> Enum.sort(fn {k1, _v1}, {k2, _v2} -> k1 <= k2 end)
|> Enum.map_join("\n", fn {k, v} -> "#{k}=#{v}" end)
calculated_hash =
"WebAppData"
|> hmac(bot_api_token)
|> hmac(data_check_string)
|> Base.encode16(case: :lower)
if received_hash == calculated_hash do
{:ok, decoded_map}
else
:error
end
end
def hmac(key, data) do
:crypto.mac(:hmac, :sha256, key, data)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment