# rust-otp

[](https://crates.io/crates/rust-otp)
`rust-otp` is a modern, flexible Rust library for performing the HMAC-based One-time Password Algorithm (HOTP) as per [RFC 4226](http://tools.ietf.org/html/rfc4226) and the Time-based One-time Password Algorithm (TOTP) as per [RFC 6238](http://tools.ietf.org/html/rfc6238).
## Features
- **Modern Builder API**: Easy and readable configuration for HOTP and TOTP.
- **Async Support**: Native `async` methods for seamless integration into modern runtimes.
- **Enhanced Security**: Support for SHA1, SHA256, and SHA512.
- **Formatted Output**: Direct support for zero-padded strings.
- **Zero Dependencies (core)**: Light-weight and secure.
## Installation
Add this to your `Cargo.toml`:
```toml
[dependencies]
rust-otp = "3.0.0"
```
To enable `async` support:
```toml
rust-otp = { version = "3.0.0", features = ["async"] }
```
## Usage
### TOTP (Time-based One-time Password)
```rust
use rust_otp::{TOTP, Algorithm};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Standard Google Authenticator configuration (30s step, 6 digits)
let totp = TOTP::builder()
.base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")?
.digits(6)
.build()?;
let code = totp.generate_current_formatted()?;
println!("Current TOTP code: {}", code);
Ok(())
}
```
### HOTP (HMAC-based One-time Password)
```rust
use rust_otp::{HOTP, Algorithm};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let hotp = HOTP::builder()
.base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")?
.algorithm(Algorithm::SHA256)
.digits(8)
.build()?;
let code = hotp.generate_formatted(1234);
println!("HOTP code at counter 1234: {}", code);
Ok(())
}
```
### Async Usage
```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let totp = TOTP::builder()
.base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")?
.build()?;
let code = totp.generate_current_formatted_async().await?;
println!("Async TOTP code: {}", code);
Ok(())
}
```
## Running Examples
You can run the provided examples using `cargo`:
```bash
# Run HOTP example
cargo run --example hotp
# Run TOTP example
cargo run --example totp
# Run Async TOTP example
cargo run --example async_totp --features async
```
## License
`rust-otp` is licensed under the [MIT license](http://opensource.org/licenses/MIT).
The full license is included in this repository in `LICENSE.md`.