Skip to content

Instantly share code, notes, and snippets.

@webmstk
Last active December 14, 2016 10:55
Show Gist options
  • Save webmstk/2767dd2f12f1d2d002d65ff4ac570084 to your computer and use it in GitHub Desktop.
Save webmstk/2767dd2f12f1d2d002d65ff4ac570084 to your computer and use it in GitHub Desktop.
<?
class OneTimePasswordGenerator {
static $PASS_CODE_LENGTH = 6;
static $PIN_MODULO;
public function __construct() {
self::$PIN_MODULO = pow(10, self::$PASS_CODE_LENGTH);
}
public function getCode($base64Secret, $time = null) {
if (!$time) {
$time = floor(time() / 30);
}
$secret = base64_decode($base64Secret);
$time = pack("N", $time);
$time = str_pad($time,8, chr(0), STR_PAD_LEFT);
$hash = hash_hmac('sha1',$time,$secret,true);
$offset = ord(substr($hash,-1));
$offset = $offset & 0xF;
$truncatedHash = self::hashToInt($hash, $offset) & 0x7FFFFFFF;
$pinValue = str_pad($truncatedHash % self::$PIN_MODULO,6,"0",STR_PAD_LEFT);
return $pinValue;
}
protected function hashToInt($bytes, $start) {
$input = substr($bytes, $start, strlen($bytes) - $start);
$val2 = unpack("N",substr($input,0,4));
return $val2[1];
}
}
$pass_gen = new OneTimePasswordGenerator;
$oneTimePassword = $pass_gen->getCode('base64EncodedSecret');
print $oneTimePassword;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment