/php-otp

PHP OTP (One Time Password) Implementation

Primary LanguagePHPMIT LicenseMIT

PHP OTP (One Time Password) Implementation

Build Status StyleCI

A PHP library to generate and verify one-time passwords. It is compatible with HOTP and TOTP.

Prerequisites

This library needs at least PHP 7.0.

Installation

You can install via composer.

$ composer require vjolenz/php-otp

HOTP Usage

Generation and verification requires a moving factor that changes on per use. You can use a login counter as moving factor.

Create Password
   $user = User::find(1);
   
   $authenticator = new \vjolenz\OtpAuth\HotpAuthenticator();
   $authenticator->setSecret('12345678901234567890'); // Default: null
   $authenticator->setAlgorithm('SHA256'); // Default: SHA1
   $authenticator->setWindowSize(3); // Default: 1
   $authenticator->setPasswordLength(9); // Default: 6
   
   $password = $authenticator->generatePassword($user->getLoginCounter());
   
   $user->advanceLoginCounter();
Verify Password
   $user = User::find(1);
   
   $authenticator = new \vjolenz\OtpAuth\HotpAuthenticator();
   $authenticator->setSecret('12345678901234567890'); // Default: null
   $authenticator->setAlgorithm('SHA256'); // Default: SHA1
   $authenticator->setWindowSize(3); // Default: 1
   $authenticator->setPasswordLength(9); // Default: 6
   
   $authenticator->verifyPassword($password, $user->getLoginCounter());

TOTP Usage

Unlike HOTP generation and verification, you don't need a moving factor since the current timestamp is used for these operations

Create Password
   $authenticator = new \vjolenz\OtpAuth\TotpAuthenticator();
   $authenticator->setSecret('12345678901234567890'); // Default: null
   $authenticator->setAlgorithm('SHA256'); // Default: SHA1
   $authenticator->setWindowSize(3); // Default: 1
   $authenticator->setPasswordLength(9); // Default: 6
   $authenticator->setInterval(60); // Default: 30
   
   $password = $authenticator->generatePassword();
Verify Password
   $authenticator = new \vjolenz\OtpAuth\TotpAuthenticator();
   $authenticator->setSecret('12345678901234567890'); // Default: null
   $authenticator->setAlgorithm('SHA256'); // Default: SHA1
   $authenticator->setWindowSize(3); // Default: 1
   $authenticator->setPasswordLength(9); // Default: 6
   $authenticator->setInterval(60); // Default: 30
   
   $authenticator->verifyPassword($password);

License

The MIT License (MIT). Please see License File for more information.