2017-11-26 18:57:40 +03:00
|
|
|
"""
|
|
|
|
This module holds the AuthKey class.
|
|
|
|
"""
|
2017-09-27 22:23:59 +03:00
|
|
|
import struct
|
2017-06-02 17:49:03 +03:00
|
|
|
from hashlib import sha1
|
|
|
|
|
2021-09-12 17:23:55 +03:00
|
|
|
from .._misc.binaryreader import BinaryReader
|
2016-08-28 20:26:06 +03:00
|
|
|
|
|
|
|
|
|
|
|
class AuthKey:
|
2017-11-26 18:57:40 +03:00
|
|
|
"""
|
|
|
|
Represents an authorization key, used to encrypt and decrypt
|
|
|
|
messages sent to Telegram's data centers.
|
|
|
|
"""
|
2016-09-08 17:11:37 +03:00
|
|
|
def __init__(self, data):
|
2017-11-26 18:57:40 +03:00
|
|
|
"""
|
|
|
|
Initializes a new authorization key.
|
|
|
|
|
|
|
|
:param data: the data in bytes that represent this auth key.
|
|
|
|
"""
|
2016-09-08 17:11:37 +03:00
|
|
|
self.key = data
|
2016-08-28 20:26:06 +03:00
|
|
|
|
2018-10-19 13:40:36 +03:00
|
|
|
@property
|
|
|
|
def key(self):
|
|
|
|
return self._key
|
|
|
|
|
|
|
|
@key.setter
|
|
|
|
def key(self, value):
|
|
|
|
if not value:
|
|
|
|
self._key = self.aux_hash = self.key_id = None
|
|
|
|
return
|
|
|
|
|
2018-10-19 14:24:52 +03:00
|
|
|
if isinstance(value, type(self)):
|
|
|
|
self._key, self.aux_hash, self.key_id = \
|
|
|
|
value._key, value.aux_hash, value.key_id
|
|
|
|
return
|
|
|
|
|
2018-10-19 13:40:36 +03:00
|
|
|
self._key = value
|
|
|
|
with BinaryReader(sha1(self._key).digest()) as reader:
|
2016-08-28 20:26:06 +03:00
|
|
|
self.aux_hash = reader.read_long(signed=False)
|
|
|
|
reader.read(4)
|
|
|
|
self.key_id = reader.read_long(signed=False)
|
|
|
|
|
2018-10-19 14:24:52 +03:00
|
|
|
# TODO This doesn't really fit here, it's only used in authentication
|
2016-08-28 20:26:06 +03:00
|
|
|
def calc_new_nonce_hash(self, new_nonce, number):
|
2017-11-26 18:57:40 +03:00
|
|
|
"""
|
|
|
|
Calculates the new nonce hash based on the current attributes.
|
|
|
|
|
|
|
|
:param new_nonce: the new nonce to be hashed.
|
|
|
|
:param number: number to prepend before the hash.
|
|
|
|
:return: the hash for the given new nonce.
|
2017-09-04 18:10:04 +03:00
|
|
|
"""
|
2017-09-28 12:36:51 +03:00
|
|
|
new_nonce = new_nonce.to_bytes(32, 'little', signed=True)
|
2017-09-27 22:23:59 +03:00
|
|
|
data = new_nonce + struct.pack('<BQ', number, self.aux_hash)
|
2018-01-08 14:01:38 +03:00
|
|
|
|
|
|
|
# Calculates the message key from the given data
|
2018-06-07 18:20:45 +03:00
|
|
|
return int.from_bytes(sha1(data).digest()[4:20], 'little', signed=True)
|
2018-06-26 17:20:30 +03:00
|
|
|
|
2018-10-19 13:40:36 +03:00
|
|
|
def __bool__(self):
|
|
|
|
return bool(self._key)
|
|
|
|
|
2018-06-26 17:20:30 +03:00
|
|
|
def __eq__(self, other):
|
2018-10-19 13:40:36 +03:00
|
|
|
return isinstance(other, type(self)) and other.key == self._key
|