base32.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. define('BASE32_ALPHABET', '0123456789bcdfghjklmnpqrstuvwxyz');
  3. define('BASE32_NBITS', 5);
  4. function base32_encode($input)
  5. {
  6. $output = '';
  7. $buffer = ['size'=>BASE32_NBITS, 'callback'=> function($x) use(&$output) { $output .= BASE32_ALPHABET[$x]; }];
  8. $length = strlen($input);
  9. for ($i = 0; $i < $length; $i++)
  10. {
  11. $char = ord($input[$i]);
  12. base32_buffer_add($buffer, $char, 8);
  13. }
  14. if ($buffer) { base32_buffer_add($buffer, 0, 8); $length--; }
  15. $output .= str_repeat('=', $length % 3);
  16. return $output;
  17. }
  18. function base32_decode($input)
  19. {
  20. $input = preg_replace('#\s#', '', $input);
  21. $output = '';
  22. $buffer = ['size'=>8, 'callback'=> function($x) use(&$output) { $output .= chr($x); }];
  23. for ($i = 0; $i < strlen($input); $i++)
  24. if ($input[$i] != '=')
  25. {
  26. $char = strpos(BASE32_ALPHABET, $input[$i]);
  27. base32_buffer_add($buffer, $char, BASE32_NBITS);
  28. }
  29. return $output;
  30. }
  31. function base32_buffer_add(&$buffer, $char, $char_size)
  32. {
  33. @$buffer['data'] |= $char << @$buffer['data_size'];
  34. @$buffer['data_size'] += $char_size;
  35. while ($buffer['data_size'] > $buffer['size'])
  36. {
  37. $mask = pow(2, $buffer['size']) - 1;
  38. $char = $buffer['data'] & $mask;
  39. $buffer['callback']($char);
  40. $buffer['data'] >>= $buffer['size'];
  41. $buffer['data_size'] -= $buffer['size'];
  42. }
  43. }