You are here

public function PHPGangsta_GoogleAuthenticator::getCode in TFA Basic plugins 7

Calculate the code, with given secret and point in time.

Parameters

string $secret:

int|null $timeSlice:

Return value

string

1 call to PHPGangsta_GoogleAuthenticator::getCode()
PHPGangsta_GoogleAuthenticator::verifyCode in includes/googleauthenticator/GoogleAuthenticator.php
Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.

File

includes/googleauthenticator/GoogleAuthenticator.php, line 63

Class

PHPGangsta_GoogleAuthenticator
PHP Class for handling Google Authenticator 2-factor authentication.

Code

public function getCode($secret, $timeSlice = null) {
  if ($timeSlice === null) {
    $timeSlice = floor(time() / 30);
  }
  $secretkey = $this
    ->_base32Decode($secret);

  // Pack time into binary string
  $time = chr(0) . chr(0) . chr(0) . chr(0) . pack('N*', $timeSlice);

  // Hash it with users secret key
  $hm = hash_hmac('SHA1', $time, $secretkey, true);

  // Use last nipple of result as index/offset
  $offset = ord(substr($hm, -1)) & 0xf;

  // grab 4 bytes of the result
  $hashpart = substr($hm, $offset, 4);

  // Unpak binary value
  $value = unpack('N', $hashpart);
  $value = $value[1];

  // Only 32 bits
  $value = $value & 0x7fffffff;
  $modulo = pow(10, $this->_codeLength);
  return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
}