Created
April 6, 2015 08:39
-
-
Save freretuc/3fc2a707accf4d10cc86 to your computer and use it in GitHub Desktop.
give a secret and a time and its return the current TOTP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function getOTP($secret, $time) { | |
| $counter = floor($time/30); | |
| $arr_map = array_flip(str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")); | |
| $arr_secret = str_split(preg_replace('/[^A-Z2-7]/', '', strtoupper($secret))); | |
| $bin_secret = ""; | |
| $n = 0; | |
| $j = 0; | |
| foreach($arr_secret as $chr) { | |
| $n = $n << 5; | |
| $n += $arr_map[$chr]; | |
| $j += 5; | |
| if($j>=8) { | |
| $j -= 8; | |
| $bin_secret .= chr(($n & (0xFF << $j)) >> $j); | |
| } | |
| } | |
| $hash = hash_hmac ('sha1', pack('N*', 0).pack('N*', $counter), $bin_secret, true); | |
| $offset = ord($hash[19]) & 0xf; | |
| $otp = ( | |
| ((ord($hash[$offset+0]) & 0x7f) << 24 ) | | |
| ((ord($hash[$offset+1]) & 0xff) << 16 ) | | |
| ((ord($hash[$offset+2]) & 0xff) << 8 ) | | |
| (ord($hash[$offset+3]) & 0xff) | |
| ) % pow(10, 6); | |
| return str_pad($otp, 6, "0", STR_PAD_LEFT); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment