use data_encoding::{DecodeError, BASE32};
use ring::hmac;
use std::time::{SystemTime, SystemTimeError};
use thiserror::Error;
fn decode_base32(input: &str) -> Result<Vec<u8>, DecodeError> {
let input = input.trim();
if input.contains('=') {
BASE32.decode(input.as_bytes())
} else {
let mut padded = input.to_string();
while padded.len() % 8 != 0 {
padded.push('=');
}
BASE32.decode(padded.as_bytes())
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid time: {0}")]
InvalidTime(#[from] SystemTimeError),
#[error("invalid secret: {0}")]
DecodeError(#[from] DecodeError),
#[error("invalid digest length")]
InvalidDigestLength,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Algorithm {
#[default]
SHA1,
SHA256,
SHA512,
}
impl From<Algorithm> for hmac::Algorithm {
fn from(algo: Algorithm) -> Self {
match algo {
Algorithm::SHA1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
Algorithm::SHA256 => hmac::HMAC_SHA256,
Algorithm::SHA512 => hmac::HMAC_SHA512,
}
}
}
#[derive(Debug, Clone)]
pub struct HOTP {
secret: Vec<u8>,
algorithm: Algorithm,
digits: u32,
}
impl HOTP {
pub fn builder() -> HOTPBuilder {
HOTPBuilder::new()
}
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32) -> Self {
Self {
secret,
algorithm,
digits,
}
}
pub fn generate(&self, counter: u64) -> u32 {
let key = hmac::Key::new(self.algorithm.into(), &self.secret);
let tag = hmac::sign(&key, &counter.to_be_bytes());
let digest = tag.as_ref();
let offset = (digest[digest.len() - 1] & 0xf) as usize;
let code_bytes: [u8; 4] = digest[offset..offset + 4].try_into().unwrap_or([0u8; 4]);
let code = u32::from_be_bytes(code_bytes);
(code & 0x7fffffff) % 10u32.pow(self.digits)
}
pub fn generate_formatted(&self, counter: u64) -> String {
format!(
"{:0width$}",
self.generate(counter),
width = self.digits as usize
)
}
pub fn verify(&self, code: u32, counter: u64) -> bool {
self.generate(counter) == code
}
pub fn verify_formatted(&self, code: &str, counter: u64) -> bool {
self.generate_formatted(counter) == code
}
#[cfg(feature = "async")]
pub async fn generate_async(&self, counter: u64) -> u32 {
self.generate(counter)
}
#[cfg(feature = "async")]
pub async fn generate_formatted_async(&self, counter: u64) -> String {
self.generate_formatted(counter)
}
}
#[derive(Debug, Default)]
pub struct HOTPBuilder {
secret: Option<Vec<u8>>,
algorithm: Algorithm,
digits: u32,
}
impl HOTPBuilder {
pub fn new() -> Self {
Self {
secret: None,
algorithm: Algorithm::SHA1,
digits: 6,
}
}
pub fn secret(mut self, secret: Vec<u8>) -> Self {
self.secret = Some(secret);
self
}
pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
self.secret = Some(decode_base32(secret)?);
Ok(self)
}
pub fn algorithm(mut self, algo: Algorithm) -> Self {
self.algorithm = algo;
self
}
pub fn digits(mut self, digits: u32) -> Self {
self.digits = digits;
self
}
pub fn build(self) -> Result<HOTP, String> {
let secret = self
.secret
.ok_or_else(|| "Secret is required".to_string())?;
if self.digits > 9 {
return Err("Digits must be between 1 and 9 for u32 output".to_string());
}
Ok(HOTP::new(secret, self.algorithm, self.digits))
}
}
#[derive(Debug, Clone)]
pub struct TOTP {
hotp: HOTP,
time_step: u64,
}
impl TOTP {
pub fn builder() -> TOTPBuilder {
TOTPBuilder::new()
}
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, time_step: u64) -> Self {
Self {
hotp: HOTP::new(secret, algorithm, digits),
time_step,
}
}
pub fn generate_at(&self, timestamp: u64) -> u32 {
let counter = timestamp / self.time_step;
self.hotp.generate(counter)
}
pub fn generate_current(&self) -> Result<u32, Error> {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
Ok(self.generate_at(now.as_secs()))
}
pub fn generate_formatted_at(&self, timestamp: u64) -> String {
format!(
"{:0width$}",
self.generate_at(timestamp),
width = self.hotp.digits as usize
)
}
pub fn generate_current_formatted(&self) -> Result<String, Error> {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
Ok(self.generate_formatted_at(now.as_secs()))
}
pub fn verify_at(&self, code: u32, timestamp: u64, window: u32) -> bool {
let current_step = timestamp / self.time_step;
for i in 0..=window {
if self.hotp.generate(current_step.saturating_sub(i as u64)) == code {
return true;
}
if self.hotp.generate(current_step.saturating_add(i as u64)) == code {
return true;
}
}
false
}
pub fn verify_current(&self, code: u32, window: u32) -> Result<bool, Error> {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
Ok(self.verify_at(code, now.as_secs(), window))
}
pub fn verify_current_formatted(&self, code: &str, window: u32) -> Result<bool, Error> {
let code_u32 = code
.parse::<u32>()
.map_err(|_| Error::InvalidDigestLength)?; self.verify_current(code_u32, window)
}
#[cfg(feature = "async")]
pub async fn generate_current_async(&self) -> Result<u32, Error> {
self.generate_current()
}
#[cfg(feature = "async")]
pub async fn generate_current_formatted_async(&self) -> Result<String, Error> {
self.generate_current_formatted()
}
}
pub struct TOTPBuilder {
secret: Option<Vec<u8>>,
algorithm: Algorithm,
digits: u32,
time_step: u64,
}
impl Default for TOTPBuilder {
fn default() -> Self {
Self {
secret: None,
algorithm: Algorithm::SHA1,
digits: 6,
time_step: 30,
}
}
}
impl TOTPBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn secret(mut self, secret: Vec<u8>) -> Self {
self.secret = Some(secret);
self
}
pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
let decoded = BASE32.decode(secret.as_bytes())?;
self.secret = Some(decoded);
Ok(self)
}
pub fn algorithm(mut self, algo: Algorithm) -> Self {
self.algorithm = algo;
self
}
pub fn digits(mut self, digits: u32) -> Self {
self.digits = digits;
self
}
pub fn time_step(mut self, step: u64) -> Self {
self.time_step = step;
self
}
pub fn build(self) -> Result<TOTP, String> {
let secret = self
.secret
.ok_or_else(|| "Secret is required".to_string())?;
if self.digits > 9 {
return Err("Digits must be between 1 and 9 for u32 output".to_string());
}
Ok(TOTP::new(
secret,
self.algorithm,
self.digits,
self.time_step,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rfc4226_hotp() {
let secret = b"12345678901234567890".to_vec();
let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
assert_eq!(hotp.generate(0), 755224);
assert_eq!(hotp.generate(1), 287082);
assert_eq!(hotp.generate(2), 359152);
assert_eq!(hotp.generate(3), 969429);
assert_eq!(hotp.generate(4), 338314);
assert_eq!(hotp.generate(5), 254676);
assert_eq!(hotp.generate(6), 287922);
assert_eq!(hotp.generate(7), 162583);
assert_eq!(hotp.generate(8), 399871);
assert_eq!(hotp.generate(9), 520489);
}
#[test]
fn test_rfc6238_totp_sha1() {
let secret = b"12345678901234567890".to_vec();
let totp = TOTP::new(secret, Algorithm::SHA1, 8, 30);
assert_eq!(totp.generate_formatted_at(59), "94287082");
assert_eq!(totp.generate_formatted_at(1111111109), "07081804");
assert_eq!(totp.generate_formatted_at(1111111111), "14050471");
assert_eq!(totp.generate_formatted_at(1234567890), "89005924");
assert_eq!(totp.generate_formatted_at(2000000000), "69279037");
assert_eq!(totp.generate_formatted_at(20000000000), "65353130");
}
#[test]
fn test_rfc6238_totp_sha256() {
let secret = b"12345678901234567890123456789012".to_vec();
let totp = TOTP::new(secret, Algorithm::SHA256, 8, 30);
assert_eq!(totp.generate_formatted_at(59), "46119246");
assert_eq!(totp.generate_formatted_at(1111111109), "68084774");
assert_eq!(totp.generate_formatted_at(1111111111), "67062674");
assert_eq!(totp.generate_formatted_at(1234567890), "91819424");
assert_eq!(totp.generate_formatted_at(2000000000), "90698825");
assert_eq!(totp.generate_formatted_at(20000000000), "77737706");
}
#[test]
fn test_rfc6238_totp_sha512() {
let secret = b"1234567890123456789012345678901234567890123456789012345678901234".to_vec();
let totp = TOTP::new(secret, Algorithm::SHA512, 8, 30);
assert_eq!(totp.generate_formatted_at(59), "90693936");
assert_eq!(totp.generate_formatted_at(1111111109), "25091201");
assert_eq!(totp.generate_formatted_at(1111111111), "99943326");
assert_eq!(totp.generate_formatted_at(1234567890), "93441116");
assert_eq!(totp.generate_formatted_at(2000000000), "38618901");
assert_eq!(totp.generate_formatted_at(20000000000), "47863826");
}
#[test]
fn test_builder() {
let hotp = HOTP::builder()
.base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
.unwrap()
.digits(6)
.build()
.unwrap();
assert_eq!(hotp.generate(0), 755224);
}
#[test]
fn test_unpadded_base32() {
let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; let res = HOTP::builder().base32_secret(secret);
assert!(res.is_ok());
let secret_unpadded = "GEZDGNBVGY3TQOJQGEZDGNBV"; let res = HOTP::builder().base32_secret(secret_unpadded);
assert!(
res.is_ok(),
"Base32 decoding should be robust to missing padding"
);
let secret_very_unpadded = "GEZDG"; let res = HOTP::builder().base32_secret(secret_very_unpadded);
assert!(
res.is_ok(),
"Base32 decoding should handle very unpadded strings"
);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_async() {
let secret = b"12345678901234567890".to_vec();
let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
assert_eq!(hotp.generate_async(0).await, 755224);
let secret = b"12345678901234567890".to_vec();
let totp = TOTP::new(secret, Algorithm::SHA1, 6, 30);
assert_eq!(totp.generate_current_async().await.is_ok(), true);
}
}