Skip to main content

layer_crypto/
auth_key.rs

1//! Telegram `AuthKey` — 256-byte key derived from the DH handshake.
2
3use crate::sha1;
4
5/// A Telegram authorization key (256 bytes) plus pre-computed identifiers.
6#[derive(Clone)]
7pub struct AuthKey {
8    pub(crate) data: [u8; 256],
9    pub(crate) aux_hash: [u8; 8],
10    pub(crate) key_id: [u8; 8],
11}
12
13impl AuthKey {
14    /// Construct from raw 256-byte DH output.
15    pub fn from_bytes(data: [u8; 256]) -> Self {
16        let sha = sha1!(&data);
17        let mut aux_hash = [0u8; 8];
18        aux_hash.copy_from_slice(&sha[..8]);
19        let mut key_id = [0u8; 8];
20        key_id.copy_from_slice(&sha[12..20]);
21        Self { data, aux_hash, key_id }
22    }
23
24    /// Return the raw 256-byte representation.
25    pub fn to_bytes(&self) -> [u8; 256] { self.data }
26
27    /// The 8-byte key identifier (SHA-1(key)[12..20]).
28    pub fn key_id(&self) -> [u8; 8] { self.key_id }
29
30    /// Compute the new-nonce hash needed for `DhGenOk/Retry/Fail` verification.
31    pub fn calc_new_nonce_hash(&self, new_nonce: &[u8; 32], number: u8) -> [u8; 16] {
32        let data: Vec<u8> = new_nonce.iter()
33            .copied()
34            .chain([number])
35            .chain(self.aux_hash.iter().copied())
36            .collect();
37        let sha = sha1!(&data);
38        let mut out = [0u8; 16];
39        out.copy_from_slice(&sha[4..]);
40        out
41    }
42}
43
44impl std::fmt::Debug for AuthKey {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "AuthKey(id={})", u64::from_le_bytes(self.key_id))
47    }
48}
49
50impl PartialEq for AuthKey {
51    fn eq(&self, other: &Self) -> bool { self.key_id == other.key_id }
52}