use awol2005ex_kerberos_keytab::Keytab;
use awol2005ex_kerberos_crypto::Key;
use std::fs;
use std::error::Error;
pub fn load_key_from_keytab(keytab_path: &str, principal: &str) -> Result<Key, Box<dyn Error>> {
let keytab_data = fs::read(keytab_path)?;
let keytab = Keytab::parse(&keytab_data)
.map_err(|e| format!("Failed to parse keytab: {:?}", e))?
.1;
for entry in keytab.entries {
let realm_str: String = entry.realm.try_into()?;
let components: Vec<String> = entry.components
.into_iter()
.map(|c| String::from_utf8(c.data))
.collect::<Result<Vec<_>, _>>()?;
let principal_str = format!("{}@{}", components.join("/"), realm_str);
if principal_str == principal {
let key_hex = hex::encode(&entry.key.keyvalue);
match entry.key.keytype {
23 => return Ok(Key::from_rc4_key_string(&key_hex)?), 17 => return Ok(Key::from_aes_128_key_string(&key_hex)?), 18 => return Ok(Key::from_aes_256_key_string(&key_hex)?), _ => return Err(format!("Unsupported key type: {}", entry.key.keytype).into()),
}
}
}
Err(format!("Principal {} not found in keytab", principal).into())
}