-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.php
50 lines (46 loc) · 1.56 KB
/
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
function generateSecret($length = 16) {
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; // Base32 characters
$secret = '';
for ($i = 0; $i < $length; $i++) {
$secret .= $characters[rand(0, strlen($characters) - 1)];
}
return $secret;
}
function getTimestamp() {
return floor(microtime(true) / 30);
}
function base32Decode($b32) {
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$b32 = strtoupper($b32); // Ensure uppercase
$decoded = '';
foreach (str_split($b32) as $char) {
$decoded .= str_pad(base_convert(strpos($alphabet, $char), 10, 2), 5, '0', STR_PAD_LEFT);
}
$binaryData = '';
foreach (str_split($decoded, 8) as $binary) {
$binaryData .= chr(bindec($binary));
}
return $binaryData;
}
function generateTotp($secret, $digits = 6) {
$timestamp = getTimestamp();
$secret = base32Decode($secret);
$hmac = hash_hmac('sha1', pack('N*', 0) . pack('N*', $timestamp), $secret, true);
$offset = ord($hmac[strlen($hmac) - 1]) & 0xF;
$code = (ord($hmac[$offset]) & 0x7F) << 24 |
(ord($hmac[$offset + 1]) & 0xFF) << 16 |
(ord($hmac[$offset + 2]) & 0xFF) << 8 |
(ord($hmac[$offset + 3]) & 0xFF);
return str_pad($code % pow(10, $digits), $digits, '0', STR_PAD_LEFT);
}
function verifyTotp($secret, $userCode, $window = 1, $digits = 6) {
for ($i = -$window; $i <= $window; $i++) {
$timestamp = getTimestamp() + $i;
if (generateTotp($secret, $digits) === $userCode) {
return true;
}
}
return false;
}
?>