A Rust implementation the HOTP and TOTP Algorithms

Overview

xotp

crate xotp License: MIT

A Rust implementation the HOTP and TOTP Algorithms.

  • HOTP was implemented in accordance with RFC4226
  • TOTP was implemented in accordance with RFC6238

Usage

To use HOTP:

use xotp::hotp::HOTP;

fn get_otp_with_hotp() {
    let secret = "secret";
    let counter = 0;
    // Get a HOTP instance with a '&str' secret
    let hotp_str = HOTP::from_utf8(secret);
    // Get an otp with the given counter and digit count
    let otp_from_str = hotp_str.get_otp(counter, 6);
    println!("The otp from hotp_str: {}", otp_from_str);
    
    // Alternatively, get a HOTP instance with a '&[u8]' secret
    let hotp_bytes = HOTP::new(secret.as_bytes());
    // Get an otp with the given counter and digit count
    let otp_from_bytes = hotp_bytes.get_otp(counter, 6);
    println!("The otp from hotp_bytes: {}", otp_from_bytes);
} 

To use TOTP:

use xotp::totp::TOTP;
use xotp::util::MacDigest;
// Only needed if using a non-SHA1 hash function
use std::time::{Duration, SystemTime, UNIX_EPOCH};

fn get_otp_with_totp() {
    let secret = "secret";
    let elapsed_seconds = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .expect("Error getting time")
        .as_secs();
    // Get a TOTP instance a '&str' secret and default SHA1 Digest
    let totp_sha1_str = TOTP::from_utf8(secret);
    // Get an otp with the given counter and elapsed seconds 
    let otp_sha1 = totp_sha1_str.get_otp(elapsed_seconds, 8);
    println!("The otp from totp_sha1_str: {}", otp_sha1);

    // Alternatively get a TOTP instance with a '&[u8]' secret
    // and different digest (Sha256 or Sha512)
    let totp_sha256_bytes = TOTP::new_with_digest(
        secret.as_bytes(),
        MacDigest::SHA256
    );
    // Get an otp with the given counter, time and other custom params
    let otp_sha256 = totp_sha256_bytes.get_otp_with_custom(
        elapsed_seconds,
        30, // A 60-second time step
        0, // Start time at unix epoch
        6 // 8-digit code
    );
    println!("The otp from totp_sha256_bytes: {}", otp_sha256);
}

Changelog

The changelog for this crate can be found at CHANGELOG.md

Features and Bugs

Please file any featre requests or bug reports through the issue tracker

Licensing

Comments
  • Leading zeroes

    Leading zeroes

    I use the crate for a keepass TOTP app and I have a little issue with leading zeroes.

    otp_gen

    When you have the result of the get_otp, you don't really know how to format the string to have the correct number of leading 0.

    I suggest that get_otp returns a struct that contains the otp, the number of digits and the duration before next refresh and has methods like get_as_integer and get_as_string in particular that return a string with the correct number of leading zeroes.

    opened by orion78fr 6
  • Optauth URI parser ?

    Optauth URI parser ?

    What do you think about an otpauth uri parser ? https://github.com/google/google-authenticator/wiki/Key-Uri-Format

    Seems like an easy-enough task, I may be able to write a PR for it if you want (disclaimer: I'm a rust beginner). Like a function in the util mod that takes a &str of the uri and give back an enum of TOTP, HOTP or Error message.

    Edit : By the way, this may need to move the digits & step to the TOTP struct, as these are constants for the TOTP generation.

    opened by orion78fr 6
  • Otpauth URI parser

    Otpauth URI parser

    ~~Still WIP~~ but seems to work. Moved digits & period to TOTP / HOTP structs. ~~TOTP tests currently fails because I haven't wrote the new constructors.~~ ~~Doc is missing / inaccurate in some parts.~~

    opened by orion78fr 1
  • Add in the `time_until_refresh` method to the TOTP struct

    Add in the `time_until_refresh` method to the TOTP struct

    Adds in the time_until_refresh method to the TOTP struct, along with a time_until_refresh_with_start method if a start offset is desired.

    This is the second part of the requested functionality from #4

    opened by tmthecoder 0
  • Add a shared `OTPResult` struct

    Add a shared `OTPResult` struct

    As mentioned in #4, it's convenient to have a method that formats the OTP for you with leading zeroes. To provide that functionality, all OTP getters now return an instance of OTPResult, which contains both an as_string or as_u32 method to retrieve the code in the desired format.

    This PR adds in that functionality.

    opened by tmthecoder 0
  • Compilation error in current rust version

    Compilation error in current rust version

    Just doing git clone "https://github.com/tmthecoder/xotp.git"; cd xotp; cargo test gives me errors:

    % cargo test
       Compiling xotp v0.4.0 (/home/geher/SonstigesSSD/Projects/xotp)
    error[E0277]: the trait bound `D: InnerInit` is not satisfied
      --> src/util.rs:66:20
       |
    66 |     let mut hmac = <D>::new_from_slice(secret).expect("Failed to initialize HMAC");
       |                    ^^^^^^^^^^^^^^^^^^^ the trait `InnerInit` is not implemented for `D`
       |
       = note: required because of the requirements on the impl of `KeyInit` for `D`
    note: required by a bound in `hmac::Mac::new_from_slice`
      --> /home/geher/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/digest-0.10.5/src/mac.rs:35:15
       |
    35 |         Self: KeyInit;
       |               ^^^^^^^ required by this bound in `hmac::Mac::new_from_slice`
    help: consider further restricting this bound
       |
    65 | fn hash_internal<D: Mac + hmac::digest::InnerInit>(msg: &[u8], secret: &[u8]) -> Vec<u8> {
       |                         +++++++++++++++++++++++++
    
    For more information about this error, try `rustc --explain E0277`.
    error: could not compile `xotp` due to previous error
    warning: build failed, waiting for other jobs to finish...
    error: build failed
    

    I'm using

    % cargo version
    cargo 1.60.0-nightly (95bb3c92b 2022-01-18)
    
    opened by BoostCookie 0
  • Add WASM support

    Add WASM support

    WIP: Rust currently doesn't allow for target-specific crate-type settings in the Cargo.toml, so this PR is halted until a CLI or config option becomes available.

    Add support to deploy this crate as a WASM library.

    All existing implementations seem to work fine with the #[wasm_bindgen] annotation with the exception of the parse_otpauth_uri as wasm_bindgen doesn't support non-C-style enums.

    I've currently added a WASM-only workaround.

    Functionality is still untested.

    opened by tmthecoder 0
Releases(v0.4.0)
  • v0.4.0(Jan 29, 2022)

    • Breaking Change the HOTP & TOTP OTP getter methods to return an instance of OTPResult instead of u32
      • Made in order to allow for the as_string convenience formatter that provides a correct length zero-padded string
      • The u32 representation of the code can also be returned with as_u32 if desired
    • Add in time_until_refresh and time_until_refresh_with_start to provide a convenient way to get time until a refresh is needed
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Jan 27, 2022)

  • v0.2.0(Jan 26, 2022)

  • v0.1.0(Jan 26, 2022)

Owner
Tejas Mehta
Avid Flutter/Dart Developer. I love to learn new languages and pick up new skills. Currently working on blinkOS and CrossClip
Tejas Mehta
A browser app that evolves vehicles using genetic algorithms, written in Rust and Bevy

Vehicle Evolver Deluxe This is a simulation that uses AI (to be specific: genetic algorithms) to try to build better and better vehicles. The vehicles

null 95 Dec 26, 2022
Common data structures and algorithms for competitive programming in Rust

algorithm-rs algorithm-rs is common data structures and algorithms for competitive programming in Rust. Contents TBA How To Contribute Contributions a

Chris Ohk 16 Dec 21, 2022
zine/book about bitmap drawing algorithms and math with code examples in Rust

A Bitmapper's Companion - zine/book about bitmap drawing algorithms and math with code examples in Rust A small zine/book written in LaTeX. In progres

Manos Pitsidianakis 42 Nov 8, 2022
This library provides implementations of many algorithms and data structures that are useful for bioinformatics.

This library provides implementations of many algorithms and data structures that are useful for bioinformatics. All provided implementations are rigorously tested via continuous integration.

Rust-Bio 1.2k Dec 26, 2022
darwin-rs, evolutionary algorithms with rust

darwin-rs This library allows you to write evolutionary algorithms (EA) using the Rust programming language. Written by Willi Kappler, License: MIT -

Willi Kappler 95 Jan 1, 2023
A tool used to evaluate the output of retrieval algorithms. Written in Rust.

Rusteval A tool used to evaluate the output of retrieval algorithms. Written in Rust. Building Install Rust with curl -sSf https://static.rust-lang.or

Giorgos Sfikas 17 Mar 22, 2022
This crate implements fast route planning algorithms in Rust.

This crate implements fast route planning algorithms in Rust. Algorithms Currently implemented: Contraction Hierarchies: The implementat

Payas Rajan 4 Aug 15, 2021
"Algorithms for approximate string matching" in Rust, with Python bindings.

ukkonen Implementation of a bounded Levenshtein distance by Esko Ukkonen in "Algorithms for approximate string matching" in Rust, with Python bindings

Ethan Smith 1 Dec 1, 2021
Algorithms implemented in Rust, explained.

Rusty Algorithms & Data Structures for Learners This repository presents Rust implementations of common algorithms and data structures, many of which

Tianyi Shi 327 Dec 19, 2022
Bandit Algorithms in Rust

Multi-armed bandit algorithms in Rust Cargo [dependencies] bandit = "0.12.3" Description and Scope This library currently only implements the annealin

Michael Bohn 30 Nov 24, 2022
Radiate is a parallel genetic programming engine capable of evolving solutions to many problems as well as training learning algorithms.

Radiate Coming from Evolutionary Radiation. Evolutionary radiation is a rapid increase in the number of species with a common ancestor, characterized

kalivas 109 Dec 18, 2022
Compare binary files using alignment algorithms

biodiff Compare binary files using alignment algorithms. What is this This is a tool for binary diffing. The tool is able to show two binary files sid

null 483 Dec 22, 2022
Genetic Algorithms Library

genx genx provides modular building blocks to run simulations of optimization and search problems using Genetic Algorithms (GA). The vision for genx i

Lakshya Singh 29 Aug 9, 2022
DSP algorithms for embedded. Often integer math.

This crate contains some tuned DSP algorithms for general and especially embedded use.

QUARTIQ 12 Nov 3, 2022
ECFFT algorithms on the BN254 base field

ECFFT algorithms on the BN254 base field This crate implements structs and traits for the ECFFT algorithms from the paper Elliptic Curve Fast Fourier

null 36 Nov 28, 2022
A library that can be used as a building block for high-performant graph algorithms.

graph A library that can be used as a building block for high-performant graph algorithms. Graph provides implementations for directed and undirected

Martin Junghanns 222 Jan 1, 2023
A small collection of procedural dungeon generation algorithms.

mapgen A small collection of procedural dungeon generation algorithms. Built with Rust & macroquad. WebAssembly build deployed here. Animated version

null 16 Aug 17, 2022
Rust implementation of real-coded GA for solving optimization problems and training of neural networks

revonet Rust implementation of real-coded genetic algorithm for solving optimization problems and training of neural networks. The latter is also know

Yury Tsoy 19 Aug 11, 2022
Raft implementation in Rust

rsraft Raft implementation in Rust. The aim of this project is implementing the Raft Consensus Algorithm as described in the paper, with the goal of f

Lauro Caetano 42 Dec 24, 2022