|
1 <?php |
|
2 |
|
3 /** |
|
4 * Returns OTP data. Numeric except for public and private IDs, which are hex. |
|
5 * @return array Associative |
|
6 */ |
|
7 |
|
8 function yms_decode_otp($otp, $key) |
|
9 { |
|
10 static $aes = false; |
|
11 if ( !is_object($aes) ) |
|
12 $aes = AESCrypt::singleton(128, 128); |
|
13 |
|
14 $return = array(); |
|
15 |
|
16 $otp = yms_tobinary($otp); |
|
17 if ( strlen($otp) != 22 ) |
|
18 { |
|
19 return false; |
|
20 } |
|
21 $key = yms_tobinary($key); |
|
22 if ( strlen($key) != 16 ) |
|
23 { |
|
24 return false; |
|
25 } |
|
26 |
|
27 $cryptpart = yms_hex_encode(substr($otp, 6, 16)); |
|
28 $publicid = substr($otp, 0, 6); |
|
29 |
|
30 $return['publicid'] = yms_hex_encode($publicid); |
|
31 $otp_decrypted = $aes->decrypt($cryptpart, $key, ENC_HEX); |
|
32 $crc_is_good = yms_validate_crc($otp_decrypted); |
|
33 $return['privateid'] = yms_hex_encode(substr($otp_decrypted, 0, 6)); |
|
34 $return['session'] = yms_unpack_int(strrev(substr($otp_decrypted, 6, 2))); |
|
35 $return['timestamp'] = yms_unpack_int(strrev(substr($otp_decrypted, 8, 3))); |
|
36 $return['count'] = yms_unpack_int(substr($otp_decrypted, 11, 1)); |
|
37 $return['random'] = yms_unpack_int(substr($otp_decrypted, 12, 2)); |
|
38 $return['crc'] = yms_unpack_int(substr($otp_decrypted, 14, 2)); |
|
39 $return['crc_good'] = $crc_is_good; |
|
40 |
|
41 return $return; |
|
42 } |
|
43 |
|
44 function yms_unpack_int($str) |
|
45 { |
|
46 $return = 0; |
|
47 for ( $i = 0; $i < strlen($str); $i++ ) |
|
48 { |
|
49 $return = $return << 8; |
|
50 $return = $return | ord($str{$i}); |
|
51 } |
|
52 return $return; |
|
53 } |
|
54 |
|
55 function yms_crc16($buffer) |
|
56 { |
|
57 $buffer = yms_tobinary($buffer); |
|
58 |
|
59 $m_crc=0x5af0; |
|
60 for($bpos=0; $bpos<strlen($buffer); $bpos++) |
|
61 { |
|
62 $m_crc ^= ord($buffer[$bpos]); |
|
63 for ($i=0; $i<8; $i++) |
|
64 { |
|
65 $j=$m_crc & 1; |
|
66 $m_crc >>= 1; |
|
67 if ($j) $m_crc ^= 0x8408; |
|
68 } |
|
69 } |
|
70 return $m_crc; |
|
71 } |
|
72 |
|
73 function yms_validate_crc($token) |
|
74 { |
|
75 $crc = yms_crc16($token); |
|
76 return $crc == 0; |
|
77 } |
|
78 |
|
79 function yms_within($test, $control, $fuzz) |
|
80 { |
|
81 $min = $control - $fuzz; |
|
82 $max = $control + $fuzz; |
|
83 return $test > $min && $test < $max; |
|
84 } |