Last active
September 26, 2024 08:31
-
-
Save ibarchenkov/95a71660efa6d5934d899c51a8a6c4d6 to your computer and use it in GitHub Desktop.
Telegram Bot API Web App initData validation in Elixir
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
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