pygram-org 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pygram/__init__.py +15 -0
- pygram/client.py +318 -0
- pygram/connection/__init__.py +3 -0
- pygram/connection/transport.py +57 -0
- pygram/crypto/__init__.py +8 -0
- pygram/crypto/aes.py +40 -0
- pygram/crypto/kdf.py +24 -0
- pygram/crypto/prime.py +61 -0
- pygram/crypto/rsa.py +166 -0
- pygram/crypto/srp.py +54 -0
- pygram/errors.py +52 -0
- pygram/media.py +66 -0
- pygram/methods.py +221 -0
- pygram/raw/__init__.py +87 -0
- pygram/raw/schema.tl +2407 -0
- pygram/raw/tl.py +401 -0
- pygram/session/__init__.py +5 -0
- pygram/session/auth.py +166 -0
- pygram/session/ids.py +30 -0
- pygram/session/session.py +235 -0
- pygram/storage/__init__.py +5 -0
- pygram/storage/encrypted.py +89 -0
- pygram/storage/storage.py +69 -0
- pygram/types.py +305 -0
- pygram/updates.py +135 -0
- pygram_org-0.1.0.dist-info/METADATA +137 -0
- pygram_org-0.1.0.dist-info/RECORD +31 -0
- pygram_org-0.1.0.dist-info/WHEEL +5 -0
- pygram_org-0.1.0.dist-info/licenses/COPYING +674 -0
- pygram_org-0.1.0.dist-info/licenses/COPYING.lesser +165 -0
- pygram_org-0.1.0.dist-info/top_level.txt +1 -0
pygram/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Pygram - an unofficial Telegram MTProto client library for Python."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
__author__ = "Shamil Habeeb Nelli"
|
|
5
|
+
|
|
6
|
+
LAYER = 225 # the TL schema layer in pygram/raw/schema.tl
|
|
7
|
+
|
|
8
|
+
from .client import Client # noqa: E402
|
|
9
|
+
from .types import (Audio, CallbackQuery, Chat, Document, InlineKeyboardButton, # noqa: E402
|
|
10
|
+
InlineKeyboardMarkup, Location, Message, MessageEntity, Photo, PhotoSize,
|
|
11
|
+
Update, User, Video, Voice)
|
|
12
|
+
|
|
13
|
+
__all__ = ["Client", "LAYER", "__version__", "User", "Chat", "Message", "MessageEntity", "Photo",
|
|
14
|
+
"PhotoSize", "Document", "Video", "Audio", "Voice", "Location", "InlineKeyboardButton",
|
|
15
|
+
"InlineKeyboardMarkup", "CallbackQuery", "Update"]
|
pygram/client.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""The high-level client: connect, log in, call methods, receive updates."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import inspect
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
from typing import Any, Awaitable, Callable, List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
from . import LAYER, __version__
|
|
11
|
+
from .connection import Transport
|
|
12
|
+
from .crypto.srp import compute_check
|
|
13
|
+
from .errors import ConnectionLost, FloodWait, PygramError, RPCError
|
|
14
|
+
from .methods import Methods
|
|
15
|
+
from .raw import functions, types
|
|
16
|
+
from .session import MsgIds, Session, authorize
|
|
17
|
+
from .storage import EncryptedStorage, FileStorage, MemoryStorage, Storage
|
|
18
|
+
from .updates import UpdateTracker, get_difference
|
|
19
|
+
|
|
20
|
+
DC_ADDRESSES = {
|
|
21
|
+
1: ("149.154.175.53", 443),
|
|
22
|
+
2: ("149.154.167.50", 443),
|
|
23
|
+
3: ("149.154.175.100", 443),
|
|
24
|
+
4: ("149.154.167.91", 443),
|
|
25
|
+
5: ("91.108.56.128", 443),
|
|
26
|
+
}
|
|
27
|
+
TEST_DC_ADDRESSES = {1: ("149.154.175.10", 443), 2: ("149.154.167.40", 443), 3: ("149.154.175.117", 443)}
|
|
28
|
+
|
|
29
|
+
Handler = Callable[[Any], Any]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Client(Methods):
|
|
33
|
+
"""A Telegram client, in the style of ``pyrogram.Client``::
|
|
34
|
+
|
|
35
|
+
app = Client("me", api_id=1, api_hash="...")
|
|
36
|
+
async with app:
|
|
37
|
+
await app.send_message("me", "hi")
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, name: str, api_id: int = 0, api_hash: str = "", *, bot_token: Optional[str] = None,
|
|
41
|
+
phone_number: Optional[str] = None, workdir: str = ".", in_memory: bool = False,
|
|
42
|
+
test_mode: bool = False, sleep_threshold: int = 10, max_retries: int = 3,
|
|
43
|
+
server: Optional[Tuple[str, int]] = None, storage: Optional[Storage] = None,
|
|
44
|
+
passphrase: str = "",
|
|
45
|
+
device_model: str = "", system_version: str = "", app_version: str = "",
|
|
46
|
+
lang_code: str = "en", keys=None):
|
|
47
|
+
self.name = name
|
|
48
|
+
self.api_id = api_id
|
|
49
|
+
self.api_hash = api_hash
|
|
50
|
+
self.bot_token = bot_token
|
|
51
|
+
self.phone_number = phone_number
|
|
52
|
+
self.test_mode = test_mode
|
|
53
|
+
self.sleep_threshold = sleep_threshold
|
|
54
|
+
self.max_retries = max_retries
|
|
55
|
+
self.server = server # overrides the address of every DC, for tests and proxies
|
|
56
|
+
if storage is None:
|
|
57
|
+
if in_memory:
|
|
58
|
+
storage = MemoryStorage()
|
|
59
|
+
elif passphrase:
|
|
60
|
+
storage = EncryptedStorage(name, workdir, passphrase)
|
|
61
|
+
else:
|
|
62
|
+
storage = FileStorage(name, workdir)
|
|
63
|
+
self.storage = storage
|
|
64
|
+
self.device_model = device_model or platform.node() or "Pygram"
|
|
65
|
+
self.system_version = system_version or f"{platform.system()} {platform.release()}"
|
|
66
|
+
self.app_version = app_version or f"Pygram {__version__}"
|
|
67
|
+
self.lang_code = lang_code
|
|
68
|
+
self.keys = keys
|
|
69
|
+
self.session: Optional[Session] = None
|
|
70
|
+
self.dc_id = 0
|
|
71
|
+
self.me: Optional[types.User] = None
|
|
72
|
+
self._handlers: List[Tuple[Handler, Optional[Callable[[Any], bool]]]] = []
|
|
73
|
+
self._initialised = False
|
|
74
|
+
self._lock = asyncio.Lock()
|
|
75
|
+
self._tasks: set = set()
|
|
76
|
+
self.update_tracker = UpdateTracker(self.storage)
|
|
77
|
+
self._recovering = False
|
|
78
|
+
|
|
79
|
+
# ---- connection ----
|
|
80
|
+
|
|
81
|
+
def _address(self, dc_id: int) -> Tuple[str, int]:
|
|
82
|
+
if self.server:
|
|
83
|
+
return self.server
|
|
84
|
+
return (TEST_DC_ADDRESSES if self.test_mode else DC_ADDRESSES)[dc_id]
|
|
85
|
+
|
|
86
|
+
async def connect(self, dc_id: Optional[int] = None) -> None:
|
|
87
|
+
"""Open a session on a DC (the stored one, else DC 2), creating the auth key if needed."""
|
|
88
|
+
dc_id = dc_id or self.storage.get("dc_id") or 2
|
|
89
|
+
if self.session is not None:
|
|
90
|
+
await self.session.close()
|
|
91
|
+
host, port = self._address(dc_id)
|
|
92
|
+
key = self.storage.get("auth_key") if self.storage.get("dc_id") == dc_id else None
|
|
93
|
+
if key:
|
|
94
|
+
t = await Transport.connect(host, port)
|
|
95
|
+
ids = MsgIds()
|
|
96
|
+
self.session = Session(t, key, 0, ids, self._on_raw_update)
|
|
97
|
+
else:
|
|
98
|
+
t, ids, res = await authorize(host, port, dc_id, keys=self.keys)
|
|
99
|
+
self.storage.set("dc_id", dc_id)
|
|
100
|
+
self.storage.set("auth_key", res.key)
|
|
101
|
+
self.session = Session(t, res.key, res.salt, ids, self._on_raw_update)
|
|
102
|
+
self.dc_id = dc_id
|
|
103
|
+
self._initialised = False
|
|
104
|
+
self.session.start()
|
|
105
|
+
|
|
106
|
+
async def disconnect(self) -> None:
|
|
107
|
+
for t in list(self._tasks):
|
|
108
|
+
t.cancel()
|
|
109
|
+
if self.session:
|
|
110
|
+
await self.session.close()
|
|
111
|
+
self.session = None
|
|
112
|
+
|
|
113
|
+
# ---- raw calls ----
|
|
114
|
+
|
|
115
|
+
async def invoke(self, request, retries: Optional[int] = None, timeout: float = 30.0):
|
|
116
|
+
"""Call a raw method. Handles FLOOD_WAIT (short ones), DC migration and reconnects."""
|
|
117
|
+
if self.session is None:
|
|
118
|
+
raise PygramError("the client is not connected")
|
|
119
|
+
tries = self.max_retries if retries is None else retries
|
|
120
|
+
while True:
|
|
121
|
+
try:
|
|
122
|
+
return await self._invoke_once(request, timeout)
|
|
123
|
+
except FloodWait as e:
|
|
124
|
+
if e.seconds > self.sleep_threshold or tries <= 0:
|
|
125
|
+
raise
|
|
126
|
+
await asyncio.sleep(e.seconds + 1)
|
|
127
|
+
except RPCError as e:
|
|
128
|
+
if e.message.startswith(("PHONE_MIGRATE_", "NETWORK_MIGRATE_", "USER_MIGRATE_")) and e.value and tries > 0:
|
|
129
|
+
self.storage.delete("auth_key")
|
|
130
|
+
await self.connect(e.value)
|
|
131
|
+
elif e.code >= 500 and tries > 0:
|
|
132
|
+
await asyncio.sleep(0.5)
|
|
133
|
+
else:
|
|
134
|
+
raise
|
|
135
|
+
except (ConnectionLost, asyncio.TimeoutError):
|
|
136
|
+
if tries <= 0:
|
|
137
|
+
raise
|
|
138
|
+
await self.connect(self.dc_id)
|
|
139
|
+
tries -= 1
|
|
140
|
+
|
|
141
|
+
async def _invoke_once(self, request, timeout):
|
|
142
|
+
if self.session is None or self.session.error:
|
|
143
|
+
await self.connect(self.dc_id or None)
|
|
144
|
+
if not self._initialised:
|
|
145
|
+
self._initialised = True
|
|
146
|
+
request = functions.InvokeWithLayer(layer=LAYER, query=functions.InitConnection(
|
|
147
|
+
api_id=self.api_id, device_model=self.device_model, system_version=self.system_version,
|
|
148
|
+
app_version=self.app_version, system_lang_code=self.lang_code, lang_pack="",
|
|
149
|
+
lang_code=self.lang_code, query=request))
|
|
150
|
+
try:
|
|
151
|
+
return await self.session.invoke(request, timeout)
|
|
152
|
+
except BaseException:
|
|
153
|
+
if not isinstance(request, functions.InvokeWithLayer):
|
|
154
|
+
raise
|
|
155
|
+
self._initialised = False
|
|
156
|
+
raise
|
|
157
|
+
|
|
158
|
+
# ---- login ----
|
|
159
|
+
|
|
160
|
+
async def send_code(self, phone_number: str):
|
|
161
|
+
"""Ask Telegram to send a login code. Returns the ``auth.SentCode``."""
|
|
162
|
+
self.phone_number = phone_number
|
|
163
|
+
return await self.invoke(functions.auth.SendCode(
|
|
164
|
+
phone_number=phone_number, api_id=self.api_id, api_hash=self.api_hash,
|
|
165
|
+
settings=types.CodeSettings()))
|
|
166
|
+
|
|
167
|
+
async def sign_in(self, phone_number: str, phone_code_hash: str, phone_code: str):
|
|
168
|
+
r = await self.invoke(functions.auth.SignIn(
|
|
169
|
+
phone_number=phone_number, phone_code_hash=phone_code_hash, phone_code=phone_code))
|
|
170
|
+
return self._signed_in(r)
|
|
171
|
+
|
|
172
|
+
async def check_password(self, password: str):
|
|
173
|
+
"""Finish a login that answered SESSION_PASSWORD_NEEDED."""
|
|
174
|
+
pw = await self.invoke(functions.account.GetPassword())
|
|
175
|
+
if not isinstance(pw.current_algo, types.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow):
|
|
176
|
+
raise PygramError("unsupported password algorithm")
|
|
177
|
+
srp_id, a, m1 = compute_check(pw.current_algo, pw.srp_B, pw.srp_id, password)
|
|
178
|
+
r = await self.invoke(functions.auth.CheckPassword(
|
|
179
|
+
password=types.InputCheckPasswordSRP(srp_id=srp_id, A=a, M1=m1)))
|
|
180
|
+
return self._signed_in(r)
|
|
181
|
+
|
|
182
|
+
async def sign_in_bot(self, bot_token: str):
|
|
183
|
+
r = await self.invoke(functions.auth.ImportBotAuthorization(
|
|
184
|
+
flags=0, api_id=self.api_id, api_hash=self.api_hash, bot_auth_token=bot_token))
|
|
185
|
+
return self._signed_in(r)
|
|
186
|
+
|
|
187
|
+
def _signed_in(self, r):
|
|
188
|
+
if isinstance(r, types.auth.AuthorizationSignUpRequired):
|
|
189
|
+
raise PygramError("this phone number is not registered; sign up in an official app first")
|
|
190
|
+
user = r.user
|
|
191
|
+
self.me = user
|
|
192
|
+
self.storage.set("user_id", user.id)
|
|
193
|
+
self.storage.set("is_bot", bool(getattr(user, "bot", False)))
|
|
194
|
+
return user
|
|
195
|
+
|
|
196
|
+
async def start(self, code_callback: Optional[Callable[[], Any]] = None,
|
|
197
|
+
password_callback: Optional[Callable[[], Any]] = None) -> "Client":
|
|
198
|
+
"""Connect and make sure the account is logged in.
|
|
199
|
+
|
|
200
|
+
Uses the stored session when valid, else ``bot_token`` or ``phone_number`` with the callbacks
|
|
201
|
+
(default: ask on the terminal).
|
|
202
|
+
"""
|
|
203
|
+
await self.connect()
|
|
204
|
+
if self.storage.get("user_id"):
|
|
205
|
+
try:
|
|
206
|
+
self.me = (await self.invoke(functions.users.GetUsers(id=[types.InputUserSelf()])))[0]
|
|
207
|
+
return self
|
|
208
|
+
except RPCError as e:
|
|
209
|
+
if e.message not in ("AUTH_KEY_UNREGISTERED", "SESSION_REVOKED", "USER_DEACTIVATED"):
|
|
210
|
+
raise
|
|
211
|
+
self.storage.clear()
|
|
212
|
+
await self.connect()
|
|
213
|
+
if self.bot_token:
|
|
214
|
+
await self.sign_in_bot(self.bot_token)
|
|
215
|
+
return self
|
|
216
|
+
phone = self.phone_number or await _ask(None, "Phone number: ")
|
|
217
|
+
sent = await self.send_code(phone)
|
|
218
|
+
code = await _ask(code_callback, "Login code: ")
|
|
219
|
+
try:
|
|
220
|
+
await self.sign_in(phone, sent.phone_code_hash, code)
|
|
221
|
+
except RPCError as e:
|
|
222
|
+
if e.message != "SESSION_PASSWORD_NEEDED":
|
|
223
|
+
raise
|
|
224
|
+
await self.check_password(await _ask(password_callback, "Two-step password: "))
|
|
225
|
+
return self
|
|
226
|
+
|
|
227
|
+
async def stop(self) -> None:
|
|
228
|
+
await self.disconnect()
|
|
229
|
+
self.storage.close()
|
|
230
|
+
|
|
231
|
+
async def __aenter__(self):
|
|
232
|
+
return await self.start()
|
|
233
|
+
|
|
234
|
+
async def __aexit__(self, *exc):
|
|
235
|
+
await self.stop()
|
|
236
|
+
|
|
237
|
+
# ---- high-level methods (the full set is built on top of invoke) ----
|
|
238
|
+
|
|
239
|
+
async def resolve_peer(self, chat_id):
|
|
240
|
+
if not isinstance(chat_id, (int, str)):
|
|
241
|
+
return chat_id # already an InputPeer
|
|
242
|
+
if chat_id in ("me", "self"):
|
|
243
|
+
return types.InputPeerSelf()
|
|
244
|
+
if isinstance(chat_id, str):
|
|
245
|
+
r = await self.invoke(functions.contacts.ResolveUsername(username=chat_id.lstrip("@")))
|
|
246
|
+
for u in r.users:
|
|
247
|
+
if u.id == getattr(r.peer, "user_id", None):
|
|
248
|
+
return types.InputPeerUser(user_id=u.id, access_hash=u.access_hash)
|
|
249
|
+
for c in r.chats:
|
|
250
|
+
if c.id == getattr(r.peer, "channel_id", None):
|
|
251
|
+
return types.InputPeerChannel(channel_id=c.id, access_hash=c.access_hash)
|
|
252
|
+
if c.id == getattr(r.peer, "chat_id", None):
|
|
253
|
+
return types.InputPeerChat(chat_id=c.id)
|
|
254
|
+
raise PygramError(f"cannot resolve {chat_id!r}")
|
|
255
|
+
if chat_id == self.storage.get("user_id"):
|
|
256
|
+
return types.InputPeerSelf()
|
|
257
|
+
if chat_id < 0:
|
|
258
|
+
return types.InputPeerChat(chat_id=-chat_id)
|
|
259
|
+
raise PygramError("a bare user id needs an access hash; pass a username or an InputPeer")
|
|
260
|
+
|
|
261
|
+
# ---- updates ----
|
|
262
|
+
|
|
263
|
+
def add_handler(self, callback: Handler, predicate: Optional[Callable[[Any], bool]] = None) -> Handler:
|
|
264
|
+
"""Call ``callback(update)`` for each raw update that passes ``predicate``."""
|
|
265
|
+
self._handlers.append((callback, predicate))
|
|
266
|
+
return callback
|
|
267
|
+
|
|
268
|
+
def on_update(self, predicate: Optional[Callable[[Any], bool]] = None):
|
|
269
|
+
"""Decorator form of add_handler."""
|
|
270
|
+
def deco(fn):
|
|
271
|
+
return self.add_handler(fn, predicate)
|
|
272
|
+
return deco
|
|
273
|
+
|
|
274
|
+
async def _on_raw_update(self, obj) -> None:
|
|
275
|
+
if self.update_tracker.feed(obj) and self.me is not None:
|
|
276
|
+
self._schedule_recovery()
|
|
277
|
+
await self._dispatch(obj)
|
|
278
|
+
|
|
279
|
+
async def _dispatch(self, obj) -> None:
|
|
280
|
+
for cb, pred in list(self._handlers):
|
|
281
|
+
if pred is not None and not pred(obj):
|
|
282
|
+
continue
|
|
283
|
+
t = asyncio.get_running_loop().create_task(_call(cb, obj))
|
|
284
|
+
self._tasks.add(t)
|
|
285
|
+
t.add_done_callback(self._tasks.discard)
|
|
286
|
+
|
|
287
|
+
def _schedule_recovery(self) -> None:
|
|
288
|
+
if self._recovering:
|
|
289
|
+
return
|
|
290
|
+
self._recovering = True
|
|
291
|
+
|
|
292
|
+
async def run():
|
|
293
|
+
try:
|
|
294
|
+
await self.recover_updates()
|
|
295
|
+
finally:
|
|
296
|
+
self._recovering = False
|
|
297
|
+
|
|
298
|
+
t = asyncio.get_running_loop().create_task(run())
|
|
299
|
+
self._tasks.add(t)
|
|
300
|
+
t.add_done_callback(self._tasks.discard)
|
|
301
|
+
|
|
302
|
+
async def recover_updates(self) -> int:
|
|
303
|
+
"""Fetch and replay missed updates with ``updates.getDifference``."""
|
|
304
|
+
async with self._lock:
|
|
305
|
+
return await get_difference(self)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
async def _call(cb, obj):
|
|
309
|
+
r = cb(obj)
|
|
310
|
+
if inspect.isawaitable(r):
|
|
311
|
+
await r
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
async def _ask(cb, prompt: str):
|
|
315
|
+
if cb is None:
|
|
316
|
+
return await asyncio.get_running_loop().run_in_executor(None, input, prompt)
|
|
317
|
+
r = cb()
|
|
318
|
+
return await r if inspect.isawaitable(r) else r
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""TCP transport with MTProto's "intermediate" framing."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import struct
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from ..errors import ConnectionLost, TransportError
|
|
9
|
+
|
|
10
|
+
INIT = b"\xee\xee\xee\xee"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Transport:
|
|
14
|
+
"""A framed connection. Every packet is a 4 byte little-endian length and the payload."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
|
17
|
+
self._r = reader
|
|
18
|
+
self._w = writer
|
|
19
|
+
self._lock = asyncio.Lock()
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
async def connect(cls, host: str, port: int, timeout: float = 10.0) -> "Transport":
|
|
23
|
+
try:
|
|
24
|
+
r, w = await asyncio.wait_for(asyncio.open_connection(host, port), timeout)
|
|
25
|
+
except (OSError, asyncio.TimeoutError) as e:
|
|
26
|
+
raise ConnectionLost(f"cannot connect to {host}:{port}: {e}") from e
|
|
27
|
+
w.write(INIT)
|
|
28
|
+
await w.drain()
|
|
29
|
+
return cls(r, w)
|
|
30
|
+
|
|
31
|
+
async def send(self, payload: bytes) -> None:
|
|
32
|
+
async with self._lock:
|
|
33
|
+
try:
|
|
34
|
+
self._w.write(struct.pack("<I", len(payload)) + payload)
|
|
35
|
+
await self._w.drain()
|
|
36
|
+
except (OSError, ConnectionError) as e:
|
|
37
|
+
raise ConnectionLost(str(e)) from e
|
|
38
|
+
|
|
39
|
+
async def recv(self) -> bytes:
|
|
40
|
+
try:
|
|
41
|
+
head = await self._r.readexactly(4)
|
|
42
|
+
n = struct.unpack("<I", head)[0]
|
|
43
|
+
if n == 4: # a bare error code, e.g. -404 for an unknown auth key
|
|
44
|
+
code = struct.unpack("<i", await self._r.readexactly(4))[0]
|
|
45
|
+
raise TransportError(code)
|
|
46
|
+
if n > 16 * 1024 * 1024:
|
|
47
|
+
raise ConnectionLost(f"absurd frame length {n}")
|
|
48
|
+
return await self._r.readexactly(n)
|
|
49
|
+
except (asyncio.IncompleteReadError, OSError, ConnectionError) as e:
|
|
50
|
+
raise ConnectionLost("connection closed") from e
|
|
51
|
+
|
|
52
|
+
async def close(self) -> None:
|
|
53
|
+
try:
|
|
54
|
+
self._w.close()
|
|
55
|
+
await self._w.wait_closed()
|
|
56
|
+
except Exception:
|
|
57
|
+
pass
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Cryptographic building blocks of MTProto."""
|
|
2
|
+
from .aes import ige_decrypt, ige_encrypt
|
|
3
|
+
from .kdf import kdf_v2, sha1, sha256
|
|
4
|
+
from .prime import factorize
|
|
5
|
+
from .rsa import ServerKey, load_server_keys, rsa_encrypt_legacy, rsa_pad
|
|
6
|
+
|
|
7
|
+
__all__ = ["ige_encrypt", "ige_decrypt", "sha1", "sha256", "kdf_v2", "factorize",
|
|
8
|
+
"ServerKey", "load_server_keys", "rsa_pad", "rsa_encrypt_legacy"]
|
pygram/crypto/aes.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""AES-256 in IGE mode (infinite garble extension), as MTProto uses it."""
|
|
2
|
+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _ecb(key: bytes, encrypt: bool):
|
|
6
|
+
c = Cipher(algorithms.AES(key), modes.ECB())
|
|
7
|
+
return c.encryptor() if encrypt else c.decryptor()
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _check(key: bytes, iv: bytes, data: bytes) -> None:
|
|
11
|
+
if len(key) != 32 or len(iv) != 32:
|
|
12
|
+
raise ValueError("IGE needs a 32 byte key and a 32 byte iv")
|
|
13
|
+
if len(data) % 16:
|
|
14
|
+
raise ValueError("IGE data must be a multiple of 16 bytes")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def ige_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
|
|
18
|
+
_check(key, iv, data)
|
|
19
|
+
ecb = _ecb(key, True)
|
|
20
|
+
y_prev, x_prev = iv[:16], iv[16:]
|
|
21
|
+
out = bytearray()
|
|
22
|
+
for i in range(0, len(data), 16):
|
|
23
|
+
x = data[i:i + 16]
|
|
24
|
+
y = bytes(a ^ b for a, b in zip(ecb.update(bytes(a ^ b for a, b in zip(x, y_prev))), x_prev))
|
|
25
|
+
out += y
|
|
26
|
+
y_prev, x_prev = y, x
|
|
27
|
+
return bytes(out)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def ige_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
|
|
31
|
+
_check(key, iv, data)
|
|
32
|
+
ecb = _ecb(key, False)
|
|
33
|
+
y_prev, x_prev = iv[:16], iv[16:]
|
|
34
|
+
out = bytearray()
|
|
35
|
+
for i in range(0, len(data), 16):
|
|
36
|
+
y = data[i:i + 16]
|
|
37
|
+
x = bytes(a ^ b for a, b in zip(ecb.update(bytes(a ^ b for a, b in zip(y, x_prev))), y_prev))
|
|
38
|
+
out += x
|
|
39
|
+
y_prev, x_prev = y, x
|
|
40
|
+
return bytes(out)
|
pygram/crypto/kdf.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Hashes and the MTProto 2.0 key derivation."""
|
|
2
|
+
import hashlib
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def sha1(*parts: bytes) -> bytes:
|
|
6
|
+
h = hashlib.sha1()
|
|
7
|
+
for p in parts:
|
|
8
|
+
h.update(p)
|
|
9
|
+
return h.digest()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def sha256(*parts: bytes) -> bytes:
|
|
13
|
+
h = hashlib.sha256()
|
|
14
|
+
for p in parts:
|
|
15
|
+
h.update(p)
|
|
16
|
+
return h.digest()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def kdf_v2(auth_key: bytes, msg_key: bytes, outgoing: bool) -> tuple[bytes, bytes]:
|
|
20
|
+
"""Return (aes_key, aes_iv). ``outgoing`` is client to server (x = 0), else x = 8."""
|
|
21
|
+
x = 0 if outgoing else 8
|
|
22
|
+
a = sha256(msg_key, auth_key[x:x + 36])
|
|
23
|
+
b = sha256(auth_key[40 + x:76 + x], msg_key)
|
|
24
|
+
return a[0:8] + b[8:24] + a[24:32], b[0:8] + a[8:24] + b[24:32]
|
pygram/crypto/prime.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Factoring the 64 bit ``pq`` of the key exchange (Pollard's rho, Brent variant)."""
|
|
2
|
+
import math
|
|
3
|
+
import random
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _is_prime(n: int) -> bool:
|
|
7
|
+
if n < 2:
|
|
8
|
+
return False
|
|
9
|
+
for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
|
10
|
+
if n % p == 0:
|
|
11
|
+
return n == p
|
|
12
|
+
d, s = n - 1, 0
|
|
13
|
+
while d % 2 == 0:
|
|
14
|
+
d //= 2
|
|
15
|
+
s += 1
|
|
16
|
+
for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
|
17
|
+
x = pow(a, d, n)
|
|
18
|
+
if x in (1, n - 1):
|
|
19
|
+
continue
|
|
20
|
+
for _ in range(s - 1):
|
|
21
|
+
x = x * x % n
|
|
22
|
+
if x == n - 1:
|
|
23
|
+
break
|
|
24
|
+
else:
|
|
25
|
+
return False
|
|
26
|
+
return True
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def factorize(pq: int) -> tuple[int, int]:
|
|
30
|
+
"""Split ``pq`` into primes ``(p, q)`` with ``p < q``."""
|
|
31
|
+
if pq < 4:
|
|
32
|
+
raise ValueError("pq too small")
|
|
33
|
+
if pq % 2 == 0:
|
|
34
|
+
return 2, pq // 2
|
|
35
|
+
while True:
|
|
36
|
+
c = random.randrange(1, pq)
|
|
37
|
+
y, r, q, g = random.randrange(0, pq), 1, 1, 1
|
|
38
|
+
m = 128
|
|
39
|
+
x = ys = 0
|
|
40
|
+
while g == 1:
|
|
41
|
+
x = y
|
|
42
|
+
for _ in range(r):
|
|
43
|
+
y = (y * y + c) % pq
|
|
44
|
+
k = 0
|
|
45
|
+
while k < r and g == 1:
|
|
46
|
+
ys = y
|
|
47
|
+
for _ in range(min(m, r - k)):
|
|
48
|
+
y = (y * y + c) % pq
|
|
49
|
+
q = q * abs(x - y) % pq
|
|
50
|
+
g = math.gcd(q, pq)
|
|
51
|
+
k += m
|
|
52
|
+
r *= 2
|
|
53
|
+
if g == pq:
|
|
54
|
+
g = 1
|
|
55
|
+
while g == 1:
|
|
56
|
+
ys = (ys * ys + c) % pq
|
|
57
|
+
g = math.gcd(abs(x - ys), pq)
|
|
58
|
+
if g != pq:
|
|
59
|
+
p, q2 = sorted((g, pq // g))
|
|
60
|
+
if _is_prime(p) and _is_prime(q2):
|
|
61
|
+
return p, q2
|