Skip to content

Commit

Permalink
Fixed code style with php-cs-fixer (fixes #39)
Browse files Browse the repository at this point in the history
  • Loading branch information
PHPGangsta committed Oct 8, 2016
1 parent 0ad4c4c commit 3baa997
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 50 deletions.
92 changes: 56 additions & 36 deletions PHPGangsta/GoogleAuthenticator.php
@@ -1,14 +1,14 @@
<?php

/**
* PHP Class for handling Google Authenticator 2-factor authentication
* PHP Class for handling Google Authenticator 2-factor authentication.
*
* @author Michael Kliewe
* @copyright 2012 Michael Kliewe
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*
* @link http://www.phpgangsta.de/
*/

class PHPGangsta_GoogleAuthenticator
{
protected $_codeLength = 6;
Expand All @@ -18,6 +18,7 @@ class PHPGangsta_GoogleAuthenticator
* 16 characters, randomly chosen from the allowed base32 characters.
*
* @param int $secretLength
*
* @return string
*/
public function createSecret($secretLength = 16)
Expand All @@ -41,20 +42,22 @@ public function createSecret($secretLength = 16)
}
}
if ($rnd !== false) {
for ($i = 0; $i < $secretLength; $i++) {
for ($i = 0; $i < $secretLength; ++$i) {
$secret .= $validChars[ord($rnd[$i]) & 31];
}
} else {
throw new Exception('No source of secure random');
}

return $secret;
}

/**
* Calculate the code, with given secret and point in time
* Calculate the code, with given secret and point in time.
*
* @param string $secret
* @param string $secret
* @param int|null $timeSlice
*
* @return string
*/
public function getCode($secret, $timeSlice = null)
Expand All @@ -81,37 +84,42 @@ public function getCode($secret, $timeSlice = null)
$value = $value & 0x7FFFFFFF;

$modulo = pow(10, $this->_codeLength);

return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
}

/**
* Get QR-Code URL for image, from google charts
* Get QR-Code URL for image, from google charts.
*
* @param string $name
* @param string $secret
* @param string $title
* @param array $params
* @param array $params
*
* @return string
*/
public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array()) {
$width = !empty($params['width']) && (int)$params['width'] > 0 ? (int)$params['width'] : 200;
$height = !empty($params['height']) && (int)$params['height'] > 0 ? (int)$params['height'] : 200;
public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
{
$width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
$height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
$level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

$urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
if(isset($title)) {
$urlencoded .= urlencode('&issuer='.urlencode($title));
if (isset($title)) {
$urlencoded .= urlencode('&issuer='.urlencode($title));
}

return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
}

/**
* Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now
* Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
*
* @param string $secret
* @param string $code
* @param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
* @param string $secret
* @param string $code
* @param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
* @param int|null $currentTimeSlice time slice if we want use other that time()
*
* @return bool
*/
public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
Expand All @@ -124,7 +132,7 @@ public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice =
return false;
}

for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
if ($this->timingSafeEquals($calculatedCode, $code)) {
return true;
Expand All @@ -135,56 +143,68 @@ public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice =
}

/**
* Set the code length, should be >=6
* Set the code length, should be >=6.
*
* @param int $length
*
* @return PHPGangsta_GoogleAuthenticator
*/
public function setCodeLength($length)
{
$this->_codeLength = $length;

return $this;
}

/**
* Helper class to decode base32
* Helper class to decode base32.
*
* @param $secret
*
* @return bool|string
*/
protected function _base32Decode($secret)
{
if (empty($secret)) return '';
if (empty($secret)) {
return '';
}

$base32chars = $this->_getBase32LookupTable();
$base32charsFlipped = array_flip($base32chars);

$paddingCharCount = substr_count($secret, $base32chars[32]);
$allowedValues = array(6, 4, 3, 1, 0);
if (!in_array($paddingCharCount, $allowedValues)) return false;
for ($i = 0; $i < 4; $i++){
if (!in_array($paddingCharCount, $allowedValues)) {
return false;
}
for ($i = 0; $i < 4; ++$i) {
if ($paddingCharCount == $allowedValues[$i] &&
substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) return false;
substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
return false;
}
}
$secret = str_replace('=','', $secret);
$secret = str_replace('=', '', $secret);
$secret = str_split($secret);
$binaryString = "";
for ($i = 0; $i < count($secret); $i = $i+8) {
$x = "";
if (!in_array($secret[$i], $base32chars)) return false;
for ($j = 0; $j < 8; $j++) {
$binaryString = '';
for ($i = 0; $i < count($secret); $i = $i + 8) {
$x = '';
if (!in_array($secret[$i], $base32chars)) {
return false;
}
for ($j = 0; $j < 8; ++$j) {
$x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
}
$eightBits = str_split($x, 8);
for ($z = 0; $z < count($eightBits); $z++) {
$binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
for ($z = 0; $z < count($eightBits); ++$z) {
$binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
}
}

return $binaryString;
}

/**
* Get array with all 32 characters for decoding from/encoding to base32
* Get array with all 32 characters for decoding from/encoding to base32.
*
* @return array
*/
Expand All @@ -195,18 +215,18 @@ protected function _getBase32LookupTable()
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
'=' // padding char
'=', // padding char
);
}

/**
* A timing safe equals comparison
* more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html
* more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html.
*
* @param string $safeString The internal (safe) value to be checked
* @param string $userString The user submitted (unsafe) value
*
* @return boolean True if the two strings are identical.
* @return bool True if the two strings are identical
*/
private function timingSafeEquals($safeString, $userString)
{
Expand All @@ -222,7 +242,7 @@ private function timingSafeEquals($safeString, $userString)

$result = 0;

for ($i = 0; $i < $userLen; $i++) {
for ($i = 0; $i < $userLen; ++$i) {
$result |= (ord($safeString[$i]) ^ ord($userString[$i]));
}

Expand Down
25 changes: 12 additions & 13 deletions tests/GoogleAuthenticatorTest.php
@@ -1,6 +1,6 @@
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__.'/../vendor/autoload.php';

class GoogleAuthenticatorTest extends PHPUnit_Framework_TestCase
{
Expand Down Expand Up @@ -31,7 +31,7 @@ public function testItCanBeInstantiated()

public function testCreateSecretDefaultsToSixteenCharacters()
{
$ga = $this->googleAuthenticator;
$ga = $this->googleAuthenticator;
$secret = $ga->createSecret();

$this->assertEquals(strlen($secret), 16);
Expand All @@ -41,7 +41,7 @@ public function testCreateSecretLengthCanBeSpecified()
{
$ga = $this->googleAuthenticator;

for ($secretLength = 16; $secretLength < 100; $secretLength++) {
for ($secretLength = 16; $secretLength < 100; ++$secretLength) {
$secret = $ga->createSecret($secretLength);

$this->assertEquals(strlen($secret), $secretLength);
Expand All @@ -51,18 +51,18 @@ public function testCreateSecretLengthCanBeSpecified()
/**
* @dataProvider codeProvider
*/
public function testgetCodeReturnsCorrectValues($secret, $timeSlice, $code)
public function testGetCodeReturnsCorrectValues($secret, $timeSlice, $code)
{
$generatedCode = $this->googleAuthenticator->getCode($secret, $timeSlice);

$this->assertEquals($code, $generatedCode);
}

public function testgetQRCodeGoogleUrlReturnsCorrectUrl()
public function testGetQRCodeGoogleUrlReturnsCorrectUrl()
{
$secret = 'SECRET';
$name = 'Test';
$url = $this->googleAuthenticator->getQRCodeGoogleUrl($name, $secret);
$secret = 'SECRET';
$name = 'Test';
$url = $this->googleAuthenticator->getQRCodeGoogleUrl($name, $secret);
$urlParts = parse_url($url);

parse_str($urlParts['query'], $queryStringArray);
Expand All @@ -71,20 +71,20 @@ public function testgetQRCodeGoogleUrlReturnsCorrectUrl()
$this->assertEquals($urlParts['host'], 'chart.googleapis.com');
$this->assertEquals($urlParts['path'], '/chart');

$expectedChl = 'otpauth://totp/' . $name . '?secret=' . $secret;
$expectedChl = 'otpauth://totp/'.$name.'?secret='.$secret;

$this->assertEquals($queryStringArray['chl'], $expectedChl);
}

public function testVerifyCode()
{
$secret = 'SECRET';
$code = $this->googleAuthenticator->getCode($secret);
$code = $this->googleAuthenticator->getCode($secret);
$result = $this->googleAuthenticator->verifyCode($secret, $code);

$this->assertEquals(true, $result);

$code = 'INVALIDCODE';
$code = 'INVALIDCODE';
$result = $this->googleAuthenticator->verifyCode($secret, $code);

$this->assertEquals(false, $result);
Expand All @@ -100,10 +100,9 @@ public function testVerifyCodeWithLeadingZero()
$code = '0'.$code;
$result = $this->googleAuthenticator->verifyCode($secret, $code);
$this->assertEquals(false, $result);

}

public function testsetCodeLength()
public function testSetCodeLength()
{
$result = $this->googleAuthenticator->setCodeLength(6);

Expand Down
2 changes: 1 addition & 1 deletion tests/bootstrap.php
@@ -1,3 +1,3 @@
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__.'/../vendor/autoload.php';

0 comments on commit 3baa997

Please sign in to comment.