Skip to main content

rust_otp/
lib.rs

1use data_encoding::{DecodeError, BASE32};
2use ring::hmac;
3use std::time::{SystemTime, SystemTimeError};
4use thiserror::Error;
5
6/// Decodes a base32 string, handling both padded and unpadded input.
7fn decode_base32(input: &str) -> Result<Vec<u8>, DecodeError> {
8    let input = input.trim();
9    if input.contains('=') {
10        BASE32.decode(input.as_bytes())
11    } else {
12        // If no padding is present, we might need to add it or use a nopad decoder.
13        // data-encoding's BASE32 is strict. Let's add padding if needed.
14        let mut padded = input.to_string();
15        while padded.len() % 8 != 0 {
16            padded.push('=');
17        }
18        BASE32.decode(padded.as_bytes())
19    }
20}
21
22#[derive(Debug, Error)]
23pub enum Error {
24    #[error("invalid time: {0}")]
25    InvalidTime(#[from] SystemTimeError),
26    #[error("invalid secret: {0}")]
27    DecodeError(#[from] DecodeError),
28    #[error("invalid digest length")]
29    InvalidDigestLength,
30}
31
32/// Supported HMAC algorithms for HOTP/TOTP
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum Algorithm {
35    /// HMAC-SHA1 - Most common for legacy applications
36    #[default]
37    SHA1,
38    /// HMAC-SHA256 - More secure, supported by modern apps
39    SHA256,
40    /// HMAC-SHA512 - Highly secure
41    SHA512,
42}
43
44impl From<Algorithm> for hmac::Algorithm {
45    fn from(algo: Algorithm) -> Self {
46        match algo {
47            Algorithm::SHA1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
48            Algorithm::SHA256 => hmac::HMAC_SHA256,
49            Algorithm::SHA512 => hmac::HMAC_SHA512,
50        }
51    }
52}
53
54/// HMAC-based One-Time Password (HOTP) generator.
55///
56/// Implements RFC 4226.
57#[derive(Debug, Clone)]
58pub struct HOTP {
59    secret: Vec<u8>,
60    algorithm: Algorithm,
61    digits: u32,
62}
63
64impl HOTP {
65    /// Returns a new HOTP builder
66    pub fn builder() -> HOTPBuilder {
67        HOTPBuilder::new()
68    }
69
70    /// Creates a new HOTP instance with the given secret, algorithm, and digits
71    pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32) -> Self {
72        Self {
73            secret,
74            algorithm,
75            digits,
76        }
77    }
78
79    /// Generates the HOTP value for the given counter as an integer
80    pub fn generate(&self, counter: u64) -> u32 {
81        let key = hmac::Key::new(self.algorithm.into(), &self.secret);
82        let tag = hmac::sign(&key, &counter.to_be_bytes());
83        let digest = tag.as_ref();
84
85        let offset = (digest[digest.len() - 1] & 0xf) as usize;
86        let code_bytes: [u8; 4] = digest[offset..offset + 4].try_into().unwrap_or([0u8; 4]);
87
88        let code = u32::from_be_bytes(code_bytes);
89        (code & 0x7fffffff) % 10u32.pow(self.digits)
90    }
91
92    /// Generates the HOTP value as a formatted string with leading zeros
93    pub fn generate_formatted(&self, counter: u64) -> String {
94        format!(
95            "{:0width$}",
96            self.generate(counter),
97            width = self.digits as usize
98        )
99    }
100
101    /// Verifies an HOTP value for the given counter
102    pub fn verify(&self, code: u32, counter: u64) -> bool {
103        self.generate(counter) == code
104    }
105
106    /// Verifies a formatted HOTP string for the given counter
107    pub fn verify_formatted(&self, code: &str, counter: u64) -> bool {
108        self.generate_formatted(counter) == code
109    }
110
111    #[cfg(feature = "async")]
112    pub async fn generate_async(&self, counter: u64) -> u32 {
113        self.generate(counter)
114    }
115
116    #[cfg(feature = "async")]
117    pub async fn generate_formatted_async(&self, counter: u64) -> String {
118        self.generate_formatted(counter)
119    }
120}
121
122/// Builder for `HOTP` instances
123#[derive(Debug, Default)]
124pub struct HOTPBuilder {
125    secret: Option<Vec<u8>>,
126    algorithm: Algorithm,
127    digits: u32,
128}
129
130impl HOTPBuilder {
131    /// Creates a new HOTP builder with default values (SHA1, 6 digits)
132    pub fn new() -> Self {
133        Self {
134            secret: None,
135            algorithm: Algorithm::SHA1,
136            digits: 6,
137        }
138    }
139
140    /// Sets the raw byte secret
141    pub fn secret(mut self, secret: Vec<u8>) -> Self {
142        self.secret = Some(secret);
143        self
144    }
145
146    /// Sets the secret from a Base32 encoded string
147    ///
148    /// # Errors
149    /// Returns error if the string is not valid Base32.
150    pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
151        self.secret = Some(decode_base32(secret)?);
152        Ok(self)
153    }
154
155    /// Sets the HMAC algorithm
156    pub fn algorithm(mut self, algo: Algorithm) -> Self {
157        self.algorithm = algo;
158        self
159    }
160
161    /// Sets the number of digits for the OTP (standard is 6 or 8)
162    pub fn digits(mut self, digits: u32) -> Self {
163        self.digits = digits;
164        self
165    }
166
167    /// Builds the `HOTP` instance
168    ///
169    /// # Errors
170    /// Returns error if secret is missing or digits is invalid (> 9).
171    pub fn build(self) -> Result<HOTP, String> {
172        let secret = self
173            .secret
174            .ok_or_else(|| "Secret is required".to_string())?;
175        if self.digits > 9 {
176            return Err("Digits must be between 1 and 9 for u32 output".to_string());
177        }
178        Ok(HOTP::new(secret, self.algorithm, self.digits))
179    }
180}
181
182/// Time-based One-Time Password (TOTP) generator.
183///
184/// Implements RFC 6238.
185#[derive(Debug, Clone)]
186pub struct TOTP {
187    hotp: HOTP,
188    time_step: u64,
189}
190
191impl TOTP {
192    /// Returns a new TOTP builder
193    pub fn builder() -> TOTPBuilder {
194        TOTPBuilder::new()
195    }
196
197    /// Creates a new TOTP instance with the given parameters
198    pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, time_step: u64) -> Self {
199        Self {
200            hotp: HOTP::new(secret, algorithm, digits),
201            time_step,
202        }
203    }
204
205    /// Generates the TOTP value for a specific timestamp
206    pub fn generate_at(&self, timestamp: u64) -> u32 {
207        let counter = timestamp / self.time_step;
208        self.hotp.generate(counter)
209    }
210
211    /// Generates the TOTP value for the current system time
212    ///
213    /// # Errors
214    /// Returns error if system time is before Unix epoch.
215    pub fn generate_current(&self) -> Result<u32, Error> {
216        let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
217        Ok(self.generate_at(now.as_secs()))
218    }
219
220    /// Generates the TOTP value as a formatted string with leading zeros for a specific timestamp
221    pub fn generate_formatted_at(&self, timestamp: u64) -> String {
222        format!(
223            "{:0width$}",
224            self.generate_at(timestamp),
225            width = self.hotp.digits as usize
226        )
227    }
228
229    /// Generates the formatted TOTP value (with leading zeros) for the current system time
230    ///
231    /// # Errors
232    /// Returns error if system time is before Unix epoch.
233    pub fn generate_current_formatted(&self) -> Result<String, Error> {
234        let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
235        Ok(self.generate_formatted_at(now.as_secs()))
236    }
237
238    /// Verifies a TOTP code at a specific timestamp with a given look-back/forward window.
239    ///
240    /// The window is the number of steps to check before and after the current step.
241    /// For example, a window of 1 means it will check the current, previous, and next step.
242    pub fn verify_at(&self, code: u32, timestamp: u64, window: u32) -> bool {
243        let current_step = timestamp / self.time_step;
244        for i in 0..=window {
245            // Check current and backward
246            if self.hotp.generate(current_step.saturating_sub(i as u64)) == code {
247                return true;
248            }
249            // Check forward
250            if self.hotp.generate(current_step.saturating_add(i as u64)) == code {
251                return true;
252            }
253        }
254        false
255    }
256
257    /// Verifies a TOTP code for the current time with default window of 0.
258    ///
259    /// # Errors
260    /// Returns error if system time is before Unix epoch.
261    pub fn verify_current(&self, code: u32, window: u32) -> Result<bool, Error> {
262        let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
263        Ok(self.verify_at(code, now.as_secs(), window))
264    }
265
266    /// Verifies a formatted TOTP string for the current time.
267    ///
268    /// # Errors
269    /// Returns error if system time is before Unix epoch or if code is not a valid number.
270    pub fn verify_current_formatted(&self, code: &str, window: u32) -> Result<bool, Error> {
271        let code_u32 = code
272            .parse::<u32>()
273            .map_err(|_| Error::InvalidDigestLength)?; // Use a better error if possible
274        self.verify_current(code_u32, window)
275    }
276
277    /// Asynchronous version of `generate_current`
278    #[cfg(feature = "async")]
279    pub async fn generate_current_async(&self) -> Result<u32, Error> {
280        self.generate_current()
281    }
282
283    /// Asynchronous version of `generate_current_formatted`
284    #[cfg(feature = "async")]
285    pub async fn generate_current_formatted_async(&self) -> Result<String, Error> {
286        self.generate_current_formatted()
287    }
288}
289
290/// Builder for `TOTP` instances
291pub struct TOTPBuilder {
292    secret: Option<Vec<u8>>,
293    algorithm: Algorithm,
294    digits: u32,
295    time_step: u64,
296}
297
298impl Default for TOTPBuilder {
299    fn default() -> Self {
300        Self {
301            secret: None,
302            algorithm: Algorithm::SHA1,
303            digits: 6,
304            time_step: 30,
305        }
306    }
307}
308
309impl TOTPBuilder {
310    /// Creates a new TOTP builder with default values (SHA1, 6 digits, 30s step)
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Sets the raw byte secret
316    pub fn secret(mut self, secret: Vec<u8>) -> Self {
317        self.secret = Some(secret);
318        self
319    }
320
321    /// Sets the secret from a Base32 encoded string
322    ///
323    /// # Errors
324    /// Returns error if the string is not valid Base32.
325    pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
326        let decoded = BASE32.decode(secret.as_bytes())?;
327        self.secret = Some(decoded);
328        Ok(self)
329    }
330
331    /// Sets the HMAC algorithm
332    pub fn algorithm(mut self, algo: Algorithm) -> Self {
333        self.algorithm = algo;
334        self
335    }
336
337    /// Sets the number of digits for the OTP (standard is 6 or 8)
338    pub fn digits(mut self, digits: u32) -> Self {
339        self.digits = digits;
340        self
341    }
342
343    /// Sets the time step in seconds (standard is 30)
344    pub fn time_step(mut self, step: u64) -> Self {
345        self.time_step = step;
346        self
347    }
348
349    /// Builds the `TOTP` instance
350    ///
351    /// # Errors
352    /// Returns error if secret is missing or digits is invalid (> 9).
353    pub fn build(self) -> Result<TOTP, String> {
354        let secret = self
355            .secret
356            .ok_or_else(|| "Secret is required".to_string())?;
357        if self.digits > 9 {
358            return Err("Digits must be between 1 and 9 for u32 output".to_string());
359        }
360        Ok(TOTP::new(
361            secret,
362            self.algorithm,
363            self.digits,
364            self.time_step,
365        ))
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_rfc4226_hotp() {
375        // Secret: "12345678901234567890" in Hex
376        let secret = b"12345678901234567890".to_vec();
377        let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
378
379        assert_eq!(hotp.generate(0), 755224);
380        assert_eq!(hotp.generate(1), 287082);
381        assert_eq!(hotp.generate(2), 359152);
382        assert_eq!(hotp.generate(3), 969429);
383        assert_eq!(hotp.generate(4), 338314);
384        assert_eq!(hotp.generate(5), 254676);
385        assert_eq!(hotp.generate(6), 287922);
386        assert_eq!(hotp.generate(7), 162583);
387        assert_eq!(hotp.generate(8), 399871);
388        assert_eq!(hotp.generate(9), 520489);
389    }
390
391    #[test]
392    fn test_rfc6238_totp_sha1() {
393        let secret = b"12345678901234567890".to_vec();
394        let totp = TOTP::new(secret, Algorithm::SHA1, 8, 30);
395
396        assert_eq!(totp.generate_formatted_at(59), "94287082");
397        assert_eq!(totp.generate_formatted_at(1111111109), "07081804");
398        assert_eq!(totp.generate_formatted_at(1111111111), "14050471");
399        assert_eq!(totp.generate_formatted_at(1234567890), "89005924");
400        assert_eq!(totp.generate_formatted_at(2000000000), "69279037");
401        assert_eq!(totp.generate_formatted_at(20000000000), "65353130");
402    }
403
404    #[test]
405    fn test_rfc6238_totp_sha256() {
406        let secret = b"12345678901234567890123456789012".to_vec();
407        let totp = TOTP::new(secret, Algorithm::SHA256, 8, 30);
408
409        assert_eq!(totp.generate_formatted_at(59), "46119246");
410        assert_eq!(totp.generate_formatted_at(1111111109), "68084774");
411        assert_eq!(totp.generate_formatted_at(1111111111), "67062674");
412        assert_eq!(totp.generate_formatted_at(1234567890), "91819424");
413        assert_eq!(totp.generate_formatted_at(2000000000), "90698825");
414        assert_eq!(totp.generate_formatted_at(20000000000), "77737706");
415    }
416
417    #[test]
418    fn test_rfc6238_totp_sha512() {
419        let secret = b"1234567890123456789012345678901234567890123456789012345678901234".to_vec();
420        let totp = TOTP::new(secret, Algorithm::SHA512, 8, 30);
421
422        assert_eq!(totp.generate_formatted_at(59), "90693936");
423        assert_eq!(totp.generate_formatted_at(1111111109), "25091201");
424        assert_eq!(totp.generate_formatted_at(1111111111), "99943326");
425        assert_eq!(totp.generate_formatted_at(1234567890), "93441116");
426        assert_eq!(totp.generate_formatted_at(2000000000), "38618901");
427        assert_eq!(totp.generate_formatted_at(20000000000), "47863826");
428    }
429
430    #[test]
431    fn test_builder() {
432        let hotp = HOTP::builder()
433            .base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
434            .unwrap()
435            .digits(6)
436            .build()
437            .unwrap();
438
439        // "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" is "12345678901234567890" in base32
440        assert_eq!(hotp.generate(0), 755224);
441    }
442
443    #[test]
444    fn test_unpadded_base32() {
445        let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; // 32 chars, no padding needed
446        let res = HOTP::builder().base32_secret(secret);
447        assert!(res.is_ok());
448
449        let secret_unpadded = "GEZDGNBVGY3TQOJQGEZDGNBV"; // 24 chars, missing 1 block of padding
450        let res = HOTP::builder().base32_secret(secret_unpadded);
451        assert!(
452            res.is_ok(),
453            "Base32 decoding should be robust to missing padding"
454        );
455
456        let secret_very_unpadded = "GEZDG"; // 5 chars, needs padding
457        let res = HOTP::builder().base32_secret(secret_very_unpadded);
458        assert!(
459            res.is_ok(),
460            "Base32 decoding should handle very unpadded strings"
461        );
462    }
463
464    #[cfg(feature = "async")]
465    #[tokio::test]
466    async fn test_async() {
467        let secret = b"12345678901234567890".to_vec();
468        let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
469        assert_eq!(hotp.generate_async(0).await, 755224);
470
471        let secret = b"12345678901234567890".to_vec();
472        let totp = TOTP::new(secret, Algorithm::SHA1, 6, 30);
473        assert_eq!(totp.generate_current_async().await.is_ok(), true);
474    }
475}