use hmac::{Hmac, Mac};
use sha1::Sha1;
const STEP_SECONDS: i64 = 30;
const DIGITS: u32 = 6;
const BASE32: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
pub fn new_secret() -> String {
let mut bytes = [0u8; 20];
getrandom::fill(&mut bytes).expect("the system's random number generator failed");
base32(&bytes)
}
pub fn uri(secret: &str, account: &str, issuer: &str) -> String {
let escape = |text: &str| {
percent_encoding::utf8_percent_encode(text, percent_encoding::NON_ALPHANUMERIC).to_string()
};
format!(
"otpauth://totp/{}:{}?secret={secret}&issuer={}&algorithm=SHA1&digits={DIGITS}&period={STEP_SECONDS}",
escape(issuer),
escape(account),
escape(issuer)
)
}
pub fn qr_svg(text: &str) -> String {
match qrcode::QrCode::new(text.as_bytes()) {
Ok(code) => code
.render::<qrcode::render::svg::Color>()
.min_dimensions(200, 200)
.quiet_zone(true)
.build(),
Err(_) => String::new(),
}
}
pub fn code_at(secret: &str, unix_seconds: i64) -> Option<String> {
let key = from_base32(secret)?;
Some(code_for_step(&key, unix_seconds.div_euclid(STEP_SECONDS)))
}
pub fn verify(secret: &str, code: &str, after: Option<i64>) -> Option<i64> {
let key = from_base32(secret)?;
let code: String = code.chars().filter(|c| !c.is_whitespace()).collect();
if code.len() != DIGITS as usize || !code.chars().all(|c| c.is_ascii_digit()) {
return None;
}
let now = crate::time::now().timestamp().div_euclid(STEP_SECONDS);
let mut matched = None;
for step in now - 1..=now + 1 {
let expected = code_for_step(&key, step);
if constant_time_eq(expected.as_bytes(), code.as_bytes())
&& after.is_none_or(|last| step > last)
{
matched = Some(step);
}
}
matched
}
pub fn recovery_codes(count: usize) -> Vec<String> {
const ALPHABET: &[u8] = b"abcdefghjkmnpqrstuvwxyz23456789";
(0..count)
.map(|_| {
let mut bytes = [0u8; 10];
getrandom::fill(&mut bytes).expect("the system's random number generator failed");
let chars: String = bytes
.iter()
.map(|b| ALPHABET[usize::from(*b) % ALPHABET.len()] as char)
.collect();
format!("{}-{}", &chars[..5], &chars[5..])
})
.collect()
}
pub fn normalize_recovery_code(code: &str) -> String {
code.chars()
.filter(|c| !c.is_whitespace())
.collect::<String>()
.to_lowercase()
}
fn code_for_step(key: &[u8], step: i64) -> String {
let mut mac = Hmac::<Sha1>::new_from_slice(key).expect("HMAC takes a key of any length");
mac.update(&step.to_be_bytes());
let hash = mac.finalize().into_bytes();
let offset = usize::from(hash[19] & 0x0f);
let binary = u32::from_be_bytes([
hash[offset] & 0x7f,
hash[offset + 1],
hash[offset + 2],
hash[offset + 3],
]);
format!(
"{:0width$}",
binary % 10u32.pow(DIGITS),
width = DIGITS as usize
)
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
fn base32(bytes: &[u8]) -> String {
let mut out = String::new();
let (mut buffer, mut bits) = (0u32, 0u32);
for byte in bytes {
buffer = (buffer << 8) | u32::from(*byte);
bits += 8;
while bits >= 5 {
bits -= 5;
out.push(BASE32[((buffer >> bits) & 31) as usize] as char);
}
}
if bits > 0 {
out.push(BASE32[((buffer << (5 - bits)) & 31) as usize] as char);
}
out
}
fn from_base32(text: &str) -> Option<Vec<u8>> {
let mut out = Vec::new();
let (mut buffer, mut bits) = (0u32, 0u32);
for c in text.chars().filter(|c| !c.is_whitespace() && *c != '=') {
let value = BASE32
.iter()
.position(|b| *b as char == c.to_ascii_uppercase())?;
buffer = (buffer << 5) | value as u32;
bits += 5;
if bits >= 8 {
bits -= 8;
out.push((buffer >> bits) as u8);
}
}
(!out.is_empty()).then_some(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn rfc_secret() -> String {
base32(b"12345678901234567890")
}
#[test]
fn matches_rfc_6238() {
let secret = rfc_secret();
assert_eq!(secret, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
assert_eq!(code_at(&secret, 59).unwrap(), "287082");
assert_eq!(code_at(&secret, 1111111109).unwrap(), "081804");
assert_eq!(code_at(&secret, 1234567890).unwrap(), "005924");
assert_eq!(code_at(&secret, 2000000000).unwrap(), "279037");
}
#[test]
fn base32_round_trips() {
for bytes in [&b"f"[..], b"fo", b"foo", b"foob", b"fooba", b"foobar"] {
assert_eq!(from_base32(&base32(bytes)).unwrap(), bytes);
}
assert_eq!(base32(b"foobar"), "MZXW6YTBOI");
assert!(from_base32("not base32!").is_none());
assert_eq!(new_secret().len(), 32);
}
#[test]
fn makes_an_otpauth_uri_and_a_qr_code() {
let uri = uri("ABC", "ada@example.com", "My App");
assert_eq!(
uri,
"otpauth://totp/My%20App:ada%40example%2Ecom?secret=ABC&issuer=My%20App&algorithm=SHA1&digits=6&period=30"
);
assert!(qr_svg(&uri).contains("<svg"));
}
#[test]
fn verifies_a_code_once() {
let secret = new_secret();
let now = crate::time::now().timestamp();
let code = code_at(&secret, now).unwrap();
let step = verify(&secret, &code, None).expect("the current code");
assert!(verify(&secret, &code, Some(step)).is_none(), "used already");
let spaced = format!("{} {}", &code[..3], &code[3..]);
assert!(verify(&secret, &spaced, Some(step - 2)).is_some());
let old = code_at(&secret, now - 120).unwrap();
assert!(
old == code || verify(&secret, &old, None).is_none(),
"too old"
);
assert!(verify(&secret, "12345", None).is_none());
assert!(verify(&secret, "abcdef", None).is_none());
}
#[test]
fn recovery_codes_are_distinct() {
let codes = recovery_codes(10);
assert_eq!(codes.len(), 10);
assert!(codes.iter().all(|c| c.len() == 11 && &c[5..6] == "-"));
let mut unique = codes.clone();
unique.sort();
unique.dedup();
assert_eq!(unique.len(), 10);
assert_eq!(normalize_recovery_code(" ABCDE-12345 "), "abcde-12345");
}
}