PHP Classes
elePHPant
Icontem

File: src/OneTime.php

Recommend this page to a friend!
  Classes of Scott Arciszewski  >  PHP Multi Factor Authentication  >  src/OneTime.php  >  Download  
File: src/OneTime.php
Role: Class source
Content type: text/plain
Description: Class source
Class: PHP Multi Factor Authentication
2 factor authentication independent of the vendor
Author: By
Last change:
Date: 3 months ago
Size: 1,466 bytes
 

 

Contents

Class file image Download
<?php
declare(strict_types=1);
namespace
ParagonIE\MultiFactor;

use
ParagonIE\MultiFactor\OTP\{
   
OTPInterface,
   
TOTP
};
use
ParagonIE\HiddenString\HiddenString;

/**
 * Class OneTime
 *
 * @package ParagonIE\MultiFactor
 */
class OneTime implements MultiFactorInterface
{
   
/**
     * @var OTPInterface
     */
   
protected $otp;

   
/**
     * @var HiddenString
     */
   
protected $secretKey;

   
/**
     * FIDOU2F constructor.
     *
     * @param string|HiddenString $secretKey
     * @param OTPInterface $otp
     */
   
public function __construct(
       
$secretKey = '',
       
OTPInterface $otp = null
   
) {
       
$this->secretKey = ($secretKey instanceof HiddenString) ? $secretKey : new HiddenString($secretKey);
        if (!
$otp) {
           
$otp = new TOTP();
        }
       
$this->otp = $otp;
    }

   
/**
     * Generate a TOTP code for 2FA
     *
     * @param int $counterValue
     * @return string
     */
   
public function generateCode(int $counterValue = 0): string
   
{
        return
$this->otp->getCode(
           
$this->secretKey,
           
$counterValue
       
);
    }

   
/**
     * Validate a user-provided code
     *
     * @param string $code
     * @param int $counterValue
     * @return bool
     */
   
public function validateCode(string $code, int $counterValue = 0): bool
   
{
       
$expected = $this->generateCode($counterValue);
        return \
hash_equals($code, $expected);
    }
}