Commit 7c4e59c6 authored by Scott Dutton's avatar Scott Dutton Committed by Florent Morselli
Browse files

Minor fixes (#131)

* Timecode calculation method corrected
* Fixed typo (#92)
    * otherwize -> otherwise
* Minor changes
* Uses newer syntax and uses unpack instead of splitting strings
* Add type hint
Showing with 7 additions and 9 deletions
+7 -9
......@@ -16,6 +16,7 @@ namespace OTPHP;
use Assert\Assertion;
use ParagonIE\ConstantTime\Base32;
use RuntimeException;
use function Safe\hex2bin;
use function Safe\ksort;
use function Safe\sprintf;
......@@ -43,13 +44,12 @@ abstract class OTP implements OTPInterface
protected function generateOTP(int $input): string
{
$hash = hash_hmac($this->getDigest(), $this->intToByteString($input), $this->getDecodedSecret());
$hmac = [];
foreach (str_split($hash, 2) as $hex) {
$hmac[] = hexdec($hex);
}
$offset = $hmac[\count($hmac) - 1] & 0xF;
$hmac = unpack('C*', hex2bin($hash));
$offset = ($hmac[\count($hmac)] & 0xF) + 1;
$code = ($hmac[$offset + 0] & 0x7F) << 24 | ($hmac[$offset + 1] & 0xFF) << 16 | ($hmac[$offset + 2] & 0xFF) << 8 | ($hmac[$offset + 3] & 0xFF);
$otp = $code % 10 ** $this->getDigits();
$otp = $code % (10 ** $this->getDigits());
return str_pad((string) $otp, $this->getDigits(), '0', STR_PAD_LEFT);
}
......@@ -85,12 +85,10 @@ abstract class OTP implements OTPInterface
private function getDecodedSecret(): string
{
try {
$secret = Base32::decodeUpper($this->getSecret());
return Base32::decodeUpper($this->getSecret());
} catch (\Exception $e) {
throw new RuntimeException('Unable to decode the secret. Is it correctly base32 encoded?');
}
return $secret;
}
private function intToByteString(int $int): string
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment