Functional Weave
Code in Rust

auth.totp@1.0.0

impl/rust/hotp_code.rs

3,554 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::crypto_hmac_sha1::hmac_sha1;  ← from crypto.hmac-sha1 ^1.0.0 · built alongside by fune
use super::crypto_hmac_sha256::hmac_sha256;  ← from crypto.hmac-sha256 ^1.0.0 · built alongside by fune
use super::encoding_base32_base32_decode::base32_decode;

const MAX_SAFE: i64 = 9007199254740991;

/// Whole number from 0 to 2^53 - 1: the range all three languages agree on.
pub fn is_totp_whole(value: i64) -> bool {
    (0..=MAX_SAFE).contains(&value)
}

pub fn check_totp_digits(digits: i64) {
    if !(6..=8).contains(&digits) {
        panic!("digits must be 6, 7 or 8");
    }
}

pub fn check_totp_algorithm(algorithm: &str) {
    if algorithm != "SHA1" && algorithm != "SHA256" {
        panic!("algorithm must be SHA1 or SHA256");
    }
}

pub fn check_totp_settings(settings: &TotpSettings) {
    check_totp_algorithm(&settings.algorithm);
    check_totp_digits(settings.digits);
    if !is_totp_whole(settings.period) || settings.period < 1 {
        panic!("period must be a whole number of seconds, 1 or more");
    }
}

/// The secret's bytes. Old Google Authenticator secrets are 80 bits, so 10
/// bytes is the least accepted; new ones from totp_secret are 16 or more.
pub fn totp_secret_key(secret: &str) -> Vec<i64> {
    let key = base32_decode(secret);
    if key.len() < 10 {
        panic!("secret must decode to at least 10 bytes");
    }
    key
}

/// RFC 4226 section 5.3: HMAC of the 8-byte big-endian counter, then dynamic
/// truncation.
pub fn hotp_from_key(key: &[i64], counter: i64, digits: i64, algorithm: &str) -> String {
    let message: Vec<i64> = (counter as u64).to_be_bytes().iter().map(|b| *b as i64).collect();
    let mac = if algorithm == "SHA1" { hmac_sha1(key, &message) } else { hmac_sha256(key, &message) };
    let offset = (mac[mac.len() - 1] & 15) as usize;
    let binary = ((mac[offset] & 127) << 24) | (mac[offset + 1] << 16) | (mac[offset + 2] << 8) | mac[offset + 3];
    let modulus = 10i64.pow(digits as u32);
    format!("{:0width$}", binary % modulus, width = digits as usize)
}

/// The RFC 4226 HOTP code for one counter value.
///
/// # Panics
/// Panics on a counter outside 0 to 2^53 - 1, digits other than 6-8, an
/// unknown algorithm, or a secret that is not base32 of at least 10 bytes.
pub fn hotp_code(secret: &str, counter: i64, digits: i64, algorithm: &str) -> String {
    if !is_totp_whole(counter) {
        panic!("counter must be a whole number from 0 to 2^53 - 1");
    }
    check_totp_digits(digits);
    check_totp_algorithm(algorithm);
    hotp_from_key(&totp_secret_key(secret), counter, digits, algorithm)
}

pub fn totp_text_arg(value: &Value, message: &str) -> String {
    match value {
        Value::Str(s) => s.clone(),
        _ => panic!("{}", message),
    }
}

pub fn totp_int_arg(value: &Value, message: &str) -> i64 {
    match value {
        Value::Int(i) => *i,
        _ => panic!("{}", message),
    }
}

pub fn totp_settings_from_value(value: &Value) -> TotpSettings {
    TotpSettings {
        algorithm: totp_text_arg(value.get("algorithm"), "algorithm must be SHA1 or SHA256"),
        digits: totp_int_arg(value.get("digits"), "digits must be 6, 7 or 8"),
        period: totp_int_arg(value.get("period"), "period must be a whole number of seconds, 1 or more"),
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&hotp_code(
        &totp_text_arg(&args[0], "base32 text must be a string"),
        totp_int_arg(&args[1], "counter must be a whole number from 0 to 2^53 - 1"),
        totp_int_arg(&args[2], "digits must be 6, 7 or 8"),
        &totp_text_arg(&args[3], "algorithm must be SHA1 or SHA256"),
    ))
}