diff --git a/src/Base32/Base32.php b/src/Base32/Base32.php index 6612ad2..043e528 100644 --- a/src/Base32/Base32.php +++ b/src/Base32/Base32.php @@ -102,20 +102,13 @@ public function decode(string $encoded, bool $strict = false): string $encoded = strtoupper($encoded); } - $remainder = strlen($encoded) % 8; - if (0 !== $remainder) { - if ($strict) { - throw new RuntimeException('The encoded data length is invalid.'); - } - - $encoded .= str_repeat($padding, $remainder); - } - $inside = rtrim($encoded, $padding); $end = substr($encoded, strlen($inside)); - $endLength = strlen($end); - if ($strict && 0 !== $endLength && 1 !== $endLength && 3 !== $endLength && 4 !== $endLength && 6 !== $endLength) { - throw new RuntimeException('The encoded data ends with an invalid padding sequence length.'); + if ($strict) { + $endLength = strlen($end); + if (0 !== $endLength && 1 !== $endLength && 3 !== $endLength && 4 !== $endLength && 6 !== $endLength) { + throw new RuntimeException('The encoded data ends with an invalid padding sequence length.'); + } } if (false !== strpos($inside, $padding)) { @@ -126,18 +119,34 @@ public function decode(string $encoded, bool $strict = false): string $encoded = str_replace($padding, '', $inside).$end; } + $remainder = strlen($encoded) % 8; + if (0 !== $remainder) { + if ($strict) { + throw new RuntimeException('The encoded data length is invalid.'); + } + + for ($index = 0; $index < $remainder; $index++) { + $encoded .= $padding; + } + } + $chars = []; - foreach (str_split($alphabet) as $offset => $char) { - $chars[$char] = $offset; + for ($index = 0; $index < self::ALPHABET_SIZE; $index++) { + $chars[$alphabet[$index]] = $index; } $chars[$padding] = 0; + $offset = 0; $bitLen = 5; $length = strlen($encoded); $decoded = ''; do { - $val ??= $chars[$encoded[$offset]] ?? -1; + if (!isset($val)) { + $index = $encoded[$offset]; + $val = array_key_exists($index, $chars) ? $chars[$index] : -1; + } + if (-1 === $val) { if ($strict) { throw new RuntimeException('The encoded data contains characters unknown to the base32 alphabet.');