christian-riesen/base32
RFC 4648-compliant Base32 encoder/decoder for PHP (7.2+). Simple static API to encode/decode strings, passes official test vectors, and includes unit tests. Also supports the extended Base32Hex alphabet via Base32Hex.
Install via Composer: composer require christian-riesen/base32. This is the minimal dependency needed to get RFC 4648-compliant Base32 encoding/decoding in Laravel. Start immediately with:
use Base32\Base32;
$encoded = Base32::encode('hello'); // → 'JBSWY3DPEHPK3PXP'
$decoded = Base32::decode('JBSWY3DPEHPK3PXP'); // → 'hello'
First use case: Generate TOTP secrets for 2FA. Encode random bytes into a Base32 string compatible with Google Authenticator:
$secret = Base32::encode(random_bytes(20)); // 160-bit secret
// Provision via QR code URL
$qrcodeUrl = 'otpauth://totp/MyApp:'.$user->email.'?secret='.$secret.'&issuer=MyApp';
No configuration or service binding required—just use Base32\Base32;.
class TotpSecretManager
{
public function create(): string
{
return Base32::encode(random_bytes(20));
}
public function isValid(string $secret): bool
{
return strlen($secret) % 8 === 0 && preg_match('/^[A-Z2-7]+$/', $secret) === 1;
}
public function toBytes(string $secret): string
{
return Base32::decode($secret);
}
}
decode() throws on invalid input):
public function handle(Request $request): Response
{
try {
$decoded = Base32::decode(strtoupper($request->input('token')));
// Use $decoded for further processing
} catch (\Base32\Base32Exception $e) {
return response()->json(['error' => 'Invalid Base32 token'], 400);
}
}
Base32Hex only when interoperating with systems requiring the hex alphabet (e.g., DNSSEC):
use Base32\Base32Hex;
$hexToken = Base32Hex::encode(bin2hex(random_bytes(16)));
interface Base32Codec
{
public function encode(string $data): string;
public function decode(string $data): string;
}
class RiesenBase32Codec implements Base32Codec
{
public function encode(string $data): string { return Base32::encode($data); }
public function decode(string $data): string { return Base32::decode($data); }
}
str_pad($encoded, strlen($encoded) + (8 - strlen($encoded) % 8) % 8, '=') if interoperability issues occur.decode() throws Base32Exception on invalid characters—no built-in isBase32() helper exists. Add validation via regex (/^[A-Z2-7]+$/ for standard, /^[A-V0-9]+$/ for hex) or catch exceptions.strtoupper()/strtolower() to prevent silent data loss.Base32Hex (A-V0-9) is not interchangeable with Base32 (A-Z2-7). Mixing them causes silent corruption. Document variant usage explicitly (e.g., // RFC 4648 Section 7 (hex alphabet)) and consider naming conventions (e.g., hexBase32Encode()).^1.6. Verify compatibility with PHP 8.2+ in tests; though claimed supported, no recent CI coverage is visible.hash_equals() after decoding—never compare raw encoded strings.How can I help you explore Laravel packages today?