|
4 | 4 | class Base32{
|
5 | 5 |
|
6 | 6 | public static function decode(string $data,string $alphabet): string{
|
7 |
| - if (empty($data)) { |
8 |
| - return ''; |
9 |
| - } |
10 |
| - |
11 |
| - $data = str_split($data); |
12 |
| - $data = array_map(static function ($character) use($alphabet) { |
13 |
| - if ($character !== $alphabet[strlen($alphabet)-1]) { |
14 |
| - $index = strpos($alphabet, $character); |
15 |
| - return sprintf('%05b', $index); |
| 7 | + $flippedAlphabet = array_flip(str_split($alphabet)); |
| 8 | + $binary = ''; |
| 9 | + for($i=0;$i<strlen($data);$i++){ |
| 10 | + $char = strtolower($data[$i]); |
| 11 | + if($char==='='){ |
| 12 | + continue; |
16 | 13 | }
|
17 |
| - }, $data); |
18 |
| - $binary = implode('', $data); |
19 |
| - |
20 |
| - /* Split to eight bit chunks. */ |
21 |
| - $data = str_split($binary, 8); |
22 |
| - |
23 |
| - /* Make sure binary is divisible by eight by ignoring the incomplete byte. */ |
24 |
| - $last = array_pop($data); |
25 |
| - if ((null !== $last) && (8 === strlen($last))) { |
26 |
| - $data[] = $last; |
| 14 | + $binaryChunk = decbin($flippedAlphabet[$char]); |
| 15 | + while(strlen($binaryChunk)%5!==0){ |
| 16 | + $binaryChunk = '0'.$binaryChunk; |
| 17 | + } |
| 18 | + $binary .= $binaryChunk; |
27 | 19 | }
|
| 20 | + $padding = strlen($binary)%8; |
| 21 | + if($padding!==0){ |
| 22 | + $binary = substr($binary,0,-$padding); |
| 23 | + } |
| 24 | + return Base2::decode($binary); |
| 25 | + |
28 | 26 |
|
29 |
| - return implode('', array_map(function ($byte) { |
30 |
| - return chr((int)bindec($byte)); |
31 |
| - }, $data)); |
| 27 | +// $map = str_split($alphabet); |
| 28 | +// $flippedMap = array_flip($map); |
| 29 | +// |
| 30 | +// $paddingCharCount = substr_count($data, $map[32]); |
| 31 | +// $allowedValues = array(6,4,3,1,0); |
| 32 | +// if(!in_array($paddingCharCount, $allowedValues)) return false; |
| 33 | +// for($i=0; $i<4; $i++){ |
| 34 | +// if($paddingCharCount == $allowedValues[$i] && |
| 35 | +// substr($data, -($allowedValues[$i])) != str_repeat($map[32], $allowedValues[$i])) return false; |
| 36 | +// } |
| 37 | +// $data = str_replace('=','', $data); |
| 38 | +// $data = str_split($data); |
| 39 | +// $binaryString = ""; |
| 40 | +// for($i=0; $i < count($data); $i = $i+8) { |
| 41 | +// $x = ""; |
| 42 | +// if(!in_array($data[$i], $map)) return false; |
| 43 | +// for($j=0; $j < 8; $j++) { |
| 44 | +// $x .= str_pad(base_convert(@$flippedMap[@$data[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); |
| 45 | +// } |
| 46 | +// $eightBits = str_split($x, 8); |
| 47 | +// for($z = 0; $z < count($eightBits); $z++) { |
| 48 | +// $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:""; |
| 49 | +// } |
| 50 | +// } |
| 51 | +// return $binaryString; |
32 | 52 | }
|
33 | 53 |
|
34 | 54 | public static function encode(string $data,string $alphabet): string{
|
|
0 commit comments