Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Base32 Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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;.

Implementation Patterns

  • TOTP/MFA Service Layer: Wrap the encoder in a dedicated service to enforce consistency and error handling:
    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);
        }
    }
    
  • Batch Processing & Validation: In job classes, validate inputs before decoding (since 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);
        }
    }
    
  • Cross-Environment Compatibility: Use Base32Hex only when interoperating with systems requiring the hex alphabet (e.g., DNSSEC):
    use Base32\Base32Hex;
    $hexToken = Base32Hex::encode(bin2hex(random_bytes(16)));
    
  • Testability: Avoid direct static calls in production logic by defining a simple interface:
    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); }
    }
    

Gotchas and Tips

  • Padding ambiguity: The library strips padding by default per RFC 4648, but older clients (e.g., some authenticator apps or legacy APIs) may expect padding. Use str_pad($encoded, strlen($encoded) + (8 - strlen($encoded) % 8) % 8, '=') if interoperability issues occur.
  • Input validation: 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.
  • Case sensitivity: Decoding is case-insensitive, but encoding always outputs uppercase. Avoid strtoupper()/strtolower() to prevent silent data loss.
  • Hex vs standard confusion: 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()).
  • Maturity caution: Last release was 2021, but critical bugs (v1.5.x/v1.6.x) were fixed quickly—pin to ^1.6. Verify compatibility with PHP 8.2+ in tests; though claimed supported, no recent CI coverage is visible.
  • Security注意: No timing-safe operations are exposed. For cryptographic comparisons (e.g., OTP verification), use hash_equals() after decoding—never compare raw encoded strings.
  • Performance: Highly optimized since v1.3+, but avoid decoding large batches in hot loops. Cache decoded secrets (e.g., in Redis) if used repeatedly.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests