Botan  2.6.0
Crypto and TLS for C++11
totp.cpp
Go to the documentation of this file.
1 /*
2 * TOTP
3 * (C) 2017 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #include <botan/totp.h>
9 #include <botan/calendar.h>
10 
11 namespace Botan {
12 
13 TOTP::TOTP(const SymmetricKey& key, const std::string& hash_algo,
14  size_t digits, size_t time_step)
15  : m_hotp(key, hash_algo, digits)
16  , m_time_step(time_step)
17  , m_unix_epoch(calendar_point(1970, 1, 1, 0, 0, 0).to_std_timepoint())
18  {
19  /*
20  * Technically any time step except 0 is valid, but 30 is typical
21  * and over 5 minutes seems unlikely.
22  */
23  if(m_time_step == 0 || m_time_step > 300)
24  throw Invalid_Argument("Invalid TOTP time step");
25  }
26 
27 uint32_t TOTP::generate_totp(std::chrono::system_clock::time_point current_time)
28  {
29  const uint64_t unix_time =
30  std::chrono::duration_cast<std::chrono::seconds>(current_time - m_unix_epoch).count();
31  return this->generate_totp(unix_time);
32  }
33 
34 uint32_t TOTP::generate_totp(uint64_t unix_time)
35  {
36  return m_hotp.generate_hotp(unix_time / m_time_step);
37  }
38 
39 bool TOTP::verify_totp(uint32_t otp, std::chrono::system_clock::time_point current_time,
40  size_t clock_drift_accepted)
41  {
42  const uint64_t unix_time =
43  std::chrono::duration_cast<std::chrono::seconds>(current_time - m_unix_epoch).count();
44  return verify_totp(otp, unix_time, clock_drift_accepted);
45  }
46 
47 bool TOTP::verify_totp(uint32_t otp, uint64_t unix_time,
48  size_t clock_drift_accepted)
49  {
50  uint64_t t = unix_time / m_time_step;
51 
52  for(size_t i = 0; i <= clock_drift_accepted; ++i)
53  {
54  if(m_hotp.generate_hotp(t-i) == otp)
55  {
56  return true;
57  }
58  }
59 
60  return false;
61  }
62 
63 }
TOTP(const SymmetricKey &key, const std::string &hash_algo="SHA-1", size_t digits=6, size_t time_step=30)
Definition: totp.cpp:13
bool verify_totp(uint32_t otp, std::chrono::system_clock::time_point time, size_t clock_drift_accepted=0)
Definition: totp.cpp:39
Definition: alg_id.cpp:13
AlgorithmIdentifier hash_algo
Definition: x509_obj.cpp:23
uint32_t generate_totp(std::chrono::system_clock::time_point time_point)
Definition: totp.cpp:27
uint32_t generate_hotp(uint64_t counter)
Definition: hotp.cpp:39