One Time Passwords in PHP and Google Authenticator

Google Authenticator implements one-time password mechanisms for enhanced security. Rather than relying solely on static passwords, the system generates fresh codes every 30 seconds through time-synchronized algorithms.

How It Works

  1. Share a secret with the authenticator app via QR code
  2. The device displays rotating one-time passwords
  3. Server generates the same codes using the shared secret
  4. User enters the current code during login
  5. Once used, a code is marked invalid—preventing replay attacks

The app requires internet access only for time synchronization. Otherwise it operates completely offline, which is good for privacy.

The Implementation

The system follows RFC specifications for TOTP (Time-based One-Time Passwords) and HOTP (HMAC-based One-Time Passwords). The math involves:

  • A shared secret (base32 encoded)
  • Current Unix timestamp divided by 30-second intervals
  • HMAC-SHA1 generating a hash
  • Dynamic truncation producing a 6-digit code

PHP Library

I created PHP classes and unit tests to simplify implementation. The code is available on GitHub as the “otp” repository.

Features:

  • TOTP and HOTP support
  • QR code generation for easy secret sharing
  • Configurable time windows for clock drift tolerance
  • Unit tested

Feel free to use, modify, and provide feedback. Two-factor authentication shouldn’t be hard to implement.