Fast and portable cryptography extension library for Pyrogram implementing AES-256-IGE, AES-256-CTR, and AES-256-CBC encryption modes for Telegram's MTProto protocol
npx @tessl/cli install tessl/pypi-tgcrypto@1.2.00
# tgcrypto
1
2
A high-performance cryptography library written in C as a Python extension, specifically designed for Telegram's MTProto protocol. tgcrypto implements three essential AES-256 encryption algorithms required by Telegram: IGE mode for MTProto v2.0, CTR mode for CDN encrypted files, and CBC mode for encrypted passport credentials.
3
4
## Package Information
5
6
- **Package Name**: tgcrypto
7
- **Language**: C/Python
8
- **Installation**: `pip install tgcrypto`
9
- **Platform**: Cross-platform (Windows, macOS, Linux)
10
- **Python Compatibility**: 3.7+ (CPython, PyPy)
11
12
## Core Imports
13
14
```python
15
import tgcrypto
16
```
17
18
## Basic Usage
19
20
```python
21
import os
22
import tgcrypto
23
24
# Generate random key and data
25
key = os.urandom(32) # 32-byte key for AES-256
26
data = os.urandom(64) # Example data (must be multiple of 16 for IGE/CBC)
27
28
# IGE Mode - for MTProto v2.0
29
iv_ige = os.urandom(32) # 32-byte IV for IGE
30
encrypted_ige = tgcrypto.ige256_encrypt(data, key, iv_ige)
31
decrypted_ige = tgcrypto.ige256_decrypt(encrypted_ige, key, iv_ige)
32
33
# CTR Mode - for CDN encrypted files
34
iv_ctr = os.urandom(16) # 16-byte IV for CTR
35
state = bytes([0]) # Counter state (0-15)
36
encrypted_ctr = tgcrypto.ctr256_encrypt(data, key, iv_ctr, state)
37
decrypted_ctr = tgcrypto.ctr256_decrypt(encrypted_ctr, key, iv_ctr, bytes([0]))
38
39
# CBC Mode - for encrypted passport credentials
40
iv_cbc = os.urandom(16) # 16-byte IV for CBC
41
encrypted_cbc = tgcrypto.cbc256_encrypt(data, key, iv_cbc)
42
decrypted_cbc = tgcrypto.cbc256_decrypt(encrypted_cbc, key, iv_cbc)
43
44
print(data == decrypted_ige) # True
45
print(data == decrypted_ctr) # True
46
print(data == decrypted_cbc) # True
47
```
48
49
## Architecture
50
51
tgcrypto is designed for maximum performance and portability:
52
53
- **C Implementation**: Core algorithms implemented in optimized C code
54
- **Python Extension**: Seamless integration with Python through the C API
55
- **Zero Dependencies**: No external dependencies beyond Python standard library
56
- **Thread Safety**: Releases GIL during encryption/decryption for concurrent operations
57
- **Memory Efficient**: Direct buffer operations without unnecessary copying
58
59
## Capabilities
60
61
### IGE Mode (AES-256-IGE)
62
63
AES-256 in Infinite Garble Extension mode, used specifically for Telegram's MTProto v2.0 protocol. IGE provides enhanced security properties compared to standard CBC mode.
64
65
```python { .api }
66
def ige256_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
67
"""
68
Encrypt data using AES-256-IGE mode.
69
70
Parameters:
71
- data: Input data to encrypt (must be multiple of 16 bytes)
72
- key: 32-byte encryption key
73
- iv: 32-byte initialization vector
74
75
Returns:
76
bytes: Encrypted data
77
78
Raises:
79
ValueError: If data is empty, not multiple of 16 bytes, key not 32 bytes, or IV not 32 bytes
80
TypeError: If arguments are not bytes-like objects
81
"""
82
83
def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
84
"""
85
Decrypt data using AES-256-IGE mode.
86
87
Parameters:
88
- data: Input data to decrypt (must be multiple of 16 bytes)
89
- key: 32-byte decryption key
90
- iv: 32-byte initialization vector
91
92
Returns:
93
bytes: Decrypted data
94
95
Raises:
96
ValueError: If data is empty, not multiple of 16 bytes, key not 32 bytes, or IV not 32 bytes
97
TypeError: If arguments are not bytes-like objects
98
"""
99
```
100
101
**Usage Example:**
102
103
```python
104
import os
105
import tgcrypto
106
107
# IGE requires data to be multiple of 16 bytes
108
data = os.urandom(1024) # Already multiple of 16
109
key = os.urandom(32)
110
iv = os.urandom(32)
111
112
# For data that's not a multiple of 16, add padding
113
data_with_padding = data + bytes(-len(data) % 16)
114
115
encrypted = tgcrypto.ige256_encrypt(data_with_padding, key, iv)
116
decrypted = tgcrypto.ige256_decrypt(encrypted, key, iv)
117
118
print(data_with_padding == decrypted) # True
119
```
120
121
### CTR Mode (AES-256-CTR)
122
123
AES-256 in Counter mode, used for CDN encrypted file downloads in Telegram. CTR mode provides streaming encryption capabilities and doesn't require padding.
124
125
```python { .api }
126
def ctr256_encrypt(data: bytes, key: bytes, iv: bytes, state: bytes) -> bytes:
127
"""
128
Encrypt data using AES-256-CTR mode.
129
130
Parameters:
131
- data: Input data to encrypt (any length)
132
- key: 32-byte encryption key
133
- iv: 16-byte initialization vector (modified during operation)
134
- state: 1-byte counter state (value 0-15)
135
136
Returns:
137
bytes: Encrypted data
138
139
Raises:
140
ValueError: If data is empty, key not 32 bytes, IV not 16 bytes, state not 1 byte, or state value > 15
141
TypeError: If arguments are not bytes-like objects
142
"""
143
144
def ctr256_decrypt(data: bytes, key: bytes, iv: bytes, state: bytes) -> bytes:
145
"""
146
Decrypt data using AES-256-CTR mode.
147
148
Parameters:
149
- data: Input data to decrypt (any length)
150
- key: 32-byte decryption key
151
- iv: 16-byte initialization vector (modified during operation)
152
- state: 1-byte counter state (value 0-15)
153
154
Returns:
155
bytes: Decrypted data
156
157
Raises:
158
ValueError: If data is empty, key not 32 bytes, IV not 16 bytes, state not 1 byte, or state value > 15
159
TypeError: If arguments are not bytes-like objects
160
"""
161
```
162
163
**Single Chunk Usage:**
164
165
```python
166
import os
167
import tgcrypto
168
169
data = os.urandom(10 * 1024 * 1024) # 10 MB of data
170
key = os.urandom(32)
171
172
# Use bytearray for IV since it gets modified
173
enc_iv = bytearray(os.urandom(16))
174
dec_iv = enc_iv.copy()
175
176
encrypted = tgcrypto.ctr256_encrypt(data, key, enc_iv, bytes([0]))
177
decrypted = tgcrypto.ctr256_decrypt(encrypted, key, dec_iv, bytes([0]))
178
179
print(data == decrypted) # True
180
```
181
182
**Streaming Usage:**
183
184
```python
185
import os
186
from io import BytesIO
187
import tgcrypto
188
189
# Setup
190
data = BytesIO(os.urandom(10 * 1024 * 1024))
191
key = os.urandom(32)
192
enc_iv = bytearray(os.urandom(16))
193
dec_iv = enc_iv.copy()
194
enc_state = bytes([0])
195
dec_state = bytes([0])
196
197
encrypted_buffer = BytesIO()
198
decrypted_buffer = BytesIO()
199
200
# Encrypt in chunks
201
while True:
202
chunk = data.read(1024)
203
if not chunk:
204
break
205
encrypted_buffer.write(tgcrypto.ctr256_encrypt(chunk, key, enc_iv, enc_state))
206
207
# Decrypt in chunks
208
encrypted_buffer.seek(0)
209
while True:
210
chunk = encrypted_buffer.read(1024)
211
if not chunk:
212
break
213
decrypted_buffer.write(tgcrypto.ctr256_decrypt(chunk, key, dec_iv, dec_state))
214
215
print(data.getvalue() == decrypted_buffer.getvalue()) # True
216
```
217
218
### CBC Mode (AES-256-CBC)
219
220
AES-256 in Cipher Block Chaining mode, used for encrypting passport credentials in Telegram. CBC provides strong security with proper IV handling.
221
222
```python { .api }
223
def cbc256_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
224
"""
225
Encrypt data using AES-256-CBC mode.
226
227
Parameters:
228
- data: Input data to encrypt (must be multiple of 16 bytes)
229
- key: 32-byte encryption key
230
- iv: 16-byte initialization vector
231
232
Returns:
233
bytes: Encrypted data
234
235
Raises:
236
ValueError: If data is empty, not multiple of 16 bytes, key not 32 bytes, or IV not 16 bytes
237
TypeError: If arguments are not bytes-like objects
238
"""
239
240
def cbc256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
241
"""
242
Decrypt data using AES-256-CBC mode.
243
244
Parameters:
245
- data: Input data to decrypt (must be multiple of 16 bytes)
246
- key: 32-byte decryption key
247
- iv: 16-byte initialization vector
248
249
Returns:
250
bytes: Decrypted data
251
252
Raises:
253
ValueError: If data is empty, not multiple of 16 bytes, key not 32 bytes, or IV not 16 bytes
254
TypeError: If arguments are not bytes-like objects
255
"""
256
```
257
258
**Usage Example:**
259
260
```python
261
import os
262
import tgcrypto
263
264
# CBC requires data to be multiple of 16 bytes
265
data = os.urandom(1024 + 7) # Add 7 bytes to demonstrate padding
266
key = os.urandom(32)
267
268
# Separate IVs for encryption and decryption
269
enc_iv = bytearray(os.urandom(16))
270
dec_iv = enc_iv.copy()
271
272
# Pad data to multiple of 16 bytes
273
padded_data = data + bytes(-len(data) % 16)
274
275
encrypted = tgcrypto.cbc256_encrypt(padded_data, key, enc_iv)
276
decrypted = tgcrypto.cbc256_decrypt(encrypted, key, dec_iv)
277
278
print(padded_data == decrypted) # True
279
```
280
281
## Error Handling
282
283
All functions perform comprehensive input validation and raise specific exceptions:
284
285
**Common Errors:**
286
287
- `ValueError`: Input validation failures (empty data, wrong sizes, invalid state values)
288
- `TypeError`: Non-bytes arguments passed to functions
289
290
**Validation Rules:**
291
292
- **Data**: Must not be empty; IGE/CBC require multiples of 16 bytes
293
- **Key**: Must be exactly 32 bytes for all modes
294
- **IV**: Must be 32 bytes for IGE, 16 bytes for CTR/CBC
295
- **State** (CTR only): Must be 1 byte with value 0-15
296
297
**Error Handling Example:**
298
299
```python
300
import tgcrypto
301
302
try:
303
# This will raise ValueError: Data size must match a multiple of 16 bytes
304
tgcrypto.ige256_encrypt(b"hello", b"x" * 32, b"y" * 32)
305
except ValueError as e:
306
print(f"Validation error: {e}")
307
308
try:
309
# This will raise ValueError: Key size must be exactly 32 bytes
310
tgcrypto.ctr256_encrypt(b"hello", b"short", b"x" * 16, bytes([0]))
311
except ValueError as e:
312
print(f"Key size error: {e}")
313
```
314
315
## Performance Considerations
316
317
- **Thread Safety**: All functions release the Python GIL during computation
318
- **Memory Efficiency**: Direct buffer operations minimize memory allocation
319
- **Optimized C Code**: Hand-optimized AES implementation for maximum performance
320
- **No Dependencies**: Zero external dependencies reduce attack surface and improve portability
321
322
## Telegram Integration
323
324
tgcrypto is specifically designed for Telegram's cryptographic requirements:
325
326
- **MTProto v2.0**: Uses IGE mode for message encryption
327
- **CDN Files**: Uses CTR mode for streaming file downloads
328
- **Passport**: Uses CBC mode for credential encryption
329
330
The library ensures compatibility with Telegram's exact specifications while providing optimal performance for bot development and MTProto implementations.