Behind the 6-digit code: Building HOTP and TOTP from scratch
a year ago
- #cryptography
- #OTP
- #authentication
- One-Time Passwords (OTPs) are dynamic authentication codes valid for a single use or limited time, reducing replay attack risks.
- HOTP (HMAC-based OTP) uses a counter that increments with each request, while TOTP (Time-based OTP) uses the current time in intervals (e.g., 30 seconds).
- TOTP is derived from HOTP by replacing the counter with a time-based counter, making synchronization easier via technologies like NTP.
- The generation of HOTP involves a secret key, a hash function (e.g., SHA-1), and a digit count, using HMAC for cryptographic security.
- The DT function in HOTP shrinks a 20-byte HMAC output to 4 bytes dynamically, ensuring uniform distribution.
- TOTP's counter is calculated using the formula \( c(t) = \left\lfloor \frac{t - t_0}{X} \right\rfloor \), where \( t_0 \) is the epoch start and \( X \) is the period (e.g., 30 seconds).
- The author created a demo app (https://otp.dogac.dev/) and open-sourced the Kotlin implementation (github.com/Dogacel/otp-server) to help others understand OTP generation.