| 1 |
<?php |
| 2 |
|
| 3 |
// Do not allow the file to be called directly. |
| 4 |
if ( ! defined( 'ABSPATH' ) ) { |
| 5 |
exit; |
| 6 |
} |
| 7 |
|
| 8 |
require_once dirname( __FILE__ ) . '/base32.php'; |
| 9 |
|
| 10 |
class TokenAuth6238 { |
| 11 |
|
| 12 |
/** |
| 13 |
* Verify the code & token. |
| 14 |
* |
| 15 |
* @param string $secretkey Secret clue (base 32). |
| 16 |
* @return bool True if success, false if failure |
| 17 |
*/ |
| 18 |
public static function verify( $secretkey, $code, $rangein30s = 3 ) { |
| 19 |
$key = base32static::decode( $secretkey ); |
| 20 |
$unixtimestamp = time() / 30; |
| 21 |
|
| 22 |
for ( $i = -( $rangein30s ); $i <= $rangein30s; $i++ ) { |
| 23 |
$checktime = (int) ( $unixtimestamp + $i ); |
| 24 |
$thiskey = self::oath_hotp( $key, $checktime ); |
| 25 |
|
| 26 |
if ( (int) $code == self::oath_truncate( $thiskey, 6 ) ) { |
| 27 |
return true; |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
return false; |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Generate the random clue/key. |
| 36 |
* |
| 37 |
* @param integer $length |
| 38 |
* @return string |
| 39 |
*/ |
| 40 |
public static function generateRandomClue( $length = 16 ) { |
| 41 |
$b32 = '234567QWERTYUIOPASDFGHJKLZXCVBNM'; |
| 42 |
$s = ''; |
| 43 |
for ( $i = 0; $i < $length; $i++ ) { |
| 44 |
$s .= $b32[ mt_rand( 0, 31 ) ]; |
| 45 |
} |
| 46 |
|
| 47 |
return $s; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* |
| 52 |
* @param string $key |
| 53 |
* @param integer $counter |
| 54 |
* @return string |
| 55 |
*/ |
| 56 |
private static function oath_hotp( $key, $counter ) { |
| 57 |
$cur_counter = array( 0, 0, 0, 0, 0, 0, 0, 0 ); |
| 58 |
|
| 59 |
for ( $i = 7; $i >= 0; $i-- ) { // C for unsigned char, * for repeating to the end of the input data |
| 60 |
$cur_counter[ $i ] = pack( 'C*', $counter ); |
| 61 |
$counter = $counter >> 8; |
| 62 |
} |
| 63 |
|
| 64 |
$binary = implode( $cur_counter ); |
| 65 |
|
| 66 |
// Pad to 8 characters |
| 67 |
str_pad( $binary, 8, chr( 0 ), STR_PAD_LEFT ); |
| 68 |
return hash_hmac( 'sha1', $binary, $key ); |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Truncate |
| 73 |
* |
| 74 |
* @param string $hash |
| 75 |
* @param integer $length |
| 76 |
* @return boolean |
| 77 |
*/ |
| 78 |
private static function oath_truncate( $hash, $length = 6 ) { |
| 79 |
$hashcharacters = str_split( $hash, 2 ); |
| 80 |
|
| 81 |
for ( $j = 0; $j < count( $hashcharacters ); $j++ ) { |
| 82 |
$hmac_result[] = hexdec( $hashcharacters[ $j ] ); |
| 83 |
} |
| 84 |
|
| 85 |
$offset = $hmac_result[19] & 0xf; |
| 86 |
return ( |
| 87 |
( ( $hmac_result[ $offset + 0 ] & 0x7f ) << 24 ) | |
| 88 |
( ( $hmac_result[ $offset + 1 ] & 0xff ) << 16 ) | |
| 89 |
( ( $hmac_result[ $offset + 2 ] & 0xff ) << 8 ) | |
| 90 |
( $hmac_result[ $offset + 3 ] & 0xff ) |
| 91 |
) % pow( 10, $length ); |
| 92 |
} |
| 93 |
} |
| 94 |
|