use crate::error::{OpenteleError, Result};
use crate::qt_compat::QDataStream;
use std::fmt;
use std::io::Read;
use zeroize::Zeroize;
pub const AUTH_KEY_LEN: usize = 256;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthKeyType {
Generated = 0,
Temporary = 1,
ReadFromFile = 2,
Local = 3,
}
#[derive(Clone)]
pub struct AuthKey {
key: Vec<u8>,
key_type: AuthKeyType,
dc_id: u32,
}
impl AuthKey {
pub fn new(key: Vec<u8>, key_type: AuthKeyType, dc_id: u32) -> Result<Self> {
if key.len() != AUTH_KEY_LEN {
return Err(OpenteleError::InvalidArgument(format!(
"auth key must contain {AUTH_KEY_LEN} bytes, got {}",
key.len()
)));
}
Ok(Self {
key,
key_type,
dc_id,
})
}
pub fn from_stream<R: Read>(
stream: &mut QDataStream<R>,
key_type: AuthKeyType,
dc_id: u32,
) -> Result<Self> {
let key_data = stream.read_qbytearray()?;
Self::new(key_data.data, key_type, dc_id)
}
pub fn as_bytes(&self) -> &[u8] {
&self.key
}
pub fn key_type(&self) -> AuthKeyType {
self.key_type.clone()
}
pub fn dc_id(&self) -> u32 {
self.dc_id
}
}
impl fmt::Debug for AuthKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("AuthKey")
.field("key", &"[REDACTED]")
.field("key_type", &self.key_type)
.field("dc_id", &self.dc_id)
.finish()
}
}
impl Drop for AuthKey {
fn drop(&mut self) {
self.key.zeroize();
}
}