use crate::attributes::*;
use crate::integrity::CREDENTIALS_SEP;
use crate::message::*;
use crate::opaque::opaque_string;
use crypto::{HashAlgorithm, RTCCrypto};
use shared::error::*;
pub const USERHASH_SIZE: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Userhash(pub [u8; USERHASH_SIZE]);
impl Userhash {
pub fn new(username: &str, realm: &str, crypto: &dyn RTCCrypto) -> Result<Self> {
let input = [opaque_string(username)?, opaque_string(realm)?].join(CREDENTIALS_SEP);
let hash = crypto
.hash(HashAlgorithm::Sha256, input.as_bytes())
.map_err(|e| Error::Crypto(e.to_string()))?;
let value: [u8; USERHASH_SIZE] = hash.as_slice().try_into().map_err(|_| {
Error::Crypto(format!(
"provider returned an invalid SHA-256 digest length: {}",
hash.len()
))
})?;
Ok(Self(value))
}
}
impl Setter for Userhash {
fn add_to(&self, m: &mut Message) -> Result<()> {
m.add(ATTR_USER_HASH, &self.0);
Ok(())
}
}
impl Getter for Userhash {
fn get_from(&mut self, m: &Message) -> Result<()> {
let v = m.get(ATTR_USER_HASH)?;
self.0 = v
.as_slice()
.try_into()
.map_err(|_| Error::ErrAttributeSizeInvalid)?;
Ok(())
}
}