MCPcopy Index your code
hub / github.com/python-telegram-bot/python-telegram-bot / decrypt

Function decrypt

src/telegram/_passport/credentials.py:52–97  ·  view source on GitHub ↗

Decrypt per telegram docs at https://core.telegram.org/passport. Args: secret (:obj:`str` or :obj:`bytes`): The encryption secret, either as bytes or as a base64 encoded string. hash (:obj:`str` or :obj:`bytes`): The hash, either as bytes or as a bas

(secret, hash, data)

Source from the content-addressed store, hash-verified

50
51@no_type_check
52def decrypt(secret, hash, data):
53 """
54 Decrypt per telegram docs at https://core.telegram.org/passport.
55
56 Args:
57 secret (:obj:`str` or :obj:`bytes`): The encryption secret, either as bytes or as a
58 base64 encoded string.
59 hash (:obj:`str` or :obj:`bytes`): The hash, either as bytes or as a
60 base64 encoded string.
61 data (:obj:`str` or :obj:`bytes`): The data to decrypt, either as bytes or as a
62 base64 encoded string.
63 file (:obj:`bool`): Force data to be treated as raw data, instead of trying to
64 b64decode it.
65
66 Raises:
67 :class:`PassportDecryptionError`: Given hash does not match hash of decrypted data.
68
69 Returns:
70 :obj:`bytes`: The decrypted data as bytes.
71
72 """
73 if not CRYPTO_INSTALLED:
74 raise RuntimeError(
75 "To use Telegram Passports, PTB must be installed via `pip install "
76 '"python-telegram-bot[passport]"`.'
77 )
78 # Make a SHA512 hash of secret + update
79 digest = Hash(SHA512(), backend=default_backend())
80 digest.update(secret + hash)
81 secret_hash_hash = digest.finalize()
82 # First 32 chars is our key, next 16 is the initialisation vector
83 key, init_vector = secret_hash_hash[:32], secret_hash_hash[32 : 32 + 16]
84 # Init a AES-CBC cipher and decrypt the data
85 cipher = Cipher(AES(key), CBC(init_vector), backend=default_backend())
86 decryptor = cipher.decryptor()
87 data = decryptor.update(data) + decryptor.finalize()
88 # Calculate SHA256 hash of the decrypted data
89 digest = Hash(SHA256(), backend=default_backend())
90 digest.update(data)
91 data_hash = digest.finalize()
92 # If the newly calculated hash did not match the one telegram gave us
93 if data_hash != hash:
94 # Raise a error that is caught inside telegram.PassportData and transformed into a warning
95 raise PassportDecryptionError(f"Hashes are not equal! {data_hash} != {hash}")
96 # Return data without padding
97 return data[data[0] :]
98
99
100@no_type_check

Callers 2

_prepare_decryptMethod · 0.90
decrypt_jsonFunction · 0.85

Calls 2

updateMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…