From d54f86592caafd4edcce38770dd748e08a35c576 Mon Sep 17 00:00:00 2001 From: wyhaya Date: Fri, 6 May 2022 17:35:49 +0800 Subject: [PATCH 1/2] Support generate token from the current time --- src/lib.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index ca28739..874f409 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,6 +55,7 @@ use core::fmt; use {base64, image::Luma, qrcodegen}; use hmac::Mac; +use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH}; type HmacSha1 = hmac::Hmac; type HmacSha256 = hmac::Hmac; @@ -169,6 +170,14 @@ impl> TOTP { ) } + /// Generate a token from the current system time + pub fn generate_current(&self) -> Result { + let time = SystemTime::now() + .duration_since(UNIX_EPOCH)? + .as_secs(); + Ok(self.generate(time)) + } + /// Will check if token is valid by current time, accounting [skew](struct.TOTP.html#structfield.skew) pub fn check(&self, token: &str, time: u64) -> bool { let basestep = time / self.step - (self.skew as u64); From 1e546058089ae996b495361e6f9658b71455db50 Mon Sep 17 00:00:00 2001 From: wyhaya Date: Fri, 6 May 2022 17:55:31 +0800 Subject: [PATCH 2/2] Add check_current --- src/lib.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 874f409..be0d599 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -104,6 +104,13 @@ impl Algorithm { } } +fn system_time() -> Result { + let t = SystemTime::now() + .duration_since(UNIX_EPOCH)? + .as_secs(); + Ok(t) +} + /// TOTP holds informations as to how to generate an auth code and validate it. Its [secret](struct.TOTP.html#structfield.secret) field is sensitive data, treat it accordingly #[derive(Debug, Clone)] #[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] @@ -172,10 +179,8 @@ impl> TOTP { /// Generate a token from the current system time pub fn generate_current(&self) -> Result { - let time = SystemTime::now() - .duration_since(UNIX_EPOCH)? - .as_secs(); - Ok(self.generate(time)) + let t = system_time()?; + Ok(self.generate(t)) } /// Will check if token is valid by current time, accounting [skew](struct.TOTP.html#structfield.skew) @@ -191,6 +196,12 @@ impl> TOTP { false } + /// Will check if token is valid by current system time, accounting [skew](struct.TOTP.html#structfield.skew) + pub fn check_current(&self, token: &str) -> Result { + let t = system_time()?; + Ok(self.check(token, t)) + } + /// Will return the base32 representation of the secret, which might be useful when users want to manually add the secret to their authenticator pub fn get_secret_base32(&self) -> String { base32::encode(