### Generate TOTP with Generated Secret Source: https://github.com/constantoine/totp-rs/blob/master/README.md This example demonstrates generating a TOTP using a securely generated secret. It's equivalent to the default secret generation. Ensure the `gen_secret` feature is enabled. ```Rust use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::generate_secret().to_bytes().unwrap(), Some("Github".to_string()), "constantoine@github.com".to_string(), ).unwrap(); let qr_code = totp.get_qr_base64()?; println!("{}", qr_code); } ``` -------------------------------- ### Configure Cargo.toml Feature Flags Source: https://context7.com/constantoine/totp-rs/llms.txt Lists various dependency configurations for enabling specific features like QR code generation, Steam support, and serialization. ```toml # Cargo.toml # Minimal installation (no otpauth URL support) [dependencies] totp-rs = "5.7" # With otpauth URL parsing/generation [dependencies.totp-rs] version = "5.7" features = ["otpauth"] # With QR code generation (enables otpauth automatically) [dependencies.totp-rs] version = "5.7" features = ["qr"] # With secure random secret generation [dependencies.totp-rs] version = "5.7" features = ["gen_secret"] # With serde serialization support [dependencies.totp-rs] version = "5.7" features = ["serde_support"] # With Steam Guard support [dependencies.totp-rs] version = "5.7" features = ["steam"] # With secure memory zeroization [dependencies.totp-rs] version = "5.7" features = ["zeroize"] # Full-featured installation [dependencies.totp-rs] version = "5.7" features = ["otpauth", "qr", "gen_secret", "serde_support", "steam", "zeroize"] ``` -------------------------------- ### Generate QR Code for TOTP Source: https://github.com/constantoine/totp-rs/blob/master/README.md Generates a base64 encoded PNG QR code for a TOTP configuration. Requires the 'qr' feature to be enabled. ```Rust use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(), Some("Github".to_string()), "constantoine@github.com".to_string(), ).unwrap(); let qr_code = totp.get_qr_base64()?; println!("{}", qr_code); } ``` -------------------------------- ### Create RFC-6238 Compliant TOTP Instances Source: https://context7.com/constantoine/totp-rs/llms.txt Use the Rfc6238 builder to ensure standard-compliant digit counts, secret lengths, and step durations. ```rust use totp_rs::{Rfc6238, TOTP, Secret}; fn main() { // Create RFC-6238 compliant config with defaults (6 digits, 30s step, SHA1) let mut rfc = Rfc6238::with_defaults( Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()) .to_bytes() .unwrap(), ).unwrap(); // Optionally customize (still within RFC compliance) rfc.digits(8).unwrap(); // 6, 7, or 8 digits allowed rfc.issuer("MyService".to_string()); rfc.account_name("user@example.com".to_string()); // Convert to TOTP let totp = TOTP::from_rfc6238(rfc).unwrap(); let code = totp.generate_current().unwrap(); println!("8-digit code: {}", code); // Full custom RFC config let rfc_custom = Rfc6238::new( 7, // 7 digits "my-secret-key-1234".as_bytes().to_vec(), // At least 16 bytes (128 bits) Some("CustomIssuer".to_string()), "account@example.com".to_string(), ).unwrap(); let totp_custom = TOTP::from_rfc6238(rfc_custom).unwrap(); println!("Custom TOTP: {}", totp_custom.generate_current().unwrap()); } ``` -------------------------------- ### Generate QR Codes for TOTP Configuration Source: https://context7.com/constantoine/totp-rs/llms.txt Provides functionality to generate QR codes as base64-encoded PNGs or raw PNG bytes, facilitating easy integration with authenticator apps. ```rust use totp_rs::{TOTP, Algorithm, Secret}; fn main() { // Create TOTP with otpauth feature enabled (requires qr feature) let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()) .to_bytes() .unwrap(), Some("GitHub".to_string()), "constantoine@github.com".to_string(), ).unwrap(); // Generate QR code as base64-encoded PNG for embedding in HTML match totp.get_qr_base64() { Ok(base64_png) => { // Use in HTML: println!("QR Code (first 50 chars): {}...", &base64_png[..50]); } Err(e) => println!("Error generating QR: {}", e), } // Generate QR code as raw PNG bytes for file saving match totp.get_qr_png() { Ok(png_bytes) => { // Save to file or process as needed println!("QR PNG size: {} bytes", png_bytes.len()); // std::fs::write("totp_qr.png", png_bytes).unwrap(); } Err(e) => println!("Error generating QR: {}", e), } } ``` -------------------------------- ### Secret Raw vs Encoded Source: https://github.com/constantoine/totp-rs/blob/master/README.md Demonstrates the equivalence between Secret::Raw and Secret::Encoded types. ```Rust Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()) ``` ```Rust Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()) ``` -------------------------------- ### Generate TOTP with All Default Values Source: https://github.com/constantoine/totp-rs/blob/master/README.md This snippet generates a TOTP using all default values, including a secure secret. This is a convenient shortcut when no specific configuration is needed. ```Rust fn main() { let totp = TOTP::default(); let code = totp.generate_current().unwrap(); println!("code: {}", code); } ``` -------------------------------- ### Generate TOTP Tokens Source: https://context7.com/constantoine/totp-rs/llms.txt Generate TOTP tokens using either the current system time or a specific Unix timestamp. The `generate_current` method uses the system clock, while `generate` accepts any timestamp. ```rust use totp_rs::{Algorithm, TOTP, Secret}; use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()) .to_bytes() .unwrap(), Some("Github".to_string()), "constantoine@github.com".to_string(), ).unwrap(); // Generate token for current time let current_token = totp.generate_current().unwrap(); println!("Current token: {}", current_token); // Generate token for specific timestamp (Unix seconds) let token_at_1000 = totp.generate(1000); println!("Token at timestamp 1000: {}", token_at_1000); // Output: "659761" // Get timestamp when next token becomes valid let next_step = totp.next_step_current().unwrap(); println!("Next token at timestamp: {}", next_step); } ``` -------------------------------- ### Parse and Generate OTPAuth URLs Source: https://context7.com/constantoine/totp-rs/llms.txt Enables interoperability with authenticator apps by parsing standard otpauth:// URLs into TOTP objects and generating URLs for configuration. ```rust use totp_rs::{TOTP, Algorithm, Secret}; fn main() { // Parse otpauth URL from authenticator app (requires otpauth feature) let url = "otpauth://totp/GitHub:constantoine@github.com?secret=KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ&issuer=GitHub"; let totp = TOTP::from_url(url).unwrap(); println!("Issuer: {:?}", totp.issuer); // Output: Some("GitHub") println!("Account: {}", totp.account_name); // Output: "constantoine@github.com" println!("Algorithm: {:?}", totp.algorithm); // Output: SHA1 println!("Digits: {}", totp.digits); // Output: 6 println!("Step: {}", totp.step); // Output: 30 // Generate current token let token = totp.generate_current().unwrap(); println!("Token: {}", token); // Generate otpauth URL from TOTP object let new_totp = TOTP::new( Algorithm::SHA256, 8, 1, 60, Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()) .to_bytes() .unwrap(), Some("MyApp".to_string()), "user@example.com".to_string(), ).unwrap(); let generated_url = new_totp.get_url(); println!("OTPAuth URL: {}", generated_url); // Output: otpauth://totp/MyApp:user%40example.com?secret=KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ&digits=8&algorithm=SHA256&issuer=MyApp&period=60 } ``` -------------------------------- ### Create TOTP Struct with Raw Secret Source: https://context7.com/constantoine/totp-rs/llms.txt Instantiate the TOTP struct using raw secret bytes. Requires the 'otpauth' feature for issuer and account name. Ensure correct algorithm, digit count, skew, and step duration are provided. ```rust use totp_rs::{Algorithm, TOTP, Secret}; fn main() { // Create TOTP with raw secret bytes let totp = TOTP::new( Algorithm::SHA1, // Hash algorithm (SHA1, SHA256, SHA512) 6, // Number of digits (6-8) 1, // Skew - allows 1 step before/after current time 30, // Step duration in seconds Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()) .to_bytes() .unwrap(), Some("MyService".to_string()), // Issuer (requires otpauth feature) "user@example.com".to_string(), // Account name (requires otpauth feature) ).unwrap(); // Generate current token let token = totp.generate_current().unwrap(); println!("Current TOTP: {}", token); // Output: 6-digit code like "123456" // Check remaining time for current token let ttl = totp.ttl().unwrap(); println!("Token valid for {} more seconds", ttl); } ``` -------------------------------- ### Generate TOTP with Default Secret Source: https://github.com/constantoine/totp-rs/blob/master/README.md Use this when you need a TOTP with default settings and a securely generated secret. Ensure the `gen_secret` feature is enabled. ```Rust use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::default().to_bytes().unwrap(), Some("Github".to_string()), "constantoine@github.com".to_string(), ).unwrap(); let qr_code = totp.get_qr_base64()?; println!("{}", qr_code); } ``` -------------------------------- ### Handle TOTP Errors in Rust Source: https://context7.com/constantoine/totp-rs/llms.txt Demonstrates matching against specific error types like invalid digit counts, secret size constraints, and URL parsing failures. ```rust use totp_rs::{TOTP, Algorithm, Secret, TotpUrlError, Rfc6238Error}; fn main() { // Invalid digit count (must be 6-8) let result = TOTP::new( Algorithm::SHA1, 5, // Invalid: too few digits 1, 30, "TestSecretSuperSecret".as_bytes().to_vec(), Some("Service".to_string()), "user@example.com".to_string(), ); match result { Err(TotpUrlError::DigitsNumber(digits)) => { println!("Invalid digits: {}", digits); } _ => {} } // Secret too small (must be at least 128 bits / 16 bytes) let result = TOTP::new( Algorithm::SHA1, 6, 1, 30, "short".as_bytes().to_vec(), // Only 5 bytes Some("Service".to_string()), "user@example.com".to_string(), ); match result { Err(TotpUrlError::SecretSize(bits)) => { println!("Secret too small: {} bits (need 128+)", bits); } _ => {} } // Invalid otpauth URL let result = TOTP::from_url("https://invalid.com/not-otpauth"); match result { Err(TotpUrlError::Scheme(scheme)) => { println!("Wrong scheme: {} (expected 'otpauth')", scheme); } _ => {} } // Invalid base32 secret let result = Secret::Encoded("not-valid-base32!!!".to_string()).to_bytes(); match result { Err(e) => println!("Secret parse error: {}", e), _ => {} } // Issuer/account_name containing colon let result = TOTP::new( Algorithm::SHA1, 6, 1, 30, "TestSecretSuperSecret".as_bytes().to_vec(), Some("Invalid:Issuer".to_string()), // Colon not allowed "user@example.com".to_string(), ); match result { Err(TotpUrlError::Issuer(issuer)) => { println!("Invalid issuer: {}", issuer); } _ => {} } } ``` -------------------------------- ### Select TOTP Hash Algorithms Source: https://context7.com/constantoine/totp-rs/llms.txt Configure TOTP to use SHA1, SHA256, or SHA512. Note that SHA1 is the most widely supported algorithm for authenticator apps. ```rust use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let secret = Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()) .to_bytes() .unwrap(); // SHA1 - Default, most widely supported let totp_sha1 = TOTP::new( Algorithm::SHA1, 6, 1, 30, secret.clone(), Some("Service".to_string()), "user@example.com".to_string(), ).unwrap(); // SHA256 - Stronger but less compatible let totp_sha256 = TOTP::new( Algorithm::SHA256, 6, 1, 30, secret.clone(), Some("Service".to_string()), "user@example.com".to_string(), ).unwrap(); // SHA512 - Strongest but least compatible let totp_sha512 = TOTP::new( Algorithm::SHA512, 6, 1, 30, secret.clone(), Some("Service".to_string()), "user@example.com".to_string(), ).unwrap(); // Same timestamp, different tokens per algorithm let timestamp = 1000u64; println!("SHA1: {}", totp_sha1.generate(timestamp)); // Output: "659761" println!("SHA256: {}", totp_sha256.generate(timestamp)); // Output: "076417" println!("SHA512: {}", totp_sha512.generate(timestamp)); // Output: "473536" // Recommendation: Use SHA1 for maximum compatibility println!("Default algorithm: {:?}", Algorithm::default()); // Output: SHA1 } ``` -------------------------------- ### Parse otpauth URL to TOTP Source: https://github.com/constantoine/totp-rs/blob/master/README.md Parses an otpauth URL to create a TOTP object. This requires the 'otpauth' feature to be enabled. ```Rust use totp_rs::TOTP; fn main() { let otpauth = "otpauth://totp/GitHub:constantoine@github.com?secret=KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ&issuer=GitHub"; let totp = TOTP::from_url(otpauth).unwrap(); println!("{}", totp.generate_current().unwrap()); } ``` -------------------------------- ### Verify TOTP Tokens Source: https://context7.com/constantoine/totp-rs/llms.txt Validate user-submitted TOTP tokens against the expected value, considering the configured time skew. The `check_current` method verifies against the system time, while `check` verifies against a specific timestamp. ```rust use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, // Skew of 1 allows +-1 time step 30, Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()) .to_bytes() .unwrap(), Some("MyApp".to_string()), "user@example.com".to_string(), ).unwrap(); // Verify against current system time let user_token = "123456"; match totp.check_current(user_token) { Ok(true) => println!("Token valid!"), Ok(false) => println!("Token invalid!"), Err(e) => println!("Error checking token: {}", e), } // Verify against specific timestamp let is_valid = totp.check("659761", 1000); println!("Token '659761' at timestamp 1000: {}", is_valid); // Output: true // With skew=1, tokens from adjacent time steps are also valid // At timestamp 1000: tokens for 999, 1000, and 1001 are all accepted assert!(totp.check("174269", 1000)); // Previous step assert!(totp.check("659761", 1000)); // Current step assert!(totp.check("260393", 1000)); // Next step } ``` -------------------------------- ### Generate TOTP with RFC-6238 Defaults Source: https://github.com/constantoine/totp-rs/blob/master/README.md Create a TOTP object using RFC-6238 defaults, including a secure secret. You can optionally set the number of digits. ```Rust use totp_rs::{Algorithm, TOTP, Secret, Rfc6238}; fn main () { let mut rfc = Rfc6238::with_defaults( Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(), ) .unwrap(); // optional, set digits rfc.digits(8).unwrap(); // create a TOTP from rfc let totp = TOTP::from_rfc6238(rfc).unwrap(); let code = totp.generate_current().unwrap(); println!("code: {}", code); } ``` -------------------------------- ### Handle Secrets for TOTP Generation Source: https://context7.com/constantoine/totp-rs/llms.txt Demonstrates using the Secret enum for raw bytes or base32 strings. Secrets can be converted to bytes for TOTP creation and generated securely. ```rust use totp_rs::{Secret, TOTP, Algorithm}; fn main() { // Raw secret from bytes let secret_raw = Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()); // Base32-encoded secret (common format from authenticator apps) let secret_encoded = Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()); // Both represent the same secret assert_eq!(secret_raw.to_bytes().unwrap(), secret_encoded.to_bytes().unwrap()); // Convert between formats let encoded_version = secret_raw.to_encoded(); let raw_version = secret_encoded.to_raw().unwrap(); // Generate a cryptographically secure random secret (requires gen_secret feature) // let generated_secret = Secret::generate_secret(); // let generated_secret = Secret::default(); // Also generates a random secret // Get base32 representation from TOTP for manual entry let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, secret_raw.to_bytes().unwrap(), Some("MyService".to_string()), "user@example.com".to_string(), ).unwrap(); let base32_secret = totp.get_secret_base32(); println!("Base32 secret for manual entry: {}", base32_secret); // Output: "KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ" } ``` -------------------------------- ### Generate Steam Guard TOTP Tokens Source: https://context7.com/constantoine/totp-rs/llms.txt Generate 5-character alphanumeric tokens compatible with Steam Guard. Requires the 'steam' feature enabled. ```rust use totp_rs::{TOTP, Secret}; fn main() { // Create Steam TOTP (requires steam feature) let totp = TOTP::new_steam( Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()) .to_bytes() .unwrap(), "steam_username".to_string(), ); // Steam tokens are 5 alphanumeric characters let steam_code = totp.generate_current().unwrap(); println!("Steam Guard code: {}", steam_code); // Output: e.g., "2BXYZ" // Steam TOTP uses special alphabet: 23456789BCDFGHJKMNPQRTVWXY // Algorithm is SHA1-based with Steam-specific encoding // Get otpauth URL for Steam let url = totp.get_url(); println!("Steam URL: {}", url); // Output: otpauth://steam/Steam:steam_username?secret=...&digits=5&algorithm=SHA1&issuer=Steam // Parse Steam URL let parsed = TOTP::from_url( "otpauth://steam/Steam:username?secret=KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ" ).unwrap(); println!("Parsed Steam code: {}", parsed.generate_current().unwrap()); } ``` -------------------------------- ### Generate TOTP Token (Raw Secret) Source: https://github.com/constantoine/totp-rs/blob/master/README.md Generates a current TOTP token using a raw secret. Ensure the secret is correctly formatted before use. ```Rust use std::time::SystemTime; use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::Raw("TestSecretSuperSecret".as_bytes().to_vec()).to_bytes().unwrap(), ).unwrap(); let token = totp.generate_current().unwrap(); println!("{}", token); } ``` -------------------------------- ### Generate TOTP from Steam Secret Source: https://github.com/constantoine/totp-rs/blob/master/README.md Use this method to generate a TOTP code specifically from a Steam authenticator secret. Ensure the `steam` feature is enabled. ```Rust use totp_rs::{TOTP, Secret}; fn main() { let totp = TOTP::new_steam( Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(), ).unwrap(); let code = totp.generate_current().unwrap(); println!("code: {}", code); } ``` -------------------------------- ### Generate TOTP Token (Encoded Secret) Source: https://github.com/constantoine/totp-rs/blob/master/README.md Generates a current TOTP token using a base32 encoded secret. This is equivalent to using Secret::Raw. ```Rust use std::time::SystemTime; use totp_rs::{Algorithm, TOTP, Secret}; fn main() { let totp = TOTP::new( Algorithm::SHA1, 6, 1, 30, Secret::Encoded("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ".to_string()).to_bytes().unwrap(), ).unwrap(); let token = totp.generate_current().unwrap(); println!("{}", token); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.