Authentication overview
Telegram's MTProto API utilizes a custom-designed protocol that ensures secure communication between client applications and Telegram servers. Unlike many RESTful APIs that might rely on standardized token-based authentication like OAuth 2.0, MTProto implements a low-level cryptographic handshake to establish a secure session. This process involves a Diffie-Hellman key exchange to generate a shared 2048-bit authorization key, which is then used to encrypt all subsequent communication within a session using AES256-IGE. The protocol is designed to be resistant to various attacks, including replay attacks and man-in-the-middle attacks, by incorporating sequence numbers and message acknowledgements.
The core principle is to establish a long-lived authorization key that securely identifies the client and encrypts all traffic. This key is stored persistently by the client application. Each message sent over the MTProto protocol is prefixed with a 64-bit authentication key identifier and a 128-bit message ID, along with a message length, payload, and a SHA-256 hash for integrity verification. This robust structure means developers integrating with MTProto need to handle significant cryptographic details directly, rather than relying on higher-level abstractions typically found in SDKs for other platforms.
Supported authentication methods
MTProto's authentication process is fundamentally a single, multi-step method centered around a secure key exchange. While it doesn't offer multiple distinct authentication schemes in the way a typical web API might (e.g., API keys, OAuth, Basic Auth), the process itself has several critical phases:
| Method | When to use | Security Level |
|---|---|---|
| Diffie-Hellman Key Exchange (Initial Setup) | First-time client connection to a Telegram server or when an existing authorization key is compromised/expired. | High: Establishes a shared secret key over an insecure channel, resistant to passive eavesdropping. |
| Authorization Key (Session Management) | All subsequent API calls after initial key establishment. Used for encrypting and decrypting messages. | High: AES256-IGE encryption provides confidentiality and integrity for all session data. |
| API ID and Hash (Application Registration) | Required for registering a new application with Telegram to obtain necessary client credentials. | Moderate: Identifies the application, but not used directly for message encryption. |
The Diffie-Hellman key exchange is a critical step where the client and server agree on a shared secret key without ever transmitting the key itself over the network. This shared key, known as the authorization key, is then used to encrypt all messages exchanged during the session. Each message includes a header with the authorization key ID, message ID, sequence number, and a SHA-256 hash of the payload to prevent tampering and ensure message order. This low-level approach offers granular control over security but requires careful implementation.
Getting your credentials
To interact with the Telegram MTProto API, you need to register your application to obtain an API ID and an API Hash. These credentials identify your application to Telegram and are essential for initiating the authentication process.
- Register your application: Visit the Telegram API Development Tools page.
- Log in: Use your Telegram phone number to log in. You will receive a login code via the Telegram app.
- Create a new application: Click on "API development tools" and then "Create new application."
- Fill in details: Provide an App title, Short name, URL (optional), Platform (e.g., Android, iOS, Desktop), and a description. The platform selection is primarily for Telegram's internal categorization and does not strictly limit where your application can run.
- Obtain credentials: After submission, you will be presented with your
api_idandapi_hash. These are your application's unique identifiers and secrets. Treat yourapi_hashas a sensitive secret, similar to a password.
These credentials are used during the initial setup of an MTProto session to inform the Telegram servers about the client application attempting to connect. They are distinct from the authorization key, which is generated dynamically per user session.
Authenticated request example
Due to the low-level nature of MTProto, a simple HTTP-based "example request" like those for REST APIs is not directly applicable. Instead, an authenticated request involves constructing a binary message, encrypting it with the established authorization key, and sending it over a TCP connection. The process can be broken down into these conceptual steps:
- Establish TCP connection: Connect to a Telegram data center IP address and port.
- Initiate Diffie-Hellman Key Exchange:
- Send
req_pqto request a public key fingerprint. - Receive
res_pqwith the public key. - Send
req_DH_paramswith client-generated Diffie-Hellman parameters. - Receive
server_DH_params_okorserver_DH_params_fail. - Complete the key exchange to derive the shared
auth_key. - Create an MTProto message: Serialize the desired API method call (e.g.,
users.getFullUser) into a binary payload according to the TL-schema. - Encrypt the message: Use the derived
auth_keyand a randomly generatedmsg_keyto encrypt the binary payload using AES256-IGE. The encryption involves padding and adding a message ID, sequence number, and CRC. - Wrap in MTProto container: Prepend the encrypted payload with the
auth_key_id. - Send over TCP: Transmit the complete binary package over the established TCP connection.
- Receive and decrypt response: Parse the incoming binary response, decrypt it using the same
auth_key, and deserialize the TL-schema response.
Developers typically use community-maintained MTProto libraries like Telethon (Python) or gotd (Go) to abstract away these low-level cryptographic and networking details. For instance, in Python with Telethon, an authenticated request might look like:
from telethon import TelegramClient, events, sync
api_id = 1234567 # Replace with your API ID
api_hash = 'your_api_hash_here' # Replace with your API Hash
client = TelegramClient('session_name', api_id, api_hash)
client.start()
# Example: Get information about the authenticated user
me = client.get_me()
print(me.stringify())
client.run_until_disconnected()
This snippet demonstrates how an SDK handles the underlying MTProto authentication and session management after the initial setup with api_id and api_hash.
Security best practices
Implementing secure authentication with Telegram MTProto requires adherence to cryptographic best practices, especially given the low-level nature of the protocol:
- Protect your API Hash: Your
api_hashis a secret. Never embed it directly in client-side code, commit it to public repositories, or expose it in logs. Use environment variables or secure configuration management systems. - Secure Authorization Keys: The generated
auth_keyis crucial for all subsequent communication. Store it securely and persistently. For client applications, this often means encrypting it on disk using platform-specific secure storage mechanisms (e.g., Android Keystore, iOS Keychain) or OS-level data protection APIs. - Validate Server Public Keys: During the Diffie-Hellman exchange, ensure you validate the server's public key by checking its fingerprint against known, hardcoded values to prevent man-in-the-middle attacks. The official Telegram documentation provides guidance on these fingerprints.
- Handle Nonces and Sequence Numbers: MTProto relies on random nonces and strictly increasing sequence numbers to prevent replay attacks and ensure message ordering. Your implementation must correctly manage these values for each message.
- Use Robust Random Number Generators: Cryptographically secure random number generators are essential for generating nonces and Diffie-Hellman parameters. Avoid using predictable or weak random sources.
- Keep Libraries Updated: If using a community-maintained MTProto library, ensure it is kept up-to-date. Security vulnerabilities or protocol changes are often addressed in new releases.
- Understand the Protocol: While libraries abstract complexity, a fundamental understanding of the MTProto protocol specification is vital for debugging and ensuring correct, secure implementation.
- Error Handling: Implement robust error handling for network issues, cryptographic failures, and server responses to maintain application stability and security.