change: Make the totp_now function better
All checks were successful
Write changelog / write-changelog (push) Successful in 4s
Rust CI / Rust CI (push) Successful in 1m55s

Signed-off-by: Awiteb <a@4rs.nl>
This commit is contained in:
Awiteb 2024-05-30 19:09:00 +03:00
parent 1221ed45db
commit 9a417e7d0b
Signed by: awiteb
GPG key ID: 3F6B55640AA6682F

View file

@ -40,37 +40,22 @@ pub enum TotpHash {
} }
/// Create the TOTP code of the current time /// Create the TOTP code of the current time with its remainig time in seconds
/// ///
/// ## Errors /// ## Errors
/// - If the given `secret_base32` are vaild base32 /// - If the given `secret_base32` are invalid base32
pub fn totp_now(secret_base32: &str, hash_function: &TotpHash) -> LprsResult<(String, u8)> { pub fn totp_now(secret_base32: &str, hash_function: &TotpHash) -> LprsResult<(String, u8)> {
let now = SystemTime::now() let now = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!") .expect("SystemTime before UNIX EPOCH!")
.as_secs(); .as_secs();
let remaining = 30 - (now % 30) as u8;
let secret = base32_decode(secret_base32)?; let secret = base32_decode(secret_base32)?;
Ok(match hash_function { let totp_code = match hash_function {
TotpHash::Sha1 => { TotpHash::Sha1 => totp_lite::totp_custom::<totp_lite::Sha1>(30, 6, &secret, now),
( TotpHash::Sha256 => totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret, now),
totp_lite::totp_custom::<totp_lite::Sha1>(30, 6, &secret, now), TotpHash::Sha512 => totp_lite::totp_custom::<totp_lite::Sha512>(30, 6, &secret, now),
remaining, };
) Ok((totp_code, 30 - (now % 30) as u8))
}
TotpHash::Sha256 => {
(
totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret, now),
remaining,
)
}
TotpHash::Sha512 => {
(
totp_lite::totp_custom::<totp_lite::Sha512>(30, 6, &secret, now),
remaining,
)
}
})
} }
/// Base32 decode /// Base32 decode