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