pub struct Totp { /* private fields */ }Implementations§
Source§impl Totp
impl Totp
Sourcepub fn new(
alg: Algorithm,
issuer: String,
label: String,
digits: u8,
period: u64,
secret: Secret,
) -> Self
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, orAlgorithm::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"),
);Sourcepub fn generate(&self) -> u32
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
Sourcepub fn generate_at(&self, timestamp_secs: u64) -> u32
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
Sourcepub fn verify(&self, otp: u32, timestamp_secs: u64, window: u64) -> bool
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 checktimestamp_secs- The Unix timestamp (in seconds) to check againstwindow- The allowed time-step drift (in units ofperiod)
§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
Sourcepub fn to_uri(&self) -> String
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?PARAMETERSFor 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: EithertotporhotpLABEL: Usuallyissuer:account, URL-encodedsecret: Base32-encoded secret keyissuer: 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/"));pub fn alg(&self) -> Algorithm
pub fn issuer(&self) -> &str
pub fn label(&self) -> &str
pub fn digits(&self) -> u8
pub fn secret(&self) -> &Secret
Sourcepub fn from_uri(uri: &str) -> Result<Self, ParseUriError>
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");