index/src/Base32.php

62 lines
1.6 KiB
PHP

<?php
// Base32.php
// Created: 2022-01-13
// Updated: 2024-07-31
namespace Index;
/**
* Provides Base32 encoding.
*/
final class Base32 {
private const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/**
* Encodes data with RFC4648 base32.
*
* @param string $string The data to encode.
* @return string The encoded data, as a string.
*/
public static function encode(string $string): string {
$length = strlen($string);
$bin = '';
$output = '';
for($i = 0; $i < $length; $i++)
$bin .= sprintf('%08b', ord($string[$i]));
$bin = str_split($bin, 5);
$last = array_pop($bin);
$bin[] = str_pad((string)$last, 5, '0', STR_PAD_RIGHT);
foreach($bin as $part)
$output .= self::CHARS[bindec($part)];
return $output;
}
/**
* Decodes data encoded with RFC4648 base32.
*
* @param string $string The encoded data.
* @return string|false Returns the decoded data or false on failure. The returned data may be binary.
*/
public static function decode(string $string): string|false {
$length = strlen($string);
$char = $shift = 0;
$output = '';
for($i = 0; $i < $length; $i++) {
$pos = stripos(self::CHARS, $string[$i]);
if($pos === false)
return false;
$char <<= 5;
$char += $pos;
$shift = ($shift + 5) % 8;
$output .= $shift < 5 ? chr(($char & (0xFF << $shift)) >> $shift) : '';
}
return $output;
}
}