HifiPlanet-Website/hifi/api/src/Support/Base32.php
Maaxxs f3ab7d0816 Initial commit: HifiPlanet Car-Hifi Shop (Frontend + Backend)
React/Vite Frontend (hifi-src) + PHP/MariaDB Backend (hifi/api) fuer
den Car-Hifi Umbau-Shop HifiPlanet in Amorbach, inkl. Admin-Panel,
2FA, Wartungsmodus, Cookie-Consent und rechtlichen Pflichtseiten.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-05 13:37:06 +02:00

53 lines
1.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support;
/** RFC 4648 Base32 – wird für TOTP-Secrets im Google-Authenticator-Format gebraucht. */
class Base32
{
private const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
public static function encode(string $binary): string
{
if ($binary === '') {
return '';
}
$bits = '';
foreach (str_split($binary) as $char) {
$bits .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
}
$output = '';
foreach (str_split($bits, 5) as $chunk) {
$chunk = str_pad($chunk, 5, '0', STR_PAD_RIGHT);
$output .= self::ALPHABET[bindec($chunk)];
}
return $output;
}
public static function decode(string $base32): string
{
$base32 = strtoupper(preg_replace('/[^A-Z2-7]/i', '', $base32));
$bits = '';
foreach (str_split($base32) as $char) {
$pos = strpos(self::ALPHABET, $char);
if ($pos === false) {
continue;
}
$bits .= str_pad(decbin($pos), 5, '0', STR_PAD_LEFT);
}
$binary = '';
foreach (str_split($bits, 8) as $byte) {
if (strlen($byte) < 8) {
break;
}
$binary .= chr(bindec($byte));
}
return $binary;
}
}