Skip to main content

ferogram_crypto/
auth_key.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//
4// ferogram: async Telegram MTProto client in Rust
5// https://github.com/ankit-chaubey/ferogram
6//
7//
8// If you use or modify this code, keep this notice at the top of your file
9// and include the LICENSE-MIT or LICENSE-APACHE file from this repository:
10// https://github.com/ankit-chaubey/ferogram
11
12//! Telegram `AuthKey`: 256-byte key derived from the DH handshake.
13
14use crate::sha1;
15
16/// A Telegram authorization key (256 bytes) plus pre-computed identifiers.
17#[derive(Clone)]
18pub struct AuthKey {
19    pub(crate) data: [u8; 256],
20    pub(crate) aux_hash: [u8; 8],
21    pub(crate) key_id: [u8; 8],
22}
23
24impl AuthKey {
25    /// Construct from raw 256-byte DH output.
26    pub fn from_bytes(data: [u8; 256]) -> Self {
27        let sha = sha1!(&data);
28        let mut aux_hash = [0u8; 8];
29        aux_hash.copy_from_slice(&sha[..8]);
30        let mut key_id = [0u8; 8];
31        key_id.copy_from_slice(&sha[12..20]);
32        Self {
33            data,
34            aux_hash,
35            key_id,
36        }
37    }
38
39    /// Return the raw 256-byte representation.
40    pub fn to_bytes(&self) -> [u8; 256] {
41        self.data
42    }
43
44    /// The 8-byte key identifier (SHA-1(key)[12..20]).
45    pub fn key_id(&self) -> [u8; 8] {
46        self.key_id
47    }
48
49    /// Compute the new-nonce hash needed for `DhGenOk/Retry/Fail` verification.
50    pub fn calc_new_nonce_hash(&self, new_nonce: &[u8; 32], number: u8) -> [u8; 16] {
51        let data: Vec<u8> = new_nonce
52            .iter()
53            .copied()
54            .chain([number])
55            .chain(self.aux_hash.iter().copied())
56            .collect();
57        let sha = sha1!(&data);
58        let mut out = [0u8; 16];
59        out.copy_from_slice(&sha[4..]);
60        out
61    }
62}
63
64impl std::fmt::Debug for AuthKey {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        write!(f, "AuthKey(id={})", u64::from_le_bytes(self.key_id))
67    }
68}
69
70impl PartialEq for AuthKey {
71    fn eq(&self, other: &Self) -> bool {
72        self.key_id == other.key_id
73    }
74}