function _base32Decode($secret) { if (empty($secret)) { return ''; } $base32chars = _getBase32LookupTable(); $base32charsFlipped = array_flip($base32chars); $paddingCharCount = substr_count($secret, $base32chars[32]); $allowedValues = array(6, 4, 3, 1, 0); if (!in_array($paddingCharCount, $allowedValues)) { return false; } for ($i = 0; $i < 4; $i++) { if ($paddingCharCount == $allowedValues[$i] && substr($secret, -$allowedValues[$i]) != str_repeat($base32chars[32], $allowedValues[$i])) { return false; } } $secret = str_replace('=', '', $secret); $secret = str_split($secret); $binaryString = ""; for ($i = 0; $i < count($secret); $i = $i + 8) { $x = ""; if (!in_array($secret[$i], $base32chars)) { return false; } for ($j = 0; $j < 8; $j++) { $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); } $eightBits = str_split($x, 8); for ($z = 0; $z < count($eightBits); $z++) { $binaryString .= ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ? $y : ""; } } return $binaryString; }
function createSecret($secretLength = 16) { $validChars = _getBase32LookupTable(); unset($validChars[32]); $secret = ''; for ($i = 0; $i < $secretLength; $i++) { $secret .= $validChars[array_rand($validChars)]; } return $secret; }