laravel-two-factor-rust 0.3.0

Laravel Two Factor for Rust: authenticator app codes, QR codes and recovery codes for Laravel for Rust
Documentation
//! HOTP from RFC 4226, the code for one counter value. TOTP (RFC 6238) is HOTP with the number
//! of periods since the Unix epoch as the counter.

use hmac::{Hmac, KeyInit, Mac};
use sha1::Sha1;
use sha2::{Sha256, Sha512};

use crate::{Algorithm, Secret, TwoFactorConfig};

/// The code for `counter`, zero-padded to the configured digits.
pub(crate) fn code(secret: &Secret, counter: u64, config: &TwoFactorConfig) -> String {
    let message = counter.to_be_bytes();
    let hash = match config.algorithm {
        Algorithm::Sha1 => sign::<Hmac<Sha1>>(secret, &message),
        Algorithm::Sha256 => sign::<Hmac<Sha256>>(secret, &message),
        Algorithm::Sha512 => sign::<Hmac<Sha512>>(secret, &message),
    };

    // Dynamic truncation: the low four bits of the last byte pick where four bytes are read.
    let offset = usize::from(hash[hash.len() - 1] & 0x0f);
    let binary = u32::from_be_bytes(hash[offset..offset + 4].try_into().expect("four bytes")) & 0x7fff_ffff;
    let code = binary % 10u32.pow(config.digits);

    format!("{code:0width$}", width = config.digits as usize)
}

fn sign<M: Mac + KeyInit>(secret: &Secret, message: &[u8]) -> Vec<u8> {
    let mut mac = <M as KeyInit>::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length");
    mac.update(message);
    mac.finalize().into_bytes().to_vec()
}