Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 7 additions & 19 deletions src/OTP.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
namespace OTPHP;

use function array_key_exists;
use function chr;
use function count;
use Exception;
use function in_array;
use function is_int;
use function is_string;
use function ord;
use OTPHP\Exception\InvalidLabelException;
use OTPHP\Exception\InvalidParameterException;
use OTPHP\Exception\ParameterNotFoundException;
Expand Down Expand Up @@ -287,14 +287,13 @@ final protected static function generateSecret(?int $secretSize = null): string
*/
protected function generateOTP(int $input): string
{
$hash = hash_hmac($this->getDigest(), $this->intToByteString($input), $this->getDecodedSecret(), true);
$unpacked = unpack('C*', $hash);
$unpacked !== false || throw new InvalidParameterException('Invalid data.', 'hash', $hash);
/** @var list<int> $hmac */
$hmac = array_values($unpacked);
$hash = hash_hmac($this->getDigest(), pack('J', $input), $this->getDecodedSecret(), true);

$offset = ($hmac[count($hmac) - 1] & 0xF);
$code = ($hmac[$offset] & 0x7F) << 24 | ($hmac[$offset + 1] & 0xFF) << 16 | ($hmac[$offset + 2] & 0xFF) << 8 | ($hmac[$offset + 3] & 0xFF);
$offset = ord($hash[strlen($hash) - 1]) & 0xF;
$code = (ord($hash[$offset]) & 0x7F) << 24
| (ord($hash[$offset + 1]) & 0xFF) << 16
| (ord($hash[$offset + 2]) & 0xFF) << 8
| (ord($hash[$offset + 3]) & 0xFF);
$otp = $code % (10 ** $this->getDigits());

return str_pad((string) $otp, $this->getDigits(), '0', STR_PAD_LEFT);
Expand Down Expand Up @@ -414,17 +413,6 @@ private function getDecodedSecret(): string
return $decoded;
}

private function intToByteString(int $int): string
{
$result = [];
while ($int !== 0) {
$result[] = chr($int & 0xFF);
$int >>= 8;
}

return str_pad(implode('', array_reverse($result)), 8, "\000", STR_PAD_LEFT);
}

/**
* @return non-empty-string
*/
Expand Down