Time-Based One-Time Password (TOTP) — Java Implementation

Rakesh Rathi
3 min readSep 30, 2023

--

The Time-Based One-Time Password (TOTP) algorithm is frequently utilized to generate unique codes, primarily for two-factor authentication and various security functions. For an in-depth example, see my Java implementation on GitHub. Let’s delve deeper into the code specifics:

For the complete code, visit my Java implementation.

Overview

The provided Java class, TimeBasedOnetimePassword, implements the TOTP algorithm using HMAC-SHA1 as the cryptographic function. The class also includes methods for Base32 encoding and decoding, which is a common format for representing the secret key in TOTP implementations.

Base32 Encoding and Decoding

Before diving into the TOTP algorithm, let’s understand the Base32 encoding and decoding methods:

Base32 Encoding

Base32 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. The specific character set used in this implementation omits the numbers 0, 1, 8, and 9 to reduce the possibility of human misinterpretation.

The method encodeBase32 takes an input string and returns its Base32 encoded representation. The encoding process involves:

  1. Iterating over each byte of the input.
  2. Shifting and buffering the byte data.
  3. Extracting 5-bit groups from the buffer and converting them to Base32 characters.
  4. Padding the result with ‘=’ characters to ensure the output length is a multiple of 8.

Base32 Decoding

The decodeBase32 method reverses the encoding process. It:

  1. Removes any padding characters.
  2. Iterates over the Base32 encoded string.
  3. Uses a lookup table to convert Base32 characters back to their binary representation.
  4. Extracts 8-bit groups from the buffer to reconstruct the original data.

TOTP Generation

The core of the TOTP algorithm lies in the generateTOTP methods. The process involves:

  1. Decoding the Base32 encoded secret key.
  2. Calculating the time interval, which is derived from the current time divided by a predefined time step (30 seconds in this case).
  3. Using the HMAC-SHA1 algorithm to hash the time interval with the secret key.
  4. Extracting a 4-byte dynamic binary code from the hash.
  5. Converting the binary code to a 6-digit number, which is the TOTP.

TOTP Validation

The validateTOTP method checks the validity of a given TOTP against the secret key. It generates TOTPs for the current, previous, and next time intervals and checks if any of them match the input TOTP. This allows for a slight time drift, accommodating scenarios where the client’s clock might be slightly ahead or behind.

--

--