TgCrypto
Cryptography Extension Library for Pyrogram
TgCrypto is a Cryptography Library written in C as a Python extension. It is designed to be portable, fast,
easy to install and use. TgCrypto is intended for Pyrogram and implements the
cryptographic algorithms Telegram requires, namely:
Requirements
Installation
$ pip3 install -U mtprotocrypt
API
TgCrypto API consists of these six methods:
def ige256_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
def ctr256_encrypt(data: bytes, key: bytes, iv: bytes, state: bytes) -> bytes: ...
def ctr256_decrypt(data: bytes, key: bytes, iv: bytes, state: bytes) -> bytes: ...
def cbc256_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
def cbc256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
Usage
IGE Mode
Note: Data must be padded to match a multiple of the block size (16 bytes).
import os
import tgcrypto
data = os.urandom(10 * 1024 * 1024 + 7)
key = os.urandom(32)
iv = os.urandom(32)
data += bytes(-len(data) % 16)
ige_encrypted = tgcrypto.ige256_encrypt(data, key, iv)
ige_decrypted = tgcrypto.ige256_decrypt(ige_encrypted, key, iv)
print(data == ige_decrypted)
CTR Mode (single chunk)
import os
import tgcrypto
data = os.urandom(10 * 1024 * 1024)
key = os.urandom(32)
enc_iv = bytearray(os.urandom(16))
dec_iv = enc_iv.copy()
ctr_encrypted = tgcrypto.ctr256_encrypt(data, key, enc_iv, bytes(1))
ctr_decrypted = tgcrypto.ctr256_decrypt(ctr_encrypted, key, dec_iv, bytes(1))
print(data == ctr_decrypted)
CTR Mode (stream)
import os
from io import BytesIO
import tgcrypto
data = BytesIO(os.urandom(10 * 1024 * 1024))
key = os.urandom(32)
enc_iv = bytearray(os.urandom(16))
dec_iv = enc_iv.copy()
enc_state = bytes(1)
dec_state = bytes(1)
encrypted_data = BytesIO()
decrypted_data = BytesIO()
while True:
chunk = data.read(1024)
if not chunk:
break
encrypted_data.write(tgcrypto.ctr256_encrypt(chunk, key, enc_iv, enc_state))
encrypted_data.seek(0)
while True:
chunk = encrypted_data.read(1024)
if not chunk:
break
decrypted_data.write(tgcrypto.ctr256_decrypt(chunk, key, dec_iv, dec_state))
print(data.getvalue() == decrypted_data.getvalue())
CBC Mode
Note: Data must be padded to match a multiple of the block size (16 bytes).
import os
import tgcrypto
data = os.urandom(10 * 1024 * 1024 + 7)
key = os.urandom(32)
enc_iv = bytearray(os.urandom(16))
dec_iv = enc_iv.copy()
data += bytes(-len(data) % 16)
cbc_encrypted = tgcrypto.cbc256_encrypt(data, key, enc_iv)
cbc_decrypted = tgcrypto.cbc256_decrypt(cbc_encrypted, key, dec_iv)
print(data == cbc_decrypted)
License
LGPLv3+ © 2017-present Dan