Skip to main content

Totp

Struct Totp 

Source
pub struct Totp { /* private fields */ }

Implementations§

Source§

impl Totp

Source

pub fn new( alg: Algorithm, issuer: String, label: String, digits: u8, period: u64, secret: Secret, ) -> Self

Creates a new Totp instance with the specified configuration.

Internally, this wraps an Hotp instance and uses time-based counter calculations according to the specified period.

§Arguments
  • alg - The hashing algorithm to use (e.g., Algorithm::SHA1, Algorithm::SHA256, or Algorithm::SHA512).
  • issuer - The name of the service or provider (e.g., "GitHub" or "example.com").
  • label - An identifier for the user account (e.g., "alice@example.com").
  • digits - Number of digits in the generated OTP (typically 6 or 8).
  • period - Time step duration in seconds (usually 30).
  • secret - The shared secret key used to generate the HMAC.
§Returns

Returns a new instance of Totp configured with the provided parameters.

§Example
use otp::{Totp, Algorithm, Secret};

let totp = Totp::new(
    Algorithm::SHA1,
    "example".into(),
    "alice@example.com".into(),
    6,
    30,
    Secret::from_bytes(b"supersecret"),
);
Source

pub fn generate(&self) -> u32

Generates a TOTP code for the current system time using the configured algorithm and secret.

Internally, this method computes the number of time steps (counters) since the Unix epoch, and uses that to derive the OTP value.

§Returns

A numeric TOTP code as a u32.

§Panics

Panics if system time is before the Unix epoch.

§Example
let totp = otp::Totp::default();
let otp = totp.generate();
println!("OTP: {}", otp);
§References
Source

pub fn generate_at(&self, timestamp_secs: u64) -> u32

Generates a TOTP code for a specific timestamp (in seconds since Unix epoch).

This method is useful when simulating or verifying TOTP behavior for a given point in time.

§Arguments
  • timestamp_secs - The Unix timestamp in seconds
§Returns

A numeric TOTP code as a u32.

§Example
let totp = otp::Totp::default();
let otp = totp.generate_at(1_600_000_000); // fixed timestamp
§References
Source

pub fn verify(&self, otp: u32, timestamp_secs: u64, window: u64) -> bool

Verifies whether a given OTP is valid for a timestamp, within a configurable window.

This method accounts for small clock skews by checking OTP values generated before and after the given timestamp by a number of time steps defined by window.

§Arguments
  • otp - The OTP value to check
  • timestamp_secs - The Unix timestamp (in seconds) to check against
  • window - The allowed time-step drift (in units of period)
§Returns

true if the OTP is valid within the given window; otherwise, false.

§Example
let totp = otp::Totp::default();
let timestamp = 1_600_000_000;
let otp = totp.generate_at(timestamp);
assert!(totp.verify(otp, timestamp + 20, 1)); // within window
§References
Source

pub fn to_uri(&self) -> String

Generates a Key URI string in the format compatible with Google Authenticator and other TOTP/HOTP apps.

This URI can be encoded as a QR code and scanned by authenticator apps (e.g., Google Authenticator, Authy) to configure the OTP settings automatically.

The URI format follows the Key URI Format specification:

otpauth://TYPE/LABEL?PARAMETERS

For example, a TOTP URI might look like:

otpauth://totp/Example%3Aalice%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Example&algorithm=SHA1&digits=6&period=30
§Format Details
  • TYPE: Either totp or hotp
  • LABEL: Usually issuer:account, URL-encoded
  • secret: Base32-encoded secret key
  • issuer: The provider or service name (optional, but recommended)
  • algorithm: Hash function used (e.g., SHA1, SHA256, SHA512)
  • digits: Number of digits in the OTP (typically 6 or 8)
  • period (TOTP only): Time step in seconds (e.g., 30)
  • counter (HOTP only): Current counter value
§Returns

A String containing the otpauth:// URI.

§Example
use otp::{Totp, Algorithm, Secret};

let totp = Totp::new(
    Algorithm::SHA256,
    "Example".into(),
    "alice@example.com".into(),
    6,
    30,
    Secret::from_bytes(b"supersecretkey")
);

let uri = totp.to_uri();
assert!(uri.starts_with("otpauth://totp/"));
Source

pub fn alg(&self) -> Algorithm

Source

pub fn issuer(&self) -> &str

Source

pub fn label(&self) -> &str

Source

pub fn digits(&self) -> u8

Source

pub fn secret(&self) -> &Secret

Source

pub fn from_uri(uri: &str) -> Result<Self, ParseUriError>

Parses a TOTP configuration from a URI string in the Key URI Format.

This function supports URIs of the form: otpauth://totp/{label}?secret={secret}&issuer={issuer}&algorithm={algorithm}&digits={digits}&period={period}

§Arguments
  • uri - A string slice containing the TOTP URI.
§Returns

Returns Ok(Totp) if the URI is valid and can be parsed. Otherwise returns Err(Error) indicating the reason for failure.

§Errors

This method returns an error in the following cases:

  • URI does not start with the otpauth://totp/ scheme.
  • Missing or empty label in the URI.
  • Missing or invalid query parameters (e.g., secret).
  • Unsupported or invalid algorithm name.
  • Base32 decoding of the secret fails.
  • Convert string errors (e.g., period, digits).
  • Invalid percent-encoding in the label or issuer.
§Examples
use otp::Totp;

let uri = "otpauth://totp/example:alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=example&algorithm=SHA1&digits=6&period=30";
let totp = Totp::from_uri(uri).unwrap();
assert_eq!(totp.issuer(), "example");
assert_eq!(totp.label(), "alice@example.com");

Trait Implementations§

Source§

impl Default for Totp

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl Freeze for Totp

§

impl RefUnwindSafe for Totp

§

impl Send for Totp

§

impl Sync for Totp

§

impl Unpin for Totp

§

impl UnsafeUnpin 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> 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, 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.