use ring::hmac;
pub const STEP_SECS: u64 = 30;
pub const DIGITS: u32 = 6;
pub const SKEW: u64 = 1;
pub fn hotp(secret: &[u8], counter: u64, digits: u32) -> u32 {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
let tag = hmac::sign(&key, &counter.to_be_bytes());
let mac = tag.as_ref();
let offset = usize::from(mac.last().copied().unwrap_or_default() & 0x0f);
let word = mac
.get(offset..offset + 4)
.and_then(|w| <[u8; 4]>::try_from(w).ok())
.unwrap_or_default();
(u32::from_be_bytes(word) & 0x7fff_ffff) % 10u32.pow(digits)
}
pub fn step(unix_secs: u64) -> u64 {
unix_secs / STEP_SECS
}
pub fn code(secret: &[u8], step: u64) -> String {
format!(
"{:0width$}",
hotp(secret, step, DIGITS),
width = DIGITS as usize
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
Missing,
Malformed,
Wrong,
Replayed,
}
impl Refusal {
pub fn as_str(self) -> &'static str {
match self {
Self::Missing => "no code was typed",
Self::Malformed => "the code is not six digits",
Self::Wrong => "the code is wrong",
Self::Replayed => "the code was already used",
}
}
}
pub fn check(secret: &[u8], typed: &str, now_secs: u64, last_step: u64) -> Result<u64, Refusal> {
let typed = typed.trim();
if typed.is_empty() {
return Err(Refusal::Missing);
}
if typed.len() != DIGITS as usize || !typed.bytes().all(|b| b.is_ascii_digit()) {
return Err(Refusal::Malformed);
}
let now = step(now_secs);
let mut matched = None;
for candidate in now.saturating_sub(SKEW)..=now.saturating_add(SKEW) {
if same(code(secret, candidate).as_bytes(), typed.as_bytes()) && matched.is_none() {
matched = Some(candidate);
}
}
match matched {
None => Err(Refusal::Wrong),
Some(step) if step <= last_step => Err(Refusal::Replayed),
Some(step) => Ok(step),
}
}
fn same(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}