rust-otp 3.0.0

A modern Rust library for performing the HMAC-based One-Time Password (HOTP) and Time-based One-Time Password (TOTP) algorithms with async support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use data_encoding::{DecodeError, BASE32};
use ring::hmac;
use std::time::{SystemTime, SystemTimeError};
use thiserror::Error;

/// Decodes a base32 string, handling both padded and unpadded input.
fn decode_base32(input: &str) -> Result<Vec<u8>, DecodeError> {
    let input = input.trim();
    if input.contains('=') {
        BASE32.decode(input.as_bytes())
    } else {
        // If no padding is present, we might need to add it or use a nopad decoder.
        // data-encoding's BASE32 is strict. Let's add padding if needed.
        let mut padded = input.to_string();
        while padded.len() % 8 != 0 {
            padded.push('=');
        }
        BASE32.decode(padded.as_bytes())
    }
}

#[derive(Debug, Error)]
pub enum Error {
    #[error("invalid time: {0}")]
    InvalidTime(#[from] SystemTimeError),
    #[error("invalid secret: {0}")]
    DecodeError(#[from] DecodeError),
    #[error("invalid digest length")]
    InvalidDigestLength,
}

/// Supported HMAC algorithms for HOTP/TOTP
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Algorithm {
    /// HMAC-SHA1 - Most common for legacy applications
    #[default]
    SHA1,
    /// HMAC-SHA256 - More secure, supported by modern apps
    SHA256,
    /// HMAC-SHA512 - Highly secure
    SHA512,
}

impl From<Algorithm> for hmac::Algorithm {
    fn from(algo: Algorithm) -> Self {
        match algo {
            Algorithm::SHA1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
            Algorithm::SHA256 => hmac::HMAC_SHA256,
            Algorithm::SHA512 => hmac::HMAC_SHA512,
        }
    }
}

/// HMAC-based One-Time Password (HOTP) generator.
///
/// Implements RFC 4226.
#[derive(Debug, Clone)]
pub struct HOTP {
    secret: Vec<u8>,
    algorithm: Algorithm,
    digits: u32,
}

impl HOTP {
    /// Returns a new HOTP builder
    pub fn builder() -> HOTPBuilder {
        HOTPBuilder::new()
    }

    /// Creates a new HOTP instance with the given secret, algorithm, and digits
    pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32) -> Self {
        Self {
            secret,
            algorithm,
            digits,
        }
    }

    /// Generates the HOTP value for the given counter as an integer
    pub fn generate(&self, counter: u64) -> u32 {
        let key = hmac::Key::new(self.algorithm.into(), &self.secret);
        let tag = hmac::sign(&key, &counter.to_be_bytes());
        let digest = tag.as_ref();

        let offset = (digest[digest.len() - 1] & 0xf) as usize;
        let code_bytes: [u8; 4] = digest[offset..offset + 4].try_into().unwrap_or([0u8; 4]);

        let code = u32::from_be_bytes(code_bytes);
        (code & 0x7fffffff) % 10u32.pow(self.digits)
    }

    /// Generates the HOTP value as a formatted string with leading zeros
    pub fn generate_formatted(&self, counter: u64) -> String {
        format!(
            "{:0width$}",
            self.generate(counter),
            width = self.digits as usize
        )
    }

    /// Verifies an HOTP value for the given counter
    pub fn verify(&self, code: u32, counter: u64) -> bool {
        self.generate(counter) == code
    }

    /// Verifies a formatted HOTP string for the given counter
    pub fn verify_formatted(&self, code: &str, counter: u64) -> bool {
        self.generate_formatted(counter) == code
    }

    #[cfg(feature = "async")]
    pub async fn generate_async(&self, counter: u64) -> u32 {
        self.generate(counter)
    }

    #[cfg(feature = "async")]
    pub async fn generate_formatted_async(&self, counter: u64) -> String {
        self.generate_formatted(counter)
    }
}

/// Builder for `HOTP` instances
#[derive(Debug, Default)]
pub struct HOTPBuilder {
    secret: Option<Vec<u8>>,
    algorithm: Algorithm,
    digits: u32,
}

impl HOTPBuilder {
    /// Creates a new HOTP builder with default values (SHA1, 6 digits)
    pub fn new() -> Self {
        Self {
            secret: None,
            algorithm: Algorithm::SHA1,
            digits: 6,
        }
    }

    /// Sets the raw byte secret
    pub fn secret(mut self, secret: Vec<u8>) -> Self {
        self.secret = Some(secret);
        self
    }

    /// Sets the secret from a Base32 encoded string
    ///
    /// # Errors
    /// Returns error if the string is not valid Base32.
    pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
        self.secret = Some(decode_base32(secret)?);
        Ok(self)
    }

    /// Sets the HMAC algorithm
    pub fn algorithm(mut self, algo: Algorithm) -> Self {
        self.algorithm = algo;
        self
    }

    /// Sets the number of digits for the OTP (standard is 6 or 8)
    pub fn digits(mut self, digits: u32) -> Self {
        self.digits = digits;
        self
    }

    /// Builds the `HOTP` instance
    ///
    /// # Errors
    /// Returns error if secret is missing or digits is invalid (> 9).
    pub fn build(self) -> Result<HOTP, String> {
        let secret = self
            .secret
            .ok_or_else(|| "Secret is required".to_string())?;
        if self.digits > 9 {
            return Err("Digits must be between 1 and 9 for u32 output".to_string());
        }
        Ok(HOTP::new(secret, self.algorithm, self.digits))
    }
}

/// Time-based One-Time Password (TOTP) generator.
///
/// Implements RFC 6238.
#[derive(Debug, Clone)]
pub struct TOTP {
    hotp: HOTP,
    time_step: u64,
}

impl TOTP {
    /// Returns a new TOTP builder
    pub fn builder() -> TOTPBuilder {
        TOTPBuilder::new()
    }

    /// Creates a new TOTP instance with the given parameters
    pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, time_step: u64) -> Self {
        Self {
            hotp: HOTP::new(secret, algorithm, digits),
            time_step,
        }
    }

    /// Generates the TOTP value for a specific timestamp
    pub fn generate_at(&self, timestamp: u64) -> u32 {
        let counter = timestamp / self.time_step;
        self.hotp.generate(counter)
    }

    /// Generates the TOTP value for the current system time
    ///
    /// # Errors
    /// Returns error if system time is before Unix epoch.
    pub fn generate_current(&self) -> Result<u32, Error> {
        let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
        Ok(self.generate_at(now.as_secs()))
    }

    /// Generates the TOTP value as a formatted string with leading zeros for a specific timestamp
    pub fn generate_formatted_at(&self, timestamp: u64) -> String {
        format!(
            "{:0width$}",
            self.generate_at(timestamp),
            width = self.hotp.digits as usize
        )
    }

    /// Generates the formatted TOTP value (with leading zeros) for the current system time
    ///
    /// # Errors
    /// Returns error if system time is before Unix epoch.
    pub fn generate_current_formatted(&self) -> Result<String, Error> {
        let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
        Ok(self.generate_formatted_at(now.as_secs()))
    }

    /// Verifies a TOTP code at a specific timestamp with a given look-back/forward window.
    ///
    /// The window is the number of steps to check before and after the current step.
    /// For example, a window of 1 means it will check the current, previous, and next step.
    pub fn verify_at(&self, code: u32, timestamp: u64, window: u32) -> bool {
        let current_step = timestamp / self.time_step;
        for i in 0..=window {
            // Check current and backward
            if self.hotp.generate(current_step.saturating_sub(i as u64)) == code {
                return true;
            }
            // Check forward
            if self.hotp.generate(current_step.saturating_add(i as u64)) == code {
                return true;
            }
        }
        false
    }

    /// Verifies a TOTP code for the current time with default window of 0.
    ///
    /// # Errors
    /// Returns error if system time is before Unix epoch.
    pub fn verify_current(&self, code: u32, window: u32) -> Result<bool, Error> {
        let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
        Ok(self.verify_at(code, now.as_secs(), window))
    }

    /// Verifies a formatted TOTP string for the current time.
    ///
    /// # Errors
    /// Returns error if system time is before Unix epoch or if code is not a valid number.
    pub fn verify_current_formatted(&self, code: &str, window: u32) -> Result<bool, Error> {
        let code_u32 = code
            .parse::<u32>()
            .map_err(|_| Error::InvalidDigestLength)?; // Use a better error if possible
        self.verify_current(code_u32, window)
    }

    /// Asynchronous version of `generate_current`
    #[cfg(feature = "async")]
    pub async fn generate_current_async(&self) -> Result<u32, Error> {
        self.generate_current()
    }

    /// Asynchronous version of `generate_current_formatted`
    #[cfg(feature = "async")]
    pub async fn generate_current_formatted_async(&self) -> Result<String, Error> {
        self.generate_current_formatted()
    }
}

/// Builder for `TOTP` instances
pub struct TOTPBuilder {
    secret: Option<Vec<u8>>,
    algorithm: Algorithm,
    digits: u32,
    time_step: u64,
}

impl Default for TOTPBuilder {
    fn default() -> Self {
        Self {
            secret: None,
            algorithm: Algorithm::SHA1,
            digits: 6,
            time_step: 30,
        }
    }
}

impl TOTPBuilder {
    /// Creates a new TOTP builder with default values (SHA1, 6 digits, 30s step)
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the raw byte secret
    pub fn secret(mut self, secret: Vec<u8>) -> Self {
        self.secret = Some(secret);
        self
    }

    /// Sets the secret from a Base32 encoded string
    ///
    /// # Errors
    /// Returns error if the string is not valid Base32.
    pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
        let decoded = BASE32.decode(secret.as_bytes())?;
        self.secret = Some(decoded);
        Ok(self)
    }

    /// Sets the HMAC algorithm
    pub fn algorithm(mut self, algo: Algorithm) -> Self {
        self.algorithm = algo;
        self
    }

    /// Sets the number of digits for the OTP (standard is 6 or 8)
    pub fn digits(mut self, digits: u32) -> Self {
        self.digits = digits;
        self
    }

    /// Sets the time step in seconds (standard is 30)
    pub fn time_step(mut self, step: u64) -> Self {
        self.time_step = step;
        self
    }

    /// Builds the `TOTP` instance
    ///
    /// # Errors
    /// Returns error if secret is missing or digits is invalid (> 9).
    pub fn build(self) -> Result<TOTP, String> {
        let secret = self
            .secret
            .ok_or_else(|| "Secret is required".to_string())?;
        if self.digits > 9 {
            return Err("Digits must be between 1 and 9 for u32 output".to_string());
        }
        Ok(TOTP::new(
            secret,
            self.algorithm,
            self.digits,
            self.time_step,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rfc4226_hotp() {
        // Secret: "12345678901234567890" in Hex
        let secret = b"12345678901234567890".to_vec();
        let hotp = HOTP::new(secret, Algorithm::SHA1, 6);

        assert_eq!(hotp.generate(0), 755224);
        assert_eq!(hotp.generate(1), 287082);
        assert_eq!(hotp.generate(2), 359152);
        assert_eq!(hotp.generate(3), 969429);
        assert_eq!(hotp.generate(4), 338314);
        assert_eq!(hotp.generate(5), 254676);
        assert_eq!(hotp.generate(6), 287922);
        assert_eq!(hotp.generate(7), 162583);
        assert_eq!(hotp.generate(8), 399871);
        assert_eq!(hotp.generate(9), 520489);
    }

    #[test]
    fn test_rfc6238_totp_sha1() {
        let secret = b"12345678901234567890".to_vec();
        let totp = TOTP::new(secret, Algorithm::SHA1, 8, 30);

        assert_eq!(totp.generate_formatted_at(59), "94287082");
        assert_eq!(totp.generate_formatted_at(1111111109), "07081804");
        assert_eq!(totp.generate_formatted_at(1111111111), "14050471");
        assert_eq!(totp.generate_formatted_at(1234567890), "89005924");
        assert_eq!(totp.generate_formatted_at(2000000000), "69279037");
        assert_eq!(totp.generate_formatted_at(20000000000), "65353130");
    }

    #[test]
    fn test_rfc6238_totp_sha256() {
        let secret = b"12345678901234567890123456789012".to_vec();
        let totp = TOTP::new(secret, Algorithm::SHA256, 8, 30);

        assert_eq!(totp.generate_formatted_at(59), "46119246");
        assert_eq!(totp.generate_formatted_at(1111111109), "68084774");
        assert_eq!(totp.generate_formatted_at(1111111111), "67062674");
        assert_eq!(totp.generate_formatted_at(1234567890), "91819424");
        assert_eq!(totp.generate_formatted_at(2000000000), "90698825");
        assert_eq!(totp.generate_formatted_at(20000000000), "77737706");
    }

    #[test]
    fn test_rfc6238_totp_sha512() {
        let secret = b"1234567890123456789012345678901234567890123456789012345678901234".to_vec();
        let totp = TOTP::new(secret, Algorithm::SHA512, 8, 30);

        assert_eq!(totp.generate_formatted_at(59), "90693936");
        assert_eq!(totp.generate_formatted_at(1111111109), "25091201");
        assert_eq!(totp.generate_formatted_at(1111111111), "99943326");
        assert_eq!(totp.generate_formatted_at(1234567890), "93441116");
        assert_eq!(totp.generate_formatted_at(2000000000), "38618901");
        assert_eq!(totp.generate_formatted_at(20000000000), "47863826");
    }

    #[test]
    fn test_builder() {
        let hotp = HOTP::builder()
            .base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
            .unwrap()
            .digits(6)
            .build()
            .unwrap();

        // "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" is "12345678901234567890" in base32
        assert_eq!(hotp.generate(0), 755224);
    }

    #[test]
    fn test_unpadded_base32() {
        let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; // 32 chars, no padding needed
        let res = HOTP::builder().base32_secret(secret);
        assert!(res.is_ok());

        let secret_unpadded = "GEZDGNBVGY3TQOJQGEZDGNBV"; // 24 chars, missing 1 block of padding
        let res = HOTP::builder().base32_secret(secret_unpadded);
        assert!(
            res.is_ok(),
            "Base32 decoding should be robust to missing padding"
        );

        let secret_very_unpadded = "GEZDG"; // 5 chars, needs padding
        let res = HOTP::builder().base32_secret(secret_very_unpadded);
        assert!(
            res.is_ok(),
            "Base32 decoding should handle very unpadded strings"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_async() {
        let secret = b"12345678901234567890".to_vec();
        let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
        assert_eq!(hotp.generate_async(0).await, 755224);

        let secret = b"12345678901234567890".to_vec();
        let totp = TOTP::new(secret, Algorithm::SHA1, 6, 30);
        assert_eq!(totp.generate_current_async().await.is_ok(), true);
    }
}