Struct TOTP

Source
pub struct TOTP {
    pub algorithm: Algorithm,
    pub digits: usize,
    pub skew: u8,
    pub step: u64,
    pub secret: Vec<u8>,
    pub issuer: Option<String>,
    pub account_name: 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 composing the auth code. Per rfc-4226, this can oscilate between 6 and 8 digits

§skew: u8

Number of steps allowed as network delay. 1 would mean one step before current step and one step after are valids. The recommended value per rfc-6238 is 1. Anything more is sketchy, and anyone recommending more is, by definition, ugly and stupid

§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

non-encoded value

§issuer: Option<String>

The “Github” part of “Github:[email protected]”. Must not contain a colon : For example, the name of your service/website. Not mandatory, but strongly recommended!

§account_name: String

The “[email protected]” part of “Github:[email protected]”. Must not contain a colon : For example, the name of your user’s account.

Implementations§

Source§

impl TOTP

Source

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

Will create a new instance of TOTP with given parameters. See the doc for reference as to how to choose those values

§Description
  • secret: expect a non-encoded value, to pass in base32 string use Secret::Encoded(String)
  • digits: MUST be between 6 & 8
  • secret: Must have bitsize of at least 128
  • account_name: Must not contain :
  • issuer: Must not contain :
§Example
use totp_rs::{Secret, TOTP, Algorithm};
let secret = Secret::Encoded("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG".to_string());
let totp = TOTP::new(Algorithm::SHA1, 6, 1, 30, secret.to_bytes().unwrap(), None, "".to_string()).unwrap();
§Errors

Will return an error if the digit or secret size is invalid or if issuer or label contain the character ‘:’

Source

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

Will create a new instance of TOTP with given parameters. See the doc for reference as to how to choose those values. This is unchecked and does not check the digits and secret size

§Description
  • secret: expect a non-encoded value, to pass in base32 string use Secret::Encoded(String)
§Example
use totp_rs::{Secret, TOTP, Algorithm};
let secret = Secret::Encoded("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG".to_string());
let totp = TOTP::new_unchecked(Algorithm::SHA1, 6, 1, 30, secret.to_bytes().unwrap(), None, "".to_string());
Source

pub fn from_rfc6238(rfc: Rfc6238) -> Result<TOTP, TotpUrlError>

Will create a new instance of TOTP from the given Rfc6238 struct

§Errors

Will return an error in case issuer or label contain the character ‘:’

Source

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

Will sign the given timestamp

Source

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

Will 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, SystemTimeError>

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

Source

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

Give the ttl (in seconds) of the current token

Source

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

Generate a token from the current system time

Source

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

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

Source

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

Will check if token is valid by current system time, accounting skew

Source

pub fn get_secret_base32(&self) -> String

Will 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_url<S: AsRef<str>>(url: S) -> Result<TOTP, TotpUrlError>

Generate a TOTP from the standard otpauth URL

Source

pub fn from_url_unchecked<S: AsRef<str>>(url: S) -> Result<TOTP, TotpUrlError>

Generate a TOTP from the standard otpauth URL, using TOTP::new_unchecked internally

Source

pub fn get_url(&self) -> String

Will generate a standard URL used to automatically add TOTP auths. Usually used with qr codes

Label and issuer will be URL-encoded if needed be Secret will be base 32’d without padding, as per RFC.

Source§

impl TOTP

Source

pub fn get_qr(&self) -> Result<String, String>

👎Deprecated since 5.3.0: get_qr was forcing the use of png as a base64. Use get_qr_base64 or get_qr_png instead. Will disappear in 6.0.
Source

pub fn get_qr_base64(&self) -> Result<String, String>

Will return a qrcode to automatically add a TOTP as a base64 string. Needs feature qr to be enabled! Result will be in the form of a string containing a base64-encoded png, which you can embed in HTML without needing To store the png as a file.

§Errors

This will return an error in case the URL gets too long to encode into a QR code. This would require the get_url method to generate an url bigger than 2000 characters, Which would be too long for some browsers anyway.

It will also return an error in case it can’t encode the qr into a png. This shouldn’t happen unless either the qrcode library returns malformed data, or the image library doesn’t encode the data correctly

Source

pub fn get_qr_png(&self) -> Result<Vec<u8>, String>

Will return a qrcode to automatically add a TOTP as a byte array. Needs feature qr to be enabled! Result will be in the form of a png file as bytes.

§Errors

This will return an error in case the URL gets too long to encode into a QR code. This would require the get_url method to generate an url bigger than 2000 characters, Which would be too long for some browsers anyway.

It will also return an error in case it can’t encode the qr into a png. This shouldn’t happen unless either the qrcode library returns malformed data, or the image library doesn’t encode the data correctly

Trait Implementations§

Source§

impl Clone for TOTP

Source§

fn clone(&self) -> TOTP

Returns a duplicate 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 Default for TOTP

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for TOTP

Source§

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

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

impl PartialEq for TOTP

Source§

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

Will not check for issuer and account_name equality As they aren’t taken in account for token generation/token checking

1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl TryFrom<Rfc6238> for TOTP

Source§

fn try_from(rfc: Rfc6238) -> Result<Self, Self::Error>

Try to create a TOTP from a Rfc6238 config.

Source§

type Error = TotpUrlError

The type returned in the event of a conversion error.

Auto Trait Implementations§

§

impl Freeze for TOTP

§

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 T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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 T
where 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 for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

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 T
where U: TryFrom<T>,

Source§

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> ErasedDestructor for T
where T: 'static,