Struct totp_sos::TOTP

source ·
pub struct TOTP {
    pub algorithm: Algorithm,
    pub digits: usize,
    pub skew: u8,
    pub step: u64,
    pub secret: Vec<u8>,
    pub account_name: String,
    pub issuer: Option<String>,
}
Expand description

TOTP holds informations as to how to generate an auth code and validate it. Its secret field is sensitive data, treat it accordingly

Fields§

§algorithm: Algorithm

SHA-1 is the most widespread algorithm used, and for totp pursposes, SHA-1 hash collisions are not a problem as HMAC-SHA-1 is not impacted. It’s also the main one cited in rfc-6238 even though the reference implementation permits the use of SHA-1, SHA-256 and SHA-512.

Not all clients support other algorithms then SHA-1

§digits: usize

The number of digits for the auth code.

Per rfc-4226, this can be in the range between 6 and 8 digits

§skew: u8

Number of steps allowed as network delay.

One would mean one step before current step and one step after are valid.

The recommended value per rfc-6238 is 1. Anything more is sketchy and should not be used.

§step: u64

Duration in seconds of a step.

The recommended value per rfc-6238 is 30 seconds

§secret: Vec<u8>

As per rfc-4226 the secret should come from a strong source, most likely a CSPRNG.

It should be at least 128 bits, but 160 are recommended.

§account_name: String

The account name, typically either an email address or username.

The “mock@example.com” part of “Github:mock@example.com”.

Must not contain a colon :.

§issuer: Option<String>

The name of your service/website.

The “Github” part of “Github:mock@example.com”.

Must not contain a colon :.

Implementations§

source§

impl TOTP

source

pub fn new( algorithm: Algorithm, digits: usize, skew: u8, step: u64, secret: Vec<u8>, account_name: String, issuer: Option<String> ) -> Result<TOTP>

Create a new instance of TOTP with given parameters.

See the doc for reference as to how to choose those values.

  • digits: MUST be between 6 & 8
  • secret: Must have bitsize of at least 128
  • account_name: Must not contain :
  • issuer: Must not contain :
Examples found in repository?
examples/ttl.rs (lines 4-12)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    let totp = TOTP::new(
        Algorithm::SHA1,
        6,
        1,
        30,
        "ThisIsAnExampleSecretWithEnoughBytes".as_bytes().to_vec(),
        "mock@example.com".to_string(),
        Some("Github".to_string()),
    )
    .unwrap();

    loop {
        println!(
            "code {}\t ttl {}\t valid until: {}",
            totp.generate_current().unwrap(),
            totp.ttl().unwrap(),
            totp.next_step_current().unwrap()
        );
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}
source

pub fn sign(&self, time: u64) -> Vec<u8>

Sign the given timestamp

source

pub fn generate(&self, time: u64) -> String

Generate a token given the provided timestamp in seconds

source

pub fn next_step(&self, time: u64) -> u64

Returns the timestamp of the first second for the next step given the provided timestamp in seconds

source

pub fn next_step_current(&self) -> Result<u64>

Returns the timestamp of the first second of the next step According to system time

Examples found in repository?
examples/ttl.rs (line 20)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    let totp = TOTP::new(
        Algorithm::SHA1,
        6,
        1,
        30,
        "ThisIsAnExampleSecretWithEnoughBytes".as_bytes().to_vec(),
        "mock@example.com".to_string(),
        Some("Github".to_string()),
    )
    .unwrap();

    loop {
        println!(
            "code {}\t ttl {}\t valid until: {}",
            totp.generate_current().unwrap(),
            totp.ttl().unwrap(),
            totp.next_step_current().unwrap()
        );
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}
source

pub fn ttl(&self) -> Result<u64>

Give the ttl (in seconds) of the current token

Examples found in repository?
examples/ttl.rs (line 19)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    let totp = TOTP::new(
        Algorithm::SHA1,
        6,
        1,
        30,
        "ThisIsAnExampleSecretWithEnoughBytes".as_bytes().to_vec(),
        "mock@example.com".to_string(),
        Some("Github".to_string()),
    )
    .unwrap();

    loop {
        println!(
            "code {}\t ttl {}\t valid until: {}",
            totp.generate_current().unwrap(),
            totp.ttl().unwrap(),
            totp.next_step_current().unwrap()
        );
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}
source

pub fn generate_current(&self) -> Result<String>

Generate a token from the current system time

Examples found in repository?
examples/ttl.rs (line 18)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    let totp = TOTP::new(
        Algorithm::SHA1,
        6,
        1,
        30,
        "ThisIsAnExampleSecretWithEnoughBytes".as_bytes().to_vec(),
        "mock@example.com".to_string(),
        Some("Github".to_string()),
    )
    .unwrap();

    loop {
        println!(
            "code {}\t ttl {}\t valid until: {}",
            totp.generate_current().unwrap(),
            totp.ttl().unwrap(),
            totp.next_step_current().unwrap()
        );
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}
source

pub fn check(&self, token: &str, time: u64) -> bool

Check if token is valid given the provided timestamp in seconds, accounting skew

source

pub fn check_current(&self, token: &str) -> Result<bool>

Check if token is valid by current system time, accounting skew.

source

pub fn to_secret_base32(&self) -> String

Return the base32 representation of the secret, which might be useful when users want to manually add the secret to their authenticator.

source

pub fn from_secret_base32<S: AsRef<str>>(secret: S) -> Result<TOTP>

Convert a base32 secret into a TOTP.

The account name is the empty string and the issuer is None; so you should set them explicitly after decoding the secret bytes.

source

pub fn from_url<S: AsRef<str>>(url: S) -> Result<TOTP>

Generate a TOTP from the standard otpauth URL

source

pub fn get_url(&self) -> String

Generate a standard URL used to automatically add TOTP auths.

Usually used with a QR code.

Label and issuer will be URL-encoded; the secret will be converted to base32 without padding, as per the RFC.

Trait Implementations§

source§

impl Clone for TOTP

source§

fn clone(&self) -> TOTP

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for TOTP

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for TOTP

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Drop for TOTP

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl PartialEq<TOTP> for TOTP

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Serialize for TOTP

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Zeroize for TOTP

source§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.

Auto Trait Implementations§

§

impl RefUnwindSafe for TOTP

§

impl Send for TOTP

§

impl Sync for TOTP

§

impl Unpin for TOTP

§

impl UnwindSafe for TOTP

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,