Time-Based One-Time Password (TOTP) — Java Implementation
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:
- Iterating over each byte of the input.
- Shifting and buffering the byte data.
- Extracting 5-bit groups from the buffer and converting them to Base32 characters.
- 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:
- Removes any padding characters.
- Iterates over the Base32 encoded string.
- Uses a lookup table to convert Base32 characters back to their binary representation.
- 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:
- Decoding the Base32 encoded secret key.
- Calculating the time interval, which is derived from the current time divided by a predefined time step (30 seconds in this case).
- Using the HMAC-SHA1 algorithm to hash the time interval with the secret key.
- Extracting a 4-byte dynamic binary code from the hash.
- 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.