├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── phpunit.xml ├── src └── TOTP.php └── tests └── TOTPTest.php /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | composer.lock 3 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018-present, h.y.michael@icloud.com. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PHP TOTP 2 | ========================= 3 | 4 | This library is an implementation of totp (rfc6238) in php (currently only sha1) 5 | 6 | Features 7 | -------- 8 | 9 | * PSR-4 autoloading compliant structure 10 | * Unit-Testing with PHPUnit 11 | * Easy to use to any framework or even a plain php file 12 | * Supports SHA1 of HOTPTimeBased 13 | 14 | Installation 15 | --- 16 | 17 | Using composer (recommended): 18 | ``` 19 | $ composer require greymich/php-totp 20 | ``` 21 | 22 | In separate package: 23 | ``` 24 | require "path/to/lib/src/TOTP.php" 25 | ``` 26 | 27 | 28 | Examples 29 | --- 30 | 31 | To start randomize a base32 secret or create one from an ASCII string 32 | ``` 33 | // ASCII to base32 34 | $secret = Greymich\TOTP\TOTP::base32Encode("12345678901234567890"); 35 | // Random 36 | $secret = Greymich\TOTP\TOTP::genSecret(32); 37 | // Initiate totp instance by secret 38 | $otp = new Greymich\TOTP\TOTP($secret); 39 | ``` 40 | 41 | 42 | Validate an OTP 43 | ``` 44 | $userInput = ""; 45 | $secret = ""; 46 | $otp = new Greymich\TOTP\TOTP($secret); 47 | // To mitigate possible timing attacks 48 | if(hash_equals( $otp->get(), $userInput )) { 49 | // Correct 50 | } 51 | ``` 52 | 53 | Generate OTP registration uri (For QR scanning) 54 | ``` 55 | $secret = Greymich\TOTP\TOTP::base32Encode("12345678901234567890"); 56 | $otp = new Greymich\TOTP\TOTP($secret); 57 | $uri = $otp->uri("[Platform] h.y.michael@icloud.com"); 58 | ``` 59 | 60 | 61 | Tests 62 | --- 63 | ``` 64 | composer test 65 | ``` 66 | 67 | ``` 68 | TOTP 69 | ✔ Should be true 70 | ✔ Should be free of syntax error 71 | ✔ Should encode and decode base 32 72 | ✔ Should generate totp with sha 1 73 | ✔ Should generate google authenticator compatible uri 74 | ``` 75 | 76 | Test are run against SHA1 of rfc6238 suggested testing vectors 77 | ``` 78 | +-------------+--------------+------------------+----------+--------+ 79 | | Time (sec) | UTC Time | Value of T (hex) | TOTP | Mode | 80 | +-------------+--------------+------------------+----------+--------+ 81 | | 59 | 1970-01-01 | 0000000000000001 | 94287082 | SHA1 | 82 | | | 00:00:59 | | | | 83 | | 59 | 1970-01-01 | 0000000000000001 | 46119246 | SHA256 | 84 | | | 00:00:59 | | | | 85 | | 59 | 1970-01-01 | 0000000000000001 | 90693936 | SHA512 | 86 | | | 00:00:59 | | | | 87 | | 1111111109 | 2005-03-18 | 00000000023523EC | 07081804 | SHA1 | 88 | | | 01:58:29 | | | | 89 | | 1111111109 | 2005-03-18 | 00000000023523EC | 68084774 | SHA256 | 90 | | | 01:58:29 | | | | 91 | | 1111111109 | 2005-03-18 | 00000000023523EC | 25091201 | SHA512 | 92 | | | 01:58:29 | | | | 93 | | 1111111111 | 2005-03-18 | 00000000023523ED | 14050471 | SHA1 | 94 | | | 01:58:31 | | | | 95 | | 1111111111 | 2005-03-18 | 00000000023523ED | 67062674 | SHA256 | 96 | | | 01:58:31 | | | | 97 | | 1111111111 | 2005-03-18 | 00000000023523ED | 99943326 | SHA512 | 98 | | | 01:58:31 | | | | 99 | | 1234567890 | 2009-02-13 | 000000000273EF07 | 89005924 | SHA1 | 100 | | | 23:31:30 | | | | 101 | | 1234567890 | 2009-02-13 | 000000000273EF07 | 91819424 | SHA256 | 102 | | | 23:31:30 | | | | 103 | | 1234567890 | 2009-02-13 | 000000000273EF07 | 93441116 | SHA512 | 104 | | | 23:31:30 | | | | 105 | | 2000000000 | 2033-05-18 | 0000000003F940AA | 69279037 | SHA1 | 106 | | | 03:33:20 | | | | 107 | | 2000000000 | 2033-05-18 | 0000000003F940AA | 90698825 | SHA256 | 108 | | | 03:33:20 | | | | 109 | | 2000000000 | 2033-05-18 | 0000000003F940AA | 38618901 | SHA512 | 110 | | | 03:33:20 | | | | 111 | | 20000000000 | 2603-10-11 | 0000000027BC86AA | 65353130 | SHA1 | 112 | | | 11:33:20 | | | | 113 | | 20000000000 | 2603-10-11 | 0000000027BC86AA | 77737706 | SHA256 | 114 | | | 11:33:20 | | | | 115 | | 20000000000 | 2603-10-11 | 0000000027BC86AA | 47863826 | SHA512 | 116 | | | 11:33:20 | | | | 117 | +-------------+--------------+------------------+----------+--------+ 118 | ``` -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sunnyvision/php-totp", 3 | "version": "1.0.0", 4 | "description": "PHP TOTP implementation for rfc6238 ", 5 | "keywords": ["composer", "php", "totp", "one time password"], 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "Michael Tam", 10 | "email": "h.y.michael@icloud.com" 11 | }, 12 | { 13 | "name": "Michael Tam", 14 | "email": "michael@sunnyvision.com" 15 | } 16 | ], 17 | "scripts": { 18 | "test": "phpunit --testdox --configuration phpunit.xml" 19 | }, 20 | "type": "library", 21 | "require": { 22 | "php": ">=5.6" 23 | }, 24 | "require-dev": { 25 | "phpunit/phpunit": "^7.2" 26 | }, 27 | "autoload": { 28 | "psr-4": { 29 | "Greymich\\TOTP\\": "src/" 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | tests 10 | 11 | 12 | 13 | 15 | 16 | 17 | 18 | ./src 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/TOTP.php: -------------------------------------------------------------------------------- 1 | secret = $secret; 21 | } 22 | 23 | public function setAlgorithm($algorithm = 'sha1') { 24 | $algorithm = strtolower($algorithm); 25 | if(array_search($algorithm, $this->supportedAlgorithms)) { 26 | $this->algorithm = $algorithm; 27 | return true; 28 | } 29 | return false; 30 | } 31 | 32 | private static function timeServerTimeDiff() { 33 | // ntp time servers to contact 34 | // we try them one at a time if the previous failed (failover) 35 | // if all fail then wait till tomorrow 36 | $time_servers = array( 37 | "time.nist.gov", 38 | "nist1.datum.com", 39 | "time-a.timefreq.bldrdoc.gov", 40 | "utcnist.colorado.edu"); 41 | $ts_count = count($time_servers); 42 | for ($i=0; $i> $bs ) : null; 93 | } 94 | return $out; 95 | } 96 | public static function base32Encode($data) 97 | { 98 | if (empty($data)) { 99 | return ""; 100 | } 101 | if (is_integer($data)) { 102 | $binary = decbin($data); 103 | if ($modulus = strlen($binary) % 5) { 104 | $padding = 5 - $modulus; 105 | $binary = str_pad($binary, strlen($binary) + $padding, "0", STR_PAD_LEFT); 106 | } 107 | } else { 108 | $data = str_split($data); 109 | $binary = implode("", array_map(function ($character) { 110 | return sprintf("%08b", ord($character)); 111 | }, $data)); 112 | } 113 | $binary = str_split($binary, 5); 114 | $last = array_pop($binary); 115 | $binary[] = str_pad($last, 5, "0", STR_PAD_RIGHT); 116 | $encoded = implode("", array_map(function ($fivebits) { 117 | $index = bindec($fivebits); 118 | return self::$base32Map[$index]; 119 | }, $binary)); 120 | return $encoded; 121 | } 122 | 123 | public function get( $digits = 6, $period = 30, $offset = null, $now = null ) 124 | { 125 | if($now === null) $now = time(); 126 | $secret = $this->secret; 127 | if( strlen($secret) < 16 || strlen($secret) % 8 != 0 ) 128 | throw new \Exception('secret length must >= 16 || %8==0'); 129 | if( preg_match('/[^a-z2-7]/i', $secret) === 1 ) 130 | throw new \Exception('sercret must be of base32'); 131 | if( $digits < 6 || $digits > 8 ) 132 | throw new \Exception('digits must be from 6 to 8'); 133 | $seed = self::base32Decode( $secret ); 134 | if($this->algorithm === 'sha256' && strlen($seed) < 32) { 135 | throw new \Exception('seed length must >= 32'); 136 | } 137 | if($this->algorithm === 'sha512' && strlen($seed) < 64) { 138 | throw new \Exception('seed length must >= 64'); 139 | } 140 | $time = str_pad( pack('N', intval($now / $period) + $offset ), 8, "\x00", STR_PAD_LEFT ); 141 | $hash = hash_hmac( $this->algorithm, $time, $seed, false ); 142 | $otp = ( hexdec(substr($hash, hexdec($hash[39]) * 2, 8)) & 0x7fffffff ) % pow( 10, $digits ); 143 | return sprintf("%'0{$digits}u", $otp); 144 | } 145 | 146 | public static function genSecret( $length = 32 ) 147 | { 148 | if( $length < 16 || $length % 8 != 0 ) 149 | throw new \Exception('length must >= 16 || %8==0'); 150 | while( $length-- ) 151 | { 152 | $c = @gettimeofday()['usec'] % 53; 153 | while( $c-- ) 154 | mt_rand(); 155 | @$secret .= self::$base32Map[mt_rand(0, 31)]; 156 | } 157 | return $secret; 158 | } 159 | 160 | public function uri( $account, $digits = null, $period = null, $issuer = null ) 161 | { 162 | 163 | $secret = $this->secret; 164 | if( empty($account) || empty($secret) ) 165 | throw new \Exception('account / secret must be provided'); 166 | if( mb_strpos($account . $issuer, ':') !== false ) 167 | throw new \Exception('cannot have colon in account / issuer'); 168 | $account = rawurlencode( $account ); 169 | $issuer = rawurlencode( $issuer ); 170 | $label = empty( $issuer ) ? $account : "$issuer:$account"; 171 | return 'otpauth://totp/' . $label . "?secret=$secret" . 172 | (is_null($digits) ? '' : "&digits=$digits") . 173 | (is_null($period) ? '' : "&period=$period") . 174 | (empty($issuer) ? '' : "&issuer=$issuer"); 175 | } 176 | } 177 | ?> -------------------------------------------------------------------------------- /tests/TOTPTest.php: -------------------------------------------------------------------------------- 1 | assertTrue(true); 14 | } 15 | /** 16 | * check for syntax error 17 | * 18 | */ 19 | public function testShouldBeFreeOfSyntaxError() 20 | { 21 | $otp = new Greymich\TOTP\TOTP; 22 | $this->assertTrue(is_object($otp)); 23 | unset($otp); 24 | } 25 | 26 | public function testShouldEncodeAndDecodeBase32() 27 | { 28 | $sharedSecret = Greymich\TOTP\TOTP::base32Encode("12345678901234567890"); 29 | $this->assertEquals(Greymich\TOTP\TOTP::base32Decode($sharedSecret), "12345678901234567890"); 30 | $sharedSecret = Greymich\TOTP\TOTP::base32Encode("Some very long string"); 31 | $this->assertEquals(Greymich\TOTP\TOTP::base32Decode($sharedSecret), "Some very long string"); 32 | } 33 | 34 | /** 35 | * Test aginst common secret 12345678901234567890 36 | * please see https://tools.ietf.org/html/rfc6238 37 | * 38 | * @return void 39 | * @author 40 | **/ 41 | public function testShouldGenerateTotpWithSha1() 42 | { 43 | $sharedSecret = Greymich\TOTP\TOTP::base32Encode("12345678901234567890"); 44 | $otp = new Greymich\TOTP\TOTP($sharedSecret); 45 | $this->assertEquals($otp->get(8, 30, null, 59), "94287082"); 46 | $this->assertEquals($otp->get(8, 30, null, 1111111109), "07081804"); 47 | $this->assertEquals($otp->get(8, 30, null, 1111111111), "14050471"); 48 | $this->assertEquals($otp->get(8, 30, null, 1234567890), "89005924"); 49 | $this->assertEquals($otp->get(8, 30, null, 2000000000), "69279037"); 50 | $this->assertEquals($otp->get(8, 30, null, 20000000000), "65353130"); 51 | } 52 | 53 | /** 54 | * Test for otp url for google authenticator 55 | * please see https://tools.ietf.org/html/rfc6238 56 | * 57 | * @return void 58 | * @author 59 | **/ 60 | public function testShouldGenerateGoogleAuthenticatorCompatibleUri() 61 | { 62 | $sharedSecret = Greymich\TOTP\TOTP::base32Encode("12345678901234567890"); 63 | $otp = new Greymich\TOTP\TOTP($sharedSecret); 64 | $this->assertEquals( 65 | $otp->uri("[Platform] h.y.michael@icloud.com"), 66 | "otpauth://totp/%5BPlatform%5D%20h.y.michael%40icloud.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" 67 | ); 68 | } 69 | 70 | } 71 | --------------------------------------------------------------------------------