RFC 4226

HOTP: An HMAC-Based One-Time Password Algorithm

๐Ÿ“… published December 2005, from ietf

HOTP: An HMAC-Based One-Time Password Algorithm ๐ŸŽ€

okay bestie, this is RFC 4226 ๐Ÿ’œ and it's from the Network Working Group. It's titled HOTP: An HMAC-Based One-Time Password Algorithm, and it's dated December 2005. The authors are D. M'Raihi (VeriSign), M. Bellare (UCSD), F. Hoornaert (Vasco), D. Naccache (Gemplus), and O. Ranen (Aladdin). It's Informational, so it's not an Internet standard. Also, the title block doesn't list anything it obsoletes or updates ๐Ÿงš

Status of This Memo โœจ

This memo gives information to the Internet community. It doesn't specify an Internet standard of any kind. Distribution of this memo is unlimited ๐ŸŒธ

Copyright (C) The Internet Society (2005).

Abstract ๐Ÿ’–

This doc describes an algorithm that makes one-time password values, and it's built on Hashed Message Authentication Code (HMAC) ๐Ÿ”ฅ It also includes a security analysis of the algorithm, and it talks about the important parameters you need for deploying it securely. The algorithm can be used across a ton of network apps, like remote Virtual Private Network (VPN) access, Wi-Fi network logon, and transaction-oriented Web applications. It's giving versatile ๐Ÿฆ‹

This work is a team effort from OATH (Open AuTHentication) members. The goal is an algorithm that can be freely shared with the technical community. The authors think a common, shared algorithm will help two-factor authentication spread across the Internet, because it lets commercial and open-source implementations work together ๐Ÿซถ

Table of Contents ๐Ÿ“

   1. Overview ........................................................3
   2. Introduction ....................................................3
   3. Requirements Terminology ........................................4
   4. Algorithm Requirements ..........................................4
   5. HOTP Algorithm ..................................................5
      5.1. Notation and Symbols .......................................5
      5.2. Description ................................................6
      5.3. Generating an HOTP Value ...................................6
      5.4. Example of HOTP Computation for Digit = 6 ..................7
   6. Security Considerations .........................................8
   7. Security Requirements ...........................................9
      7.1. Authentication Protocol Requirements .......................9
      7.2. Validation of HOTP Values .................................10
      7.3. Throttling at the Server ..................................10
      7.4. Resynchronization of the Counter ..........................11
      7.5. Management of Shared Secrets ..............................11
   8. Composite Shared Secrets .......................................14
   9. Bi-Directional Authentication ..................................14
   10. Conclusion ....................................................15
   11. Acknowledgements ..............................................15
   12. Contributors ..................................................15
   13. References ....................................................15
      13.1. Normative References .....................................15
      13.2. Informative References ...................................16
   Appendix A - HOTP Algorithm Security: Detailed Analysis ...........17
      A.1. Definitions and Notations .................................17
      A.2. The Idealized Algorithm: HOTP-IDEAL .......................17
      A.3. Model of Security .........................................18
      A.4. Security of the Ideal Authentication Algorithm ............19
           A.4.1. From Bits to Digits ................................19
           A.4.2. Brute Force Attacks ................................21
           A.4.3. Brute force attacks are the best possible attacks ..22
      A.5. Security Analysis of HOTP .................................23
   Appendix B - SHA-1 Attacks ........................................25
      B.1. SHA-1 Status ..............................................25
      B.2. HMAC-SHA-1 Status .........................................26
      B.3. HOTP Status ...............................................26
   Appendix C - HOTP Algorithm: Reference Implementation .............27
   Appendix D - HOTP Algorithm: Test Values ..........................32
   Appendix E - Extensions ...........................................33
      E.1. Number of Digits ..........................................33
      E.2. Alphanumeric Values .......................................33
      E.3. Sequence of HOTP values ...................................34
      E.4. A Counter-Based Resynchronization Method ..................34
      E.5. Data Field ................................................35

1. Overview โœจ

So first up, this doc sets the scene for an algorithm that generates one-time password values based on HMAC [BCK1]. That's why it's called the HMAC-Based One-Time Password (HOTP) algorithm ๐Ÿงš In Section 4, you'll find the algorithm requirements, and in Section 5, the HOTP algorithm itself gets explained. Sections 6 and 7 are all about algorithm security. Section 8 proposes some extensions and improvements, and Section 10 wraps everything up. If you're a security nerd, Appendix A is your moment ๐Ÿค“ It has a full, detailed analysis: an idealized version of the algorithm gets evaluated first, and then the security of HOTP itself gets analyzed ๐Ÿ’…

2. Introduction ๐Ÿ’œ

Honestly? Two-factor authentication is still super limited in scope and scale ๐Ÿ™ˆ Even though threats keep getting worse and worse, most Internet apps still rely on weak authentication to control user access. A big reason adoption is stuck is that hardware and software vendors don't interoperate well. Without open specs, solutions end up tightly coupled through proprietary tech, which means high costs, poor adoption, and not much innovation ๐Ÿ’€

Over the last two years, network threats have blown up, and that exposed how bad static passwords are as the main way to authenticate on the Internet. Meanwhile, the usual approach of making an end user carry a pricey, single-purpose device that only authenticates to the network is clearly not the move ๐Ÿ™…โ€โ™€๏ธ For two-factor authentication to actually spread, it has to be embedded in more flexible devices that work across lots of different applications ๐ŸŒˆ

To embed this base tech while keeping things interoperable, it needs to be freely available to the wider community of hardware and software developers. Only an open-system approach will make sure basic two-factor authentication building blocks end up in the next generation of consumer devices, like USB mass storage devices, IP phones, and personal digital assistants ๐ŸŽง

One-Time Password is honestly one of the simplest and most popular forms of two-factor authentication for securing network access ๐Ÿ” For example, big enterprises often need One-Time Password tokens for Virtual Private Network access so remote users can authenticate. People often prefer One-Time Passwords over stronger options like Public-Key Infrastructure (PKI) or biometrics, because an air-gap device doesn't need any client desktop software installed on the user's machine. That means users can roam across multiple machines, including home computers, kiosks, and personal digital assistants ๐Ÿงณ

This document proposes a simple One-Time Password algorithm that any hardware manufacturer or software developer can implement to create interoperable authentication devices and software agents ๐Ÿ› ๏ธ The algorithm is event-based, so it can be embedded in high-volume devices like Java smart cards, USB dongles, and GSM SIM cards. The algorithm is freely available to developers under the terms and conditions of the IETF Intellectual Property Rights [RFC3979] โœจ

The authors of this document are members of the Open AuTHentication initiative [OATH]. That initiative was created in 2004 to help strong authentication technology providers collaborate ๐Ÿซถ

3. Requirements Terminology ๐ŸŽ€

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119] ๐Ÿ“–

4. Algorithm Requirements ๐Ÿ’…

This section lists the main requirements that shaped this algorithm's design. A lot of focus went into end-consumer usability, plus the ability to run on low-cost hardware with minimal user interface. Embedding the algorithm into high-volume SIM and Java cards was a must-have ๐Ÿ’–

R1 - The algorithm MUST be sequence- or counter-based: one of the goals is to have the HOTP algorithm embedded in high-volume devices such as Java smart cards, USB dongles, and GSM SIM cards. ๐Ÿงš

R2 - The algorithm SHOULD be economical to implement in hardware by minimizing requirements on battery, number of buttons, computational horsepower, and size of LCD display. ๐Ÿ”‹

R3 - The algorithm MUST work with tokens that do not support any numeric input, but MAY also be used with more sophisticated devices such as secure PIN-pads. โญ

R4 - The value displayed on the token MUST be easily read and entered by the user: This requires the HOTP value to be of reasonable length. ๐Ÿ‘€

The HOTP value must be at least a 6-digit value. It's also desirable that the HOTP value be 'numeric only' so it can be easily entered on restricted devices such as phones ๐Ÿ“ฑ

R5 - There MUST be user-friendly mechanisms available to resynchronize the counter. Section 7.4 and Appendix E.4 details the resynchronization mechanism proposed in this document ๐Ÿ”„

R6 - The algorithm MUST use a strong shared secret. The length of the shared secret MUST be at least 128 bits. This document RECOMMENDs a shared secret length of 160 bits. ๐Ÿ”‘

5. HOTP Algorithm ๐Ÿฆ‹

In this section, we introduce the notation and go through the HOTP algorithm's basic blocks. That's the base function that computes an HMAC-SHA-1 value, plus the truncation method that pulls out an HOTP value ๐ŸŒธ

part 1 of 7, more coming soon ๐ŸŽ€

5.1. Notation and Symbols โœจ

Okay, first the notation, bestie ๐Ÿงš. A string always means a binary string, which is just a sequence of zeros and ones ๐Ÿ’œ.

If s is a string, then |s| is its length. If n is a number, then |n| is its absolute value. If s is a string, then s[i] is its i-th bit. We start counting bits at 0, so s = s[0]s[1]...s[n-1] where n = |s| is the length of s ๐ŸŽ€.

Next, StToNum (String to Number) is the function that takes a string s and gives you back the number whose binary representation is s. For example, StToNum(110) = 6 ๐Ÿ“.

Here is the symbol list, and it's giving very important vibes ๐Ÿ‘‘:

   Symbol  Represents
   -------------------------------------------------------------------
   C       8-byte counter value, the moving factor.  This counter
           MUST be synchronized between the HOTP generator (client)
           and the HOTP validator (server).

   K       shared secret between client and server; each HOTP
           generator has a different and unique secret K.

   T       throttling parameter: the server will refuse connections
           from a user after T unsuccessful authentication attempts.

   s       resynchronization parameter: the server will attempt to
           verify a received authenticator across s consecutive
           counter values.

   Digit   number of digits in an HOTP value; system parameter.

Quick breakdown, because these are the ones you'll see everywhere ๐Ÿ’…. C is the 8-byte counter, the moving factor, and it MUST be synced between the generator (client) and the validator (server) ๐Ÿ”ฅ. K is the shared secret, and every HOTP generator gets its own unique one ๐Ÿ”. T is the throttling parameter, so the server refuses connections from a user after T failed attempts ๐Ÿšซ. s is the resync parameter, meaning the server tries to verify an authenticator across s consecutive counter values ๐ŸŒˆ. And Digit is how many digits an HOTP value has, which is a system parameter โœจ.

5.2. Description

So the HOTP algorithm is built on an increasing counter and a static symmetric key that only the token and the validation service know about ๐Ÿฆ‹. To make the HOTP value, we use HMAC-SHA-1, as defined in RFC 2104 [BCK2] ๐Ÿ’–.

The thing is, the HMAC-SHA-1 output is 160 bits, which is way too long for a human to type in, so we must truncate it down to something a user can actually enter ๐Ÿ˜ญ.

                   HOTP(K,C) = Truncate(HMAC-SHA-1(K,C))

Where:

  • Truncate is the function that turns an HMAC-SHA-1 value into an HOTP value, as defined in Section 5.3.

The Key (K), the Counter (C), and Data values are all hashed high-order byte first ๐Ÿซถ. And the HOTP values the generator spits out are treated as big endian ๐Ÿ“.

5.3. Generating an HOTP Value

We can break this into 3 distinct steps, and it's honestly so clean ๐Ÿงš:

   Step 1: Generate an HMAC-SHA-1 value Let HS = HMAC-SHA-1(K,C)  // HS
   is a 20-byte string

   Step 2: Generate a 4-byte string (Dynamic Truncation)
   Let Sbits = DT(HS)   //  DT, defined below,
                        //  returns a 31-bit string

   Step 3: Compute an HOTP value
   Let Snum  = StToNum(Sbits)   // Convert S to a number in
                                    0...2^{31}-1
   Return D = Snum mod 10^Digit //  D is a number in the range
                                    0...10^{Digit}-1

Step 2 and Step 3 together are what the Truncate function does: the dynamic truncation, and then the reduction modulo 10^Digit ๐Ÿ”ฅ. The whole point of this dynamic offset truncation is to pull a 4-byte dynamic binary code out of that 160-bit (20-byte) HMAC-SHA-1 result ๐Ÿ’….

    DT(String) // String = String[0]...String[19]
     Let OffsetBits be the low-order 4 bits of String[19]
     Offset = StToNum(OffsetBits) // 0 <= OffSet <= 15
     Let P = String[OffSet]...String[OffSet+3]
     Return the Last 31 bits of P

Why do we mask the most significant bit of P? Because it stops any confusion about signed vs. unsigned modulo math ๐Ÿ™ˆ. Different processors handle those operations differently, and masking out the signed bit clears up all the ambiguity โœจ.

Now the important part ๐Ÿ‘‘: implementations MUST extract a 6-digit code at a minimum, and they might also extract 7 or 8-digit codes. Depending on how much security you need, Digit = 7 or more SHOULD be considered if you want a longer HOTP value ๐Ÿ”.

Next up is an example of this technique for Digit = 6, which means a 6-digit HOTP value gets calculated from the HMAC value ๐ŸŽ€.

5.4. Example of HOTP Computation for Digit = 6

Here's the code example for pulling out the dynamic binary code, assuming hmac_result is a byte array holding the HMAC-SHA-1 result ๐Ÿ’œ:

        int offset   =  hmac_result[19] & 0xf ;
        int bin_code = (hmac_result[offset]  & 0x7f) << 24
           | (hmac_result[offset+1] & 0xff) << 16
           | (hmac_result[offset+2] & 0xff) <<  8
           | (hmac_result[offset+3] & 0xff) ;

And now the worked example, which is so satisfying to follow ๐Ÿฆ‹:

   SHA-1 HMAC Bytes (Example)

   -------------------------------------------------------------
   | Byte Number                                               |
   -------------------------------------------------------------
   |00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|
   -------------------------------------------------------------
   | Byte Value                                                |
   -------------------------------------------------------------
   |1f|86|98|69|0e|02|ca|16|61|85|50|ef|7f|19|da|8e|94|5b|55|5a|
   -------------------------------***********----------------++|
   * The last byte (byte 19) has the hex value 0x5a.
   * The value of the lower 4 bits is 0xa (the offset value).
   * The offset value is byte 10 (0xa).
   * The value of the 4 bytes starting at byte 10 is 0x50ef7f19,
     which is the dynamic binary code DBC1.
   * The MSB of DBC1 is 0x50 so DBC2 = DBC1 = 0x50ef7f19 .
   * HOTP = DBC2 modulo 10^6 = 872921.

So the last byte is 0x5a, its low 4 bits give us 0xa, and that's our offset ๐Ÿงš. We grab the 4 bytes starting at byte 10, which is 0x50ef7f19 (that's DBC1), and since the MSB is 0x50, DBC2 is just DBC1 again ๐Ÿ’–. Then HOTP = DBC2 modulo 10^6 = 872921 โœจ iconic.

We treat the dynamic binary code as a 31-bit, unsigned, big-endian integer, and the first byte gets masked with 0x7f ๐Ÿ”ฅ. After that we take the number modulo 1,000,000 (10^6) to get the 6-digit HOTP value 872921 decimal ๐Ÿ‘‘.


6. Security Considerations ๐Ÿ”

Okay, this section is the reason I'm up at 3am ๐Ÿ˜ญ. The conclusion of the security analysis (which lives in the Appendix) is that, for all practical purposes, the outputs of the Dynamic Truncation (DT) on distinct counter inputs are uniformly and independently distributed 31-bit strings ๐Ÿ’….

The analysis then looks at the impact of converting a string into an integer and then doing the final reduction modulo 10^Digit, where Digit is the number of digits in an HOTP value ๐Ÿงš.

The analysis shows that these final steps add a negligible bias, and that bias does not hurt the security of HOTP, in the sense that the best possible attack against the HOTP function is brute force ๐Ÿ™ˆ. Honestly the brute force part is kind of the vibe ๐Ÿ˜ญ.

Let's say an adversary can watch a bunch of protocol exchanges and collect sequences of successful authentication values. This adversary tries to build a function F that generates HOTP values from what they've observed, and they won't have a significant advantage over a random guess ๐Ÿ’€.

So the logical conclusion is that the best strategy will, once again, be brute force, which means enumerating and trying all the possible values ๐Ÿ”ฅ.

Considering the security analysis in the Appendix of this document, without loss of generality, we can closely approximate the security of the HOTP algorithm with this formula:

                            Sec = sv/10^Digit

Where:

  • Sec is the probability of success of the adversary;
  • s is the look-ahead synchronization window size;
  • v is the number of verification attempts;
  • Digit is the number of digits in HOTP values.

Obviously, you can play with s, T (the Throttling parameter that limits how many attempts an attacker gets), and Digit until you hit a certain level of security, all while keeping the system usable ๐ŸŒธ.

7. Security Requirements ๐Ÿ›ก๏ธ

Any One-Time Password algorithm is only as secure as the application and the authentication protocols that implement it ๐Ÿ’œ. So this section covers the critical security requirements that our choice of algorithm puts on the authentication protocol and the validation software ๐Ÿ‘‘.

The parameters T and s from this section have a big impact on security. Section 6 goes deeper into how those parameters relate to each other and to system security ๐Ÿฆ‹.

It's also important to remember that HOTP is not a substitute for encryption, and it does not provide privacy for data transmission. Other mechanisms should be used to defeat attacks aimed at breaking the confidentiality and privacy of transactions ๐Ÿ”.

7.1. Authentication Protocol Requirements

Here are some requirements for a protocol P implementing HOTP as the authentication method between a prover and a verifier ๐ŸŽ€.

  • RP1 - P MUST support two-factor authentication, meaning the communication and verification of something you know (a secret code like a Password, Pass phrase, PIN code, etc.) and something you have (a token). The secret code is known only to the user and is usually entered along with the One-Time Password value for authentication purposes (two-factor authentication) ๐Ÿ’….
  • RP2 - P SHOULD NOT be vulnerable to brute force attacks. This implies that a throttling/lockout scheme is RECOMMENDED on the validation server side ๐Ÿšซ.
  • RP3 - P SHOULD be implemented over a secure channel in order to protect users' privacy and avoid replay attacks ๐ŸŒˆ.

7.2. Validation of HOTP Values

The HOTP client (hardware or software token) increments its counter and then calculates the next HOTP value, HOTP client ๐Ÿงš. If the value the authentication server receives matches what the client calculated, the HOTP value is validated โœจ. In that case, the server increments the counter value by one ๐Ÿ’–.

If the value the server receives doesn't match what the client calculated, the server initiates the resync protocol (look-ahead window) before it requests another pass ๐Ÿ”„.

If the resync fails, the server then asks for another authentication pass of the protocol, and this keeps going until the maximum number of authorized attempts is reached ๐Ÿ˜ฌ.

If and when the maximum number of authorized attempts is reached, the server SHOULD lock out the account and start a procedure to inform the user ๐Ÿ”’.

7.3. Throttling at the Server

Truncating the HMAC-SHA-1 value to a shorter value makes a brute force attack possible ๐Ÿ™ˆ. That's why the authentication server needs to detect and stop brute force attacks ๐Ÿ›‘.

We RECOMMEND setting a throttling parameter T, which defines the maximum number of possible attempts for One-Time Password validation ๐Ÿ’œ. The validation server manages individual counters per HOTP device so it can note every failed attempt ๐ŸŽ€. We RECOMMEND T not be too large, especially if the resynchronization method on the server is window-based and the window size is large ๐Ÿซถ. T SHOULD be set as low as possible while still making sure usability isn't significantly impacted โœจ.

Another option is a delay scheme to avoid brute force attacks. After each failed attempt A, the authentication server would wait for an increased T*A number of seconds. For example, say T = 5. After 1 attempt, the server waits 5 seconds. At the second failed attempt, it waits 5*2 = 10 seconds, and so on ๐ŸŒธ.

The delay or lockout schemes MUST work across login sessions, so they can prevent attacks based on multiple parallel guessing techniques ๐Ÿ”ฅ๐Ÿ’….

7.4. Resynchronization of the Counter โœจ

Okay so, the server's counter only ticks up after a successful HOTP login, but the token's counter ticks up every single time the user asks for a new HOTP ๐Ÿ™ˆ. So the two counters can drift apart, and that's the whole problem bestie ๐Ÿ’€

We RECOMMEND setting a look-ahead parameter s on the server. This is the size of the look-ahead window ๐ŸชŸ In a nutshell, the server can recalculate the next s HOTP-server values and check them against the HOTP the client sent. Iconic.

Resyncing is literally just the server calculating the next HOTP values and seeing if one matches ๐Ÿงš Optionally, the system MAY ask the user to send a sequence of (say, 2, 3) HOTP values for resync. Why? Because forging a run of consecutive HOTP values is way harder than guessing one single value. Main character security ๐Ÿ‘‘

The s bound keeps the server from checking HOTP values forever (that would be a denial-of-service attack, not it ๐Ÿ˜ค), and it also limits the number of possible solutions an attacker has when trying to fake HOTP values. s SHOULD be set as low as possible while still making sure usability doesn't suffer ๐Ÿฆ‹


7.5. Management of Shared Secrets ๐Ÿ”

The operations that touch the shared secrets used to generate and verify OTP values have to be done securely, so there's less risk of sensitive info leaking ๐Ÿซถ This section walks through different modes of operation and techniques for these operations, based on the state of the art in data security. It's giving responsible.

There are two avenues for generating and storing shared secrets (securely) in the Validation system:

  • Deterministic Generation: secrets are derived from a master seed, both at provisioning and verification time, and generated on the fly whenever they're needed.
  • Random Generation: secrets are randomly generated at provisioning time and must be stored right away and kept secure for their whole life cycle.

Deterministic Generation

One possible strategy is to derive the shared secrets from a master secret ๐Ÿ—๏ธ The master secret gets stored at the server only. A tamper-resistant device MUST be used to store the master key and derive the shared secrets from the master key plus some public info. The big win is that the shared secrets are never exposed at any point, and you don't need special storage requirements, because they can be generated on demand at provisioning and validation time. Ate ๐Ÿ’…

We split this into two cases:

  • A single master key MK is used to derive all the shared secrets. Each HOTP device gets its own secret, K_i = SHA-1 (MK,i), where i stands for a public piece of info that uniquely identifies the HOTP device, like a serial number, a token ID, etc. Obviously this only applies within a specific application or service. Different application or service providers will have different secrets and settings ๐ŸŒธ
  • Several master keys MK_i are used, and each HOTP device stores a set of different derived secrets, {K_i,j = SHA-1(MK_i,j)}, where j stands for a public piece of info identifying the device. The idea is to store ONLY the active master key at the validation server, in the Hardware Security Module (HSM), and keep the others somewhere safe, using secret sharing methods such as [Shamir] for instance. In this case, if a master secret MK_i gets compromised, you can switch to another secret without replacing all the devices. Genius ๐Ÿง 

The catch with the deterministic approach is that if the master secret is exposed, an attacker could rebuild any shared secret from the right public info. That means revoking all secrets, or switching to a new set of secrets if you're using multiple master keys ๐Ÿ˜ญ

On the other hand, the device that stores the master key(s) and generates the shared secrets MUST be tamper resistant. Plus, the HSM won't be exposed outside the validation system's security perimeter, which cuts down the risk of a leak ๐Ÿ”ฅ

Random Generation

The shared secrets are randomly generated. We RECOMMEND following the recommendations in [RFC4086] and picking a good, secure random source for generating these secrets ๐ŸŽฒ A (true) random generator needs a naturally occurring source of randomness. In practice, there are two options to think about for generating the shared secrets:

  • Hardware-based generators: these exploit the randomness that shows up in physical phenomena. A nice implementation can be based on oscillators and built so that active attacks are harder to pull off ๐Ÿ”ง
  • Software-based generators: designing a good software random generator is not an easy task ๐Ÿฅฒ A simple but efficient implementation should be based on various sources and apply a one-way function such as SHA-1 to the sampled sequence.

We RECOMMEND selecting proven products, whether hardware or software generators, for computing shared secrets โœ…

We also RECOMMEND storing the shared secrets securely. Specifically, encrypt them when they're stored, using tamper-resistant hardware encryption, and only expose them when required. For example, the shared secret gets decrypted when it's needed to verify an HOTP value, then re-encrypted immediately so it's only sitting in RAM for a short time ๐ŸงŠ The data store holding the shared secrets MUST be in a secure area, to avoid direct attacks on the validation system and the secrets database as much as possible.

Especially, access to the shared secrets should be limited to the programs and processes that the validation system actually needs. I won't go deep into the specific security mechanisms to put in place, but honestly, protecting shared secrets is of the uttermost importance ๐Ÿซ ๐Ÿ’œ


8. Composite Shared Secrets ๐Ÿงฉ

It may be desirable to add extra authentication factors into the shared secret K. These factors can be any data known at the token but not easily obtained by others. Examples include:

  • PIN or Password obtained as user input at the token
  • Phone number
  • Any unique identifier programmatically available at the token

In this setup, the composite shared secret K gets built during provisioning from a random seed value combined with one or more additional authentication factors. The server can either build it on demand or store composite secrets. Either way, depending on the implementation, the token only stores the seed value. When the token runs the HOTP calculation, it computes K from the seed value plus the locally derived or input values of the other factors ๐ŸŒˆ

Composite secrets can strengthen HOTP-based auth by adding more factors at the token. As long as the token is a trusted device, there's an extra perk: the factors (like a user-input PIN) never have to be exposed to other devices ๐ŸŽ€


9. Bi-Directional Authentication ๐Ÿ”

Here's a fun one. The HOTP client could also be used to authenticate the validation server, proving it's a genuine entity that knows the shared secret ๐Ÿ‘€

Since the HOTP client and the server are synchronized and share the same secret (or a method to recompute it), a simple 3-pass protocol could be put in place:

1- The end user enter the TokenID and a first OTP value OTP1;
2- The server checks OTP1 and if correct, sends back OTP2;
3- The end user checks OTP2 using his HOTP device and if correct,
   uses the web site.

Obviously, like I said before, all the OTP communications have to happen over a secure channel, e.g., SSL/TLS, IPsec connections ๐Ÿ”’


10. Conclusion ๐ŸŽฌ

This document describes HOTP, a HMAC-based One-Time Password algorithm. It also recommends the preferred implementation and related modes of operation for deploying the algorithm ๐Ÿ’–

The document also covers security and shows that the HOTP algorithm is practical and sound. The best possible attack is a brute force attack, and that can be prevented by carefully implementing countermeasures in the validation server ๐Ÿ›ก๏ธ

Finally, several enhancements have been proposed to improve security for specific applications if needed โœจ

11. Acknowledgements ๐Ÿซถ

The authors would like to thank Siddharth Bajaj, Alex Deacon, Loren Hart, and Nico Popp for their help during the conception and redaction of this document ๐ŸŒท

12. Contributors ๐Ÿ‘‘

The authors of this document would like to emphasize the role of three persons who made a key contribution to this document:

  • Laszlo Elteto is system architect with SafeNet, Inc.
  • Ernesto Frutos is director of Engineering with Authenex, Inc.
  • Fred McClain is Founder and CTO with Boojum Mobile, Inc.

Without their advice and valuable input, this document would not be the same ๐Ÿฅน

13. References ๐Ÿ“š

13.1. Normative References

[BCK1]     M.  Bellare, R.  Canetti and H.  Krawczyk, "Keyed Hash
           Functions and Message Authentication", Proceedings of
           Crypto'96, LNCS Vol. 1109, pp. 1-15.

[BCK2]     Krawczyk, H., Bellare, M., and R. Canetti, "HMAC: Keyed-
           Hashing for Message Authentication", RFC 2104, February
           1997.

[RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
           Requirement Levels", BCP 14, RFC 2119, March 1997.

[RFC3979]  Bradner, S., "Intellectual Property Rights in IETF
           Technology", BCP 79, RFC 3979, March 2005.

[RFC4086]  Eastlake, D., 3rd, Schiller, J., and S.  Crocker,
           "Randomness Requirements for Security", BCP 106, RFC 4086,
           June 2005.

13.2. Informative References

[OATH]     Initiative for Open AuTHentication
           http://www.openauthentication.org

[PrOo]     B.  Preneel and P. van Oorschot, "MD-x MAC and building
           fast MACs from hash functions", Advances in Cryptology
           CRYPTO '95, Lecture Notes in Computer Science Vol. 963, D.
           Coppersmith ed., Springer-Verlag, 1995.

[Crack]    Crack in SHA-1 code 'stuns' security gurus
           http://www.eetimes.com/showArticle.jhtml?
           articleID=60402150

[Sha1]     Bruce Schneier.  SHA-1 broken.  February 15, 2005.
           http://www.schneier.com/blog/archives/2005/02/
           sha1_broken.html

[Res]      Researchers: Digital encryption standard flawed
           http://news.com.com/
           Researchers+Digital+encryption+standard+flawed/
           2100-1002-5579881.html?part=dht&tag=ntop&tag=nl.e703

[Shamir]   How to Share a Secret, by Adi Shamir.  In Communications
           of the ACM, Vol. 22, No. 11, pp. 612-613, November, 1979.

Appendix A - HOTP Algorithm Security: Detailed Analysis ๐Ÿ”โœจ

okay bestie, this is the deep dive ๐Ÿค“๐Ÿ’œ we're going to look at the sneakiest attacks on HOTP, how secure it is under different assumptions, how the truncation step changes things, and what we'd recommend for the number of digits. we're focusing on the case where Digit = 6, so HOTP spits out 6-digit values, which is the bare minimum recommended in this document. it's the main character here ๐Ÿ’…

A.1. Definitions and Notations ๐Ÿ“š

we write {0,1}^l for the set of all strings of length l ๐Ÿซถ

Z_{n} = {0,.., n - 1}

IntDiv(a,b) is our integer division helper. it takes integers a and b where a >= b >= 1, and it gives back (q,r), the quotient and remainder of dividing a by b. so a = bq + r and 0 <= r < b โœจ

H is the base function: {0,1}^k x {0,1}^c --> {0,1}^n. it takes a k-bit key K and a c-bit counter C, and returns an n-bit output H(K,C). for HOTP, H is HMAC-SHA-1, but we use this formal definition so the proof generalizes ๐Ÿง 

A.2. The Idealized Algorithm: HOTP-IDEAL ๐Ÿชž

now we make an idealized twin of HOTP, called HOTP-IDEAL. in this version, H gets swapped out for a random function that acts as the key ๐ŸŽฒ

more precisely, Maps(c,n) is the set of all functions from {0,1}^c to {0,1}^n. the idealized algorithm has key space Maps(c,n), so a "key" here is a function h from {0,1}^c to {0,1}^n. we imagine this key gets drawn at random ๐ŸŽฐ

it's not feasible to actually implement this, because a function from {0,1}^c to {0,1}^n is way too big to even store ๐Ÿ’€ so why bother? ๐Ÿค”

the payoff is this: our analysis will show that as long as H satisfies a certain well-accepted assumption, the actual and idealized algorithms are, for all practical purposes, equally secure. so the real job is to figure out how secure the idealized algorithm is. ๐Ÿซถ

we're basically judging the quality of the algorithm's design on its own, separate from HMAC-SHA-1. and honestly, that's the important question ๐Ÿ”ฅ

A.3. Model of Security ๐Ÿ•ต๏ธโ€โ™€๏ธ

this section lays out the threats we're worried about, so we can test how secure HOTP and HOTP-IDEAL really are. we write ALG for either HOTP or HOTP-IDEAL in this analysis ๐Ÿ’œ

here's the setup: a user and a server share a key K for ALG. both keep a counter C, starting at zero. the user proves who they are by sending ALG(K,C) to the server, and the server accepts if the value is correct โœจ

to guard against the user's counter accidentally running ahead, the server takes a received value z and accepts it as long as z equals ALG(K,i) for some i in the range C,...,C + s-1. here s is the resynchronization parameter and C is the server's counter. if it accepts with some value of i, it bumps its counter to i+1. if it doesn't accept, the counter stays put ๐Ÿ”„

now the fun part: what can the adversary do, and what counts as winning? ๐Ÿ˜ˆ first, the adversary can eavesdrop, which means it can see the authenticator the user sends. second, the adversary wins if it gets the server to accept an authenticator for a counter value the user never sent one for ๐Ÿšจ

the formal adversary, called B, starts out knowing which algorithm ALG is being used, knowing how the system is designed, and knowing all the system parameters. the only thing it doesn't get upfront is the shared key K ๐Ÿ”‘

B gets full control over when things happen. it has access to an authenticator oracle that stands in for the user. by calling it, B can make the user authenticate and get the authenticator back. it can do this as often as it wants and whenever it wants, and it can use what it collects to try to "learn" how to make authenticators itself ๐Ÿงช at any time, it can also call a verification oracle and hand it a candidate authenticator of its own choosing. it wins if the server accepts that candidate โญ

here's the game. the adversary B is trying to break the security of an authentication algorithm ALG: K x {0,1}^c --> R.

Initializations - A key K is selected at random from K, a counter C
is initialized to 0, and the Boolean value win is set to false.

Game execution - Adversary B is provided with the two following
oracles:

Oracle AuthO()
--------------
   A = ALG(K,C)
   C = C + 1
   Return O to B

Oracle VerO(A)
--------------
   i = C
   While (i <= C + s - 1 and Win == FALSE) do
      If A == ALG(K,i) then Win = TRUE; C = i + 1
      Else i = i + 1
   Return Win to B

AuthO() is the authenticator oracle and VerO(A) is the verification oracle ๐ŸŽ€

B can query the two oracles as much as it likes. let Adv(B) be the probability that win gets set to true in this game. that's the chance the adversary successfully impersonates the user ๐Ÿ˜ฑ

our goal is to figure out how big that value can get, as a function of three things: the number v of verification queries B makes, the number a of authenticator oracle queries B makes, and the running time t of B. this tells us how to set the throttle, which basically caps v ๐Ÿซง

A.4. Security of the Ideal Authentication Algorithm ๐Ÿ›ก๏ธ

this section sums up the security analysis of HOTP-IDEAL. we start with what happens when we convert to digits by taking modulo 10^Digit, and then we go through the different attacks one by one ๐Ÿ’…

A.4.1. From Bits to Digits ๐Ÿ”ข

when you do dynamic offset truncation on a random n-bit string, you get a random 31-bit string. but what happens to the distribution when we take it modulo m = 10^Digit, which is exactly what HOTP does? ๐Ÿค” the lemma below estimates the biases in the outputs in that case ๐ŸŒˆ

Lemma 1
-------
Let N >= m >= 1 be integers, and let (q,r) = IntDiv(N,m).  For z in
Z_{m} let:

       P_{N,m}(z) = Pr [x mod m = z : x randomly pick in Z_{n}]

Then for any z in Z_{m}

P_{N,m}(z) =   (q + 1) / N    if 0 <= z < r
               q / N          if r <= z < m
Proof of Lemma 1
----------------
Let the random variable X be uniformly distributed over Z_{N}.  Then:

P_{N,m}(z)  = Pr [X mod m = z]

            = Pr [X < mq] * Pr [X mod m = z| X < mq]
            + Pr [mq <= X < N] * Pr [X mod m = z| mq <= X < N]

            = mq/N * 1/m +
               (N - mq)/N * 1 / (N - mq)     if 0 <= z < N - mq
               0                             if N - mq <= z <= m

            = q/N +
               r/N * 1 / r                   if 0 <= z < N - mq
               0                             if r <= z <= m

Simplifying yields the claimed equation.

so let's plug in the real numbers: N = 2^31, d = 6, and m = 10^d. if x is picked at random from Z_{N} (a random 31-bit string), then reducing it to a 6-digit number with x mod m does NOT give you a random 6-digit number ๐Ÿ˜ญ the tea is that the output is lopsided, and it's shown in this table:

Values               Probability that each appears as output
----------------------------------------------------------------
0,1,...,483647       2148/2^31 roughly equals to 1.00024045/10^6
483648,...,999999    2147/2^31 roughly equals to 0.99977478/10^6

so if X is uniformly distributed over Z_{2^31} (a random 31-bit string), the table shows the probabilities for each output of X mod 10^6. the first group of values shows up with a probability just above 10^-6, and the rest show up with a probability just below it. the distribution is slightly non-uniform, but only slightly ๐Ÿฆ‹

still, the bias is tiny. as we'll see later, it's negligible: the probabilities are all super close to 10^-6 ๐Ÿซถ

A.4.2. Brute Force Attacks ๐Ÿ’ฅ

if the authenticator was made of d random digits, a brute force attack using v verification attempts would succeed with probability sv/10^Digit ๐ŸŽฏ

but an adversary can exploit the bias in the outputs of HOTP-IDEAL (the one Lemma 1 predicted) to launch a slightly better attack ๐Ÿ‘€ specifically, it makes authentication attempts using the most likely authenticators, which are the ones in the range 0,...,r - 1, where (q,r) = IntDiv(2^31,10^Digit).

the next bit specifies an adversary in our security model that runs this attack. it also estimates the success probability as a function of the number of verification queries ๐Ÿงฎ

to keep things simple, we assume the number of verification queries is at most r. with N = 2^31 and m = 10^6, we get r = 483,648. the throttle value is definitely below that, so this assumption isn't much of a restriction at all โœจ

Proposition 1
-------------

Suppose m = 10^Digit < 2^31, and let (q,r) = IntDiv(2^31,m).  Assume
s <= m.  The brute-force-attack adversary B-bf attacks HOTP using v
<= r verification oracle queries.  This adversary makes no
authenticator oracle queries, and succeeds with probability

                 Adv(B-bf) = 1 - (1 - v(q+1)/2^31)^s

which is roughly equal to

                          sv * (q+1)/2^31

With m = 10^6 we get q = 2,147.  In that case, the brute force attack
using v verification attempts succeeds with probability

      Adv(B-bf) roughly = sv * 2148/2^31 = sv * 1.00024045/10^6
โš ๏ธ the resynchronization parameter s has a big impact. the adversary's success probability is proportional to s, which means s can't be made too large without wrecking security ๐Ÿ™ˆ

A.4.3. Brute force attacks are the best possible attacks. ๐Ÿ†

the big question is whether there are any attacks better than brute force ๐Ÿคจ specifically, the brute force attack didn't bother collecting the authenticators the user sent and trying to cryptanalyze them to figure out how to build better authenticators. would doing that actually help? is there some way to "learn" how to make authenticators that beat the brute force success rate?

the answer is no ๐Ÿ™…โ€โ™€๏ธ no matter what strategy the adversary uses, and even if it sees the user's authentication attempts and tries to exploit them, its success probability won't go above the brute force attack's. and this holds as long as the number of authentications it observes isn't incredibly huge. this is super valuable info for judging the scheme's security ๐Ÿ’–

Proposition 2
-------------
Suppose m = 10^Digit < 2^31, and let (q,r) = IntDiv(2^31,m).  Let B be
any adversary attacking HOTP-IDEAL using v verification oracle queries
and a <= 2^c - s authenticator oracle queries.  Then

                     Adv(B) < = sv * (q+1)/ 2^31
๐Ÿ“ this result is conditional on the adversary not seeing more than 2^c - s authentications performed by the user. honestly that's hardly restrictive, as long as c is large enough ๐Ÿซง

with m = 10^6, we get q = 2,147. in that case, Proposition 2 says that any adversary B attacking HOTP-IDEAL and making v verification attempts succeeds with a probability of at most:

Equation 1
----------
           sv * 2148/2^31 roughly = sv * 1.00024045/10^6

so, B's success rate is never more than what the brute force attack gets ๐ŸŒˆ๐Ÿ‘‘

A.5. Security Analysis of HOTP โœจ

Okay bestie, so we've already looked at the idealized versions of HOTP, which are called HOTP-IDEAL ๐Ÿง . Now we check whether the real HOTP algorithm is basically just as strong. We can show that it is, as long as one well-believed assumption about H holds ๐Ÿ’œ.

That assumption is that H is a secure pseudorandom function, or PRF ๐Ÿ”. In practice, that means its input-output values look indistinguishable from those of a random function.

Now picture an adversary A that gets an oracle for a function f: {0,1}^c --> {0, 1}^n and eventually outputs a bit ๐Ÿ‘€. We write Adv(A) for the prf-advantage of A, which measures how well A can tell the case where its oracle is H(K,.) apart from the case where its oracle is a random function from {0,1}^c to {0,1}^n.

There's one obvious attack, which is exhaustive search for the key K. If A runs for t steps, and T is the time to do one computation of H, then its prf-advantage from this attack works out to (t/T)2^-k ๐Ÿ”Ž. Another option is a birthday attack [PrOo]. With this one, A can reach advantage p^2/2^n using p oracle queries and a running time of about pT โฑ๏ธ.

We're assuming these are the best possible attacks ๐Ÿ™. That leads to the following.

Assumption 1

Let T denote the time to perform one computation of H. Then if A is any adversary with running time at most t and making at most p oracle queries,

Adv(A) <= (t/T)/2^k + p^2/2^n

In practice, this assumption means H is very secure as a PRF ๐Ÿ’ช. For example, if k = n = 160, an attacker with running time 2^60 and 2^40 oracle queries has advantage at most (about) 2^-80 ๐Ÿซถ.

Theorem 1

Suppose m = 10^Digit < 2^31, and let (q,r) = IntDiv(2^31,m). Let B be any adversary attacking HOTP using v verification oracle queries, a <= 2^c - s authenticator oracle queries, and running time t. Let T denote the time to perform one computation of H. If Assumption 1 is true, then

      Adv(B) <= sv * (q + 1)/2^31 + (t/T)/2^k + ((sv + a)^2)/2^n

Here's the vibe: the (t/T)2^-k + ((sv + a)^2)2^-n term is way smaller than the sv(q + 1)/2^n term ๐Ÿค. So for all practical purposes, the success rate of an adversary attacking HOTP is sv(q + 1)/2^n, which is exactly the same as for HOTP-IDEAL ๐ŸŽฏ. Translation: HOTP is basically as good as its idealized counterpart, periodt ๐Ÿ’….

When m = 10^6, which is a 6-digit output, an adversary making v authentication attempts has a success rate that is at most that of Equation 1 ๐Ÿ”ข.

For example, take an adversary with running time at most 2^60 that sees at most 2^40 authentication attempts from the user ๐Ÿ˜ณ. Both of those numbers are super generous to the adversary, since they usually won't have that many resources ๐Ÿ™ƒ. Even so, a powerful adversary like this still won't get more success than Equation 1 says ๐Ÿ’€.

We can safely assume sv <= 2^40, thanks to the throttling and the bounds on s ๐Ÿ›‘. So:

    (t/T)/2^k + ((sv + a)^2)/2^n  <= 2^60/2^160 + (2^41)^2/2^160
                                 roughly <= 2^-78

That's way smaller than the success probability in Equation 1, and basically negligible next to it ๐ŸŒธ.


Appendix B - SHA-1 Attacks

This section covers the impact of the recent attacks on SHA-1 on HMAC-SHA-1-based HOTP ๐Ÿ”. We'll start with what's going on with SHA-1 itself, then look at how it affects HMAC-SHA-1 and HOTP. Cited references are in Section 13 ๐Ÿ“š.

B.1. SHA-1 Status

A collision for a hash function h is a pair x,y of different inputs where h(x)=h(y) ๐Ÿ’. SHA-1 outputs 160 bits, so a birthday attack finds a collision in 2^{80} trials. (A trial just means one computation of the function.) That was thought to be the best possible until Wang, Yin, and Yu announced on February 15, 2005, that they had an attack finding collisions in 2^{69} trials ๐Ÿ˜ฎ.

Is SHA-1 broken? Ngl, for most practical purposes, probably not ๐Ÿ™…โ€โ™€๏ธ, because the resources needed to pull off the attack are huge. Here's one way to get a sense of it: the cost is about the same as factoring a 760-bit RSA modulus, and that's currently considered out of reach ๐Ÿšซ.

Burr of NIST is quoted in [Crack] as saying "Large national intelligence agencies could do this in a reasonable amount of time with a few million dollars in computer time". However, the computation may still be out of reach for everyone except those very well-funded agencies ๐Ÿ•ต๏ธโ€โ™€๏ธ.

We should also ask what finding SHA-1 collisions actually does to real applications, like signatures โœ๏ธ. To use a collision x,y to forge signatures, you'd need to somehow get a signature of x, and then you could forge a signature of y. How damaging that is depends on the content of y: the y made by the attack may not mean anything in the application context ๐Ÿคทโ€โ™€๏ธ. Also, you'd need a chosen-message attack to get the signature of x. That seems possible in some contexts but not others. Overall, it's not clear that the impact on the security of signatures is significant ๐Ÿค”.

Indeed, you can read in the press that SHA-1 is "broken" [Sha1], and that encryption and SSL are "broken" [Res]. The media tends to blow things up ๐Ÿ“ฐ. It would hardly be interesting to announce in the news that a team of cryptanalysts did some very interesting theoretical work attacking SHA-1 ๐Ÿ˜ด.

Cryptographers are excited too, but mainly because this is an important theoretical breakthrough ๐Ÿค“. Attacks can only get better with time, so it's important to keep an eye on any progress in hash function cryptanalysis, and to be ready for any really practical break with a sound migration plan for the future ๐Ÿ—“๏ธ๐Ÿซถ.

B.2. HMAC-SHA-1 Status

The new attacks on SHA-1 have no impact on the security of HMAC-SHA-1 ๐ŸŽ‰. The best attack on HMAC-SHA-1 still needs a sender to authenticate 2^{80} messages before an adversary can create a forgery. Why? ๐Ÿ‘€

HMAC is not a hash function. It's a message authentication code (MAC) that uses a hash function internally ๐Ÿง. A MAC depends on a secret key, while hash functions don't. What you need to worry about with a MAC is forgery, not collisions ๐Ÿ”‘. HMAC was designed so that collisions in the hash function (here SHA-1) do not produce forgeries for HMAC ๐Ÿ›ก๏ธ.

Recall that HMAC-SHA-1(K,x) = SHA-1(K_o,SHA-1(K_i,x)), where the keys K_o and K_i are derived from K:

HMAC-SHA-1(K,x) = SHA-1(K_o,SHA-1(K_i,x))

Suppose the attacker finds a pair x,y such that SHA-1(K_i,x) = SHA-1(K_i,y). Call that a hidden-key collision ๐Ÿ•ถ๏ธ. Then, if the attacker can obtain the MAC of x (which is itself a tall order ๐Ÿ˜…), it can forge the MAC of y, since those values are the same. But finding hidden-key collisions is harder than finding ordinary collisions, because the attacker doesn't know the hidden key K_i. All it may have is some outputs of HMAC-SHA-1 with key K. To date, there are no claims or evidence that the recent attacks on SHA-1 extend to finding hidden-key collisions ๐Ÿ™Œ.

The HMAC design has already proven itself in this regard, historically speaking ๐Ÿ†. MD5 is considered broken, in that collisions in that hash function can be found relatively easily. But there's still no attack on HMAC-MD5 better than the trivial 2^{64} time birthday one. (MD5 outputs 128 bits, not 160.) We're seeing this strength of HMAC come into play again in the SHA-1 context ๐Ÿ’ชโœจ.

B.3. HOTP Status

Since no new weakness has surfaced in HMAC-SHA-1, there's no impact on HOTP ๐Ÿฅณ. The best attacks on HOTP are still the ones described in the document, namely trying to guess output values ๐ŸŽฒ.

The security proof of HOTP requires that HMAC-SHA-1 behaves like a pseudorandom function. The new attacks on SHA-1 don't affect how good HMAC-SHA-1 is as a pseudorandom function, so this proven guarantee stands too ๐Ÿซถ๐Ÿ’œ.

Appendix C - HOTP Algorithm: Reference Implementation ๐Ÿ’–โœจ

Okay bestie, here's the reference implementation, and it's giving full Java ๐ŸŽ€ Yes, it's long, but every line is part of the vibe.

/*
 * OneTimePasswordAlgorithm.java
 * OATH Initiative,
 * HOTP one-time password algorithm
 *
 */

/* Copyright (C) 2004, OATH.  All rights reserved.
 *
 * License to copy and use this software is granted provided that it
 * is identified as the "OATH HOTP Algorithm" in all material
 * mentioning or referencing this software or this function.
 *
 * License is also granted to make and use derivative works provided
 * that such works are identified as
 *  "derived from OATH HOTP algorithm"
 * in all material mentioning or referencing the derived work.
 *
 * OATH (Open AuTHentication) and its members make no
 * representations concerning either the merchantability of this
 * software or the suitability of this software for any particular
 * purpose.
 *
 * It is provided "as is" without express or implied warranty
 * of any kind and OATH AND ITS MEMBERS EXPRESSaLY DISCLAIMS
 * ANY WARRANTY OR LIABILITY OF ANY KIND relating to this software.
 *
 * These notices must be retained in any copies of any part of this
 * documentation and/or software.
 */

package org.openauthentication.otp;

import java.io.IOException;
import java.io.File;
import java.io.DataInputStream;
import java.io.FileInputStream ;
import java.lang.reflect.UndeclaredThrowableException;

import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
 * This class contains static methods that are used to calculate the
 * One-Time Password (OTP) using
 * JCE to provide the HMAC-SHA-1.
 *
 * @author Loren Hart
 * @version 1.0
 */
public class OneTimePasswordAlgorithm {
    private OneTimePasswordAlgorithm() {}

    // These are used to calculate the check-sum digits.
    //                                0  1  2  3  4  5  6  7  8  9
    private static final int[] doubleDigits =
                    { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };

    /**
     * Calculates the checksum using the credit card algorithm.
     * This algorithm has the advantage that it detects any single
     * mistyped digit and any single transposition of
     * adjacent digits.
     *
     * @param num the number to calculate the checksum for
     * @param digits number of significant places in the number
     *
     * @return the checksum of num
     */
    public static int calcChecksum(long num, int digits) {
        boolean doubleDigit = true;
        int     total = 0;
        while (0 < digits--) {
            int digit = (int) (num % 10);
            num /= 10;
            if (doubleDigit) {
                digit = doubleDigits[digit];
            }
            total += digit;
            doubleDigit = !doubleDigit;
        }
        int result = total % 10;
        if (result > 0) {
            result = 10 - result;
        }
        return result;
    }

    /**
     * This method uses the JCE to provide the HMAC-SHA-1
     * algorithm.
     * HMAC computes a Hashed Message Authentication Code and
     * in this case SHA1 is the hash algorithm used.
     *
     * @param keyBytes   the bytes to use for the HMAC-SHA-1 key
     * @param text       the message or text to be authenticated.
     *
     * @throws NoSuchAlgorithmException if no provider makes
     *       either HmacSHA1 or HMAC-SHA-1
     *       digest algorithms available.
     * @throws InvalidKeyException
     *       The secret provided was not a valid HMAC-SHA-1 key.
     *
     */

    public static byte[] hmac_sha1(byte[] keyBytes, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeyException
    {
//        try {
            Mac hmacSha1;
            try {
                hmacSha1 = Mac.getInstance("HmacSHA1");
            } catch (NoSuchAlgorithmException nsae) {
                hmacSha1 = Mac.getInstance("HMAC-SHA-1");
            }
            SecretKeySpec macKey =
        new SecretKeySpec(keyBytes, "RAW");
            hmacSha1.init(macKey);
            return hmacSha1.doFinal(text);
//        } catch (GeneralSecurityException gse) {
//            throw new UndeclaredThrowableException(gse);
//        }
    }

    private static final int[] DIGITS_POWER
  // 0 1  2   3    4     5      6       7        8
  = {1,10,100,1000,10000,100000,1000000,10000000,100000000};

    /**
     * This method generates an OTP value for the given
     * set of parameters.
     *
     * @param secret       the shared secret
     * @param movingFactor the counter, time, or other value that
     *                     changes on a per use basis.
     * @param codeDigits   the number of digits in the OTP, not
     *                     including the checksum, if any.
     * @param addChecksum  a flag that indicates if a checksum digit
     *                     should be appended to the OTP.
     * @param truncationOffset the offset into the MAC result to
     *                     begin truncation.  If this value is out of
     *                     the range of 0 ... 15, then dynamic
     *                     truncation  will be used.
     *                     Dynamic truncation is when the last 4
     *                     bits of the last byte of the MAC are
     *                     used to determine the start offset.
     * @throws NoSuchAlgorithmException if no provider makes
     *                     either HmacSHA1 or HMAC-SHA-1
     *                     digest algorithms available.
     * @throws InvalidKeyException
     *                     The secret provided was not
     *                     a valid HMAC-SHA-1 key.
     *
     * @return A numeric String in base 10 that includes
     * {@link codeDigits} digits plus the optional checksum
     * digit if requested.
     */
    static public String generateOTP(byte[] secret,
               long movingFactor,
          int codeDigits,
               boolean addChecksum,
          int truncationOffset)
        throws NoSuchAlgorithmException, InvalidKeyException
    {
        // put movingFactor value into text byte array
  String result = null;
  int digits = addChecksum ? (codeDigits + 1) : codeDigits;
        byte[] text = new byte[8];
        for (int i = text.length - 1; i >= 0; i--) {
            text[i] = (byte) (movingFactor & 0xff);
            movingFactor >>= 8;
        }

        // compute hmac hash
        byte[] hash = hmac_sha1(secret, text);

        // put selected bytes into result int
        int offset = hash[hash.length - 1] & 0xf;
  if ( (0<=truncationOffset) &&
         (truncationOffset<(hash.length-4)) ) {
      offset = truncationOffset;
  }
        int binary =
            ((hash[offset] & 0x7f) << 24)
            | ((hash[offset + 1] & 0xff) << 16)
            | ((hash[offset + 2] & 0xff) << 8)
            | (hash[offset + 3] & 0xff);

        int otp = binary % DIGITS_POWER[codeDigits];
  if (addChecksum) {
      otp =  (otp * 10) + calcChecksum(otp, codeDigits);
  }
  result = Integer.toString(otp);
  while (result.length() < digits) {
      result = "0" + result;
  }
  return result;
    }
}

Appendix D - HOTP Algorithm: Test Values ๐Ÿงš

Okay, test vectors time, and these are the receipts. We're using the ASCII string "12345678901234567890" as the secret, which in hex is Secret = 0x3132333435363738393031323334353637383930 ๐Ÿ“

Table 1 shows the intermediate HMAC value for each count, so you can see the raw output before anything gets chopped up ๐Ÿ‘€

Count    Hexadecimal HMAC-SHA-1(secret, count)
0        cc93cf18508d94934c64b65d8ba7667fb7cde4b0
1        75a48a19d4cbe100644e8ac1397eea747a2d33ab
2        0bacb7fa082fef30782211938bc1c5e70416ff44
3        66c28227d03a2d5529262ff016a1e6ef76557ece
4        a904c900a64b35909874b33e61c5938a8e15ed1c
5        a37e783d7b7233c083d4f62926c7a25f238d0316
6        bc9cd28561042c83f219324d3c607256c03272ae
7        a4fb960c0bc06e1eabb804e5b397cdc4b45596fa
8        1b3c89f65e6c9e883012052823443f048b4332db
9        1637409809a679dc698207310c8c7fc07290d9e5

Table 2 is the glow-up ๐Ÿ’… For each count it shows the truncated values, in both hex and decimal, and then the final HOTP value you actually get to use.

                 Truncated
Count    Hexadecimal    Decimal        HOTP
0        4c93cf18       1284755224     755224
1        41397eea       1094287082     287082
2         82fef30        137359152     359152
3        66ef7655       1726969429     969429
4        61c5938a       1640338314     338314
5        33c083d4        868254676     254676
6        7256c032       1918287922     287922
7         4e5b397         82162583     162583
8        2823443f        673399871     399871
9        2679dc69        645520489     520489

Appendix E - Extensions โœจ

Okay so this last bit is all about enhancements we could bolt on to HOTP ๐Ÿฆ‹ None of these are recommended extensions or part of the standard algorithm. They're just variations a customised implementation could use, so don't go treating them like the official rules, bestie ๐Ÿซถ

E.1. Number of Digits ๐Ÿ”ฅ

A simple security win is to pull more digits out of the HMAC-SHA-1 value.

For example, if you calculate the HOTP value modulo 10^8 to build an 8-digit HOTP value, the probability of success for the adversary drops from sv/10^6 to sv/10^8. Iconic ๐Ÿ™Œ

This could also let you improve usability, like by increasing T and/or s, and you'd still end up with better security overall. For instance, s = 10 gives 10v/10^8 = v/10^7 < v/10^6, which is the theoretical optimum for a 6-digit code when s = 1. Main character energy ๐Ÿ‘‘

E.2. Alphanumeric Values ๐ŸŒˆ

Another option is to use A-Z and 0-9 values, or really a subset of 32 symbols picked from the alphanumeric alphabet, so people don't get confused. 0, O, and Q look basically the same, and so do l, 1, and I, especially on a tiny display ๐Ÿ’€

The immediate consequence is that the security is now on the order of sv/32^6 for a 6-digit HOTP value, and sv/32^8 for an 8-digit HOTP value.

32^6 > 10^9, so a 6-alphanumeric HOTP code is slightly better than a 9-digit HOTP value, which is the maximum length of an HOTP code supported by the proposed algorithm.

32^8 > 10^12, so an 8-alphanumeric HOTP code is significantly better than a 9-digit HOTP value. Literally ate ๐Ÿฐ

Depending on the application and on the token and interface used to display and enter the HOTP value, going alphanumeric could be a simple, efficient way to level up security at a reduced cost and impact on users ๐Ÿงš

E.3. Sequence of HOTP Values ๐Ÿ’œ

As we suggested for resynchronization, where you enter a short sequence (say, 2 or 3) of HOTP values, we could generalise the concept to the protocol and add a parameter L that defines the length of the HOTP sequence to enter.

By default, the value L SHOULD be set to 1. But if security needs a boost, users might be asked (possibly for a short period of time, or for a specific operation) to enter L HOTP values.

This is another way to tighten security without making the HOTP longer or switching to alphanumeric values ๐Ÿซถ

Note: The system MAY also be programmed to request synchronization on a regular basis (e.g., every night, twice a week, etc.), and to achieve this purpose, ask for a sequence of L HOTP values. ๐Ÿ™ˆ

E.4. A Counter-Based Resynchronization Method ๐Ÿ”

okay so this one assumes the client can send over more than just the HOTP value. it can also send the counter value itself ๐Ÿ‘€ bestie, that's the glow-up, because the HOTP value now acts as a message authentication code of the counter ๐Ÿ”โœจ

Resynchronization Counter-based Protocol (RCP)

the server accepts only if ALL of these are true, where C-server is its own current counter value ๐Ÿ’…

1) C-client >= C-server
2) C-client - C-server <= s
3) Check that HOTP client is valid HOTP(K,C-Client)
4) If true, the server sets C to C-client + 1 and client is
   authenticated

no more managing a look-ahead window ๐Ÿ™Œ the adversary's chance of winning is just v/10^6, or roughly v in one million ๐ŸŽฏ and the side benefit? you can increase s "infinitely" and the system gets way more usable without hurting security ๐ŸŒธ

This resynchronization protocol SHOULD be used whenever the related impact on the client and server applications is deemed acceptable. ๐Ÿฆ‹

E.5. Data Field ๐ŸŽ€

another cute option is adding a Data field to the OTP generation, like HOTP (K, C, [Data]). Data is optional and can be a bunch of identity-related info stuck together, e.g., Data = Address | PIN ๐Ÿ’–

we could also use a Timer, either solo as the moving factor or mixed in with the Counter. so Data = Timer, where Timer could be UNIX-time (GMT seconds since 1/1/1970) divided by some factor (8, 16, 32, etc.) to get a specific time step โฐ the OTP's time window is then the time step multiplied by the resynchronization parameter from before. for example, 64 seconds as the time step and 7 for the resync parameter gives you an acceptance window of +/- 3 minutes ๐Ÿงš

the Data field gives you way more flexibility in how you implement the algorithm ๐Ÿ’œ just make sure the Data field is clearly specified, or everyone's gonna be confused ๐Ÿ’€

Authors' Addresses โœจ

David M'Raihi (primary contact for sending comments and questions) ๐Ÿ’Œ

David M'Raihi (primary contact for sending comments and questions)
VeriSign, Inc.
685 E. Middlefield Road
Mountain View, CA 94043 USA

Phone: 1-650-426-3832
EMail: dmraihi@verisign.com
Mihir Bellare
Dept of Computer Science and Engineering, Mail Code 0114
University of California at San Diego
9500 Gilman Drive
La Jolla, CA 92093, USA

EMail: mihir@cs.ucsd.edu
Frank Hoornaert
VASCO Data Security, Inc.
Koningin Astridlaan 164
1780 Wemmel, Belgium

EMail: frh@vasco.com
David Naccache
Gemplus Innovation
34 rue Guynemer, 92447,
Issy les Moulineaux, France
and
Information Security Group,
Royal Holloway,
University of London, Egham,
Surrey TW20 0EX, UK

EMail: david.naccache@gemplus.com, david.naccache@rhul.ac.uk
Ohad Ranen
Aladdin Knowledge Systems Ltd.
15 Beit Oved Street
Tel Aviv, Israel 61110

EMail: Ohad.Ranen@ealaddin.com

Copyright (C) The Internet Society (2005).

This document is subject to the rights, licenses and restrictions contained in BCP 78, and except as set forth therein, the authors retain all their rights.

This document and the information contained herein are provided on an "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Intellectual Property ๐Ÿ”ฅ

The IETF takes no position regarding the validity or scope of any Intellectual Property Rights or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; nor does it represent that it has made any independent effort to identify any such rights. Information on the procedures with respect to rights in RFC documents can be found in BCP 78 and BCP 79.

Copies of IPR disclosures made to the IETF Secretariat and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this specification can be obtained from the IETF on-line IPR repository at http://www.ietf.org/ipr.

The IETF invites any interested party to bring to its attention any copyrights, patents or patent applications, or other proprietary rights that may cover technology that may be required to implement this standard. Please address the information to the IETF at ietf-ipr@ietf.org.

Acknowledgement ๐Ÿซถ

Funding for the RFC Editor function is currently provided by the Internet Society. ๐Ÿ’œ

๐Ÿ“ฆ where this page comes from