grammpars 0.1.0

Offline conversion between Telegram Desktop tdata, Telethon, and grammers sessions
Documentation
use crate::error::{OpenteleError, Result};
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
use aes::Aes256;
use pbkdf2::pbkdf2_hmac;
use sha2::Sha512;

/// Cryptographic operations for the Telegram Desktop storage format.
pub struct CryptoUtils;

impl CryptoUtils {
    /// Computes an MD5 digest used by the legacy TDF format.
    pub fn md5(data: &[u8]) -> Vec<u8> {
        use md5::{Digest, Md5};
        let mut hasher = Md5::new();
        hasher.update(data);
        hasher.finalize().to_vec()
    }
    /// Decrypts data using AES Infinite Garble Extension (IGE) mode.
    ///
    /// # Errors
    ///
    /// Returns an error when the key or IV is not 32 bytes, or when the input
    /// length is not a multiple of the 16 byte AES block size.
    pub fn aes_ige_decrypt(data: &[u8], key: &[u8], iv: &[u8]) -> Result<Vec<u8>> {
        if key.len() != 32 || iv.len() != 32 || data.len() % 16 != 0 {
            return Err(OpenteleError::CryptoError(
                "Invalid key/iv or data length for AES-IGE".to_string(),
            ));
        }

        let cipher = Aes256::new(GenericArray::from_slice(key));

        let mut prev_c = *GenericArray::from_slice(&iv[0..16]);
        let mut prev_p = *GenericArray::from_slice(&iv[16..32]);

        let mut output = Vec::with_capacity(data.len());

        for chunk in data.chunks_exact(16) {
            let c = *GenericArray::from_slice(chunk);
            let mut block = c;

            for i in 0..16 {
                block[i] ^= prev_p[i];
            }

            cipher.decrypt_block(&mut block);

            for i in 0..16 {
                block[i] ^= prev_c[i];
            }

            output.extend_from_slice(&block);
            prev_c = c;
            prev_p = block;
        }

        Ok(output)
    }

    /// Encrypts data using AES Infinite Garble Extension (IGE) mode.
    ///
    /// # Errors
    ///
    /// Returns an error when the key or IV is not 32 bytes, or when the input
    /// length is not a multiple of the 16 byte AES block size.
    pub fn aes_ige_encrypt(data: &[u8], key: &[u8], iv: &[u8]) -> Result<Vec<u8>> {
        if key.len() != 32 || iv.len() != 32 || data.len() % 16 != 0 {
            return Err(OpenteleError::CryptoError(
                "Invalid key/iv or data length for AES-IGE".to_string(),
            ));
        }

        let cipher = Aes256::new(GenericArray::from_slice(key));

        let mut prev_c = *GenericArray::from_slice(&iv[0..16]);
        let mut prev_p = *GenericArray::from_slice(&iv[16..32]);

        let mut output = Vec::with_capacity(data.len());

        for chunk in data.chunks_exact(16) {
            let p = *GenericArray::from_slice(chunk);
            let mut block = p;

            for i in 0..16 {
                block[i] ^= prev_c[i];
            }

            cipher.encrypt_block(&mut block);

            for i in 0..16 {
                block[i] ^= prev_p[i];
            }

            output.extend_from_slice(&block);
            prev_p = p;
            prev_c = block;
        }

        Ok(output)
    }

    /// Derives the local key used to encrypt the `tdata` key store.
    ///
    /// # Errors
    ///
    /// This implementation currently completes without returning an error.
    /// The result remains wrapped for consistency with other crypto operations.
    pub fn derive_local_key(passcode: &[u8], salt: &[u8]) -> Result<Vec<u8>> {
        let iterations = if passcode.is_empty() { 1 } else { 100_000 };

        use sha2::Digest;
        let mut hasher = Sha512::new();
        hasher.update(salt);
        hasher.update(passcode);
        hasher.update(salt);
        let hash_key = hasher.finalize();

        let mut res = vec![0u8; 256];
        pbkdf2_hmac::<Sha512>(&hash_key, salt, iterations, &mut res);

        Ok(res)
    }

    /// Derives a legacy PBKDF2-HMAC-SHA1 local key.
    ///
    /// # Errors
    ///
    /// This implementation currently completes without returning an error.
    /// The result remains wrapped for consistency with other crypto operations.
    pub fn derive_legacy_local_key(passcode: &[u8], salt: &[u8]) -> Result<Vec<u8>> {
        let iterations = if passcode.is_empty() { 4 } else { 4_000 };

        let mut res = vec![0u8; 256];
        pbkdf2_hmac::<sha1::Sha1>(passcode, salt, iterations, &mut res);

        Ok(res)
    }

    /// Derives the AES key and IV used by Telegram Desktop's old MTProto scheme.
    ///
    /// # Errors
    ///
    /// Returns an error when `msg_key` is shorter than 16 bytes or `auth_key`
    /// is too short for the selected message direction.
    pub fn prepare_aes_oldmtp(
        msg_key: &[u8],
        auth_key: &[u8],
        send: bool,
    ) -> Result<(Vec<u8>, Vec<u8>)> {
        let x = if send { 0 } else { 8 };
        if msg_key.len() < 16 || auth_key.len() < x + 128 {
            return Err(OpenteleError::CryptoError(
                "msg_key or auth_key too short".into(),
            ));
        }
        use sha1::{Digest, Sha1};

        let sha1_a = {
            let mut h = Sha1::new();
            h.update(&msg_key[..16]);
            h.update(&auth_key[x..x + 32]);
            h.finalize()
        };

        let sha1_b = {
            let mut h = Sha1::new();
            h.update(&auth_key[x + 32..x + 32 + 16]);
            h.update(&msg_key[..16]);
            h.update(&auth_key[x + 48..x + 48 + 16]);
            h.finalize()
        };

        let sha1_c = {
            let mut h = Sha1::new();
            h.update(&auth_key[x + 64..x + 64 + 32]);
            h.update(&msg_key[..16]);
            h.finalize()
        };

        let sha1_d = {
            let mut h = Sha1::new();
            h.update(&msg_key[..16]);
            h.update(&auth_key[x + 96..x + 96 + 32]);
            h.finalize()
        };

        let mut aes_key = Vec::with_capacity(32);
        aes_key.extend_from_slice(&sha1_a[..8]);
        aes_key.extend_from_slice(&sha1_b[8..8 + 12]);
        aes_key.extend_from_slice(&sha1_c[4..4 + 12]);

        let mut aes_iv = Vec::with_capacity(32);
        aes_iv.extend_from_slice(&sha1_a[8..8 + 12]);
        aes_iv.extend_from_slice(&sha1_b[..8]);
        aes_iv.extend_from_slice(&sha1_c[16..16 + 4]);
        aes_iv.extend_from_slice(&sha1_d[..8]);

        Ok((aes_key, aes_iv))
    }
}