Weave 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

Crypto For Laravel Laravel Package

roundly-consulting/crypto-for-laravel

Crypto for Laravel adds a clean, framework-native layer for common cryptography tasks—encryption, decryption, hashing, and secure random/key generation—with config-driven setup, facades, and helpers so you can keep sensitive data safe without wiring low-level PHP crypto code yourself.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install the package via Composer:

    composer require roundly-consulting/crypto-for-laravel
    

    Laravel’s package auto-discovery registers the service provider and Crypto facade automatically.

  2. Publish the config (optional) – the package is “zero-config” for most primitives, but if you need default keys for JWS/HMAC or custom algorithm preferences, publish the config file:

    php artisan vendor:publish --tag=crypto-config
    

    Then set values in config/crypto.php (or use per-call arguments to override).

  3. First use case – secure token generation
    The quickest win is generating a cryptographically secure random token for API keys, password resets, or session identifiers:

    use Roundly\Crypto\Facades\Crypto;
    
    $token = Crypto::token(32); // 32 bytes of CSPRNG entropy, hex or base64url encoded
    

    Store only a hash of the token in your database and compare using hash_equals.

  4. Where to look next – Open the Crypto facade class (usually Roundly\Crypto\Facades\Crypto) to see the full list of methods grouped by primitive: totp(), hotp(), jws(), webauthn(), hmac(), token(), and codec helpers (base64url(), hex()). Each primitive is à la carte – use only what you need.

Implementation Patterns

Token generation & verification

Use Crypto::token($bytes) to create opaque tokens. For storage, hash with hash('sha256', $token) and verify with hash_equals. This pattern is ideal for API keys, email verification links, and remember-me cookies.

TOTP / HOTP for two-factor authentication

// Generate a new secret for a user
$secret = Crypto::totp()->generateSecret();

// Display a QR code (otpauth://totp/...)
$uri = Crypto::totp()->provisioningUri($secret, $user->email, 'MyApp');

// Verify a code (with a window of ±1 time step to allow for clock drift)
$isValid = Crypto::totp()->verify($secret, $request->code, window: 1);

For HOTP (counter-based), use Crypto::hotp()->verify($secret, $counter, $code) and increment the counter after each successful verification.

JWS / JOSE for stateless tokens

Sign and verify JSON Web Signatures without pulling in a full JWT library:

$jws = Crypto::jws()->sign(['sub' => $user->id, 'exp' => now()->addHour()->timestamp], 'HS256', $key);
$payload = Crypto::jws()->verify($jws, 'HS256', $key); // returns array or throws

Use asymmetric algorithms (RS256, ES256) when the verifier should not be able to sign. The package handles base64url encoding and header validation.

WebAuthn signature verification

For passkey registration and authentication, verify attestation and assertion signatures:

$valid = Crypto::webauthn()->verifyAssertion(
    $clientDataJson,
    $authenticatorData,
    $signature,
    $publicKeyPem,
    $expectedChallenge,
    $expectedOrigin,
    $expectedRpId
);

Always generate the challenge with Crypto::token(32) and store it in the session per attempt.

HMAC for webhook signatures

$signature = Crypto::hmac()->sign($payload, $secret, 'sha256');
$valid = Crypto::hmac()->verify($payload, $signature, $secret, 'sha256');

Use hash_equals internally (the package does) to avoid timing attacks.

Codecs

Convert between binary and URL-safe strings:

$encoded = Crypto::base64url()->encode($binary);
$decoded = Crypto::base64url()->decode($encoded);

Useful for JWT segments, WebAuthn challenges, and cookie values that must survive URL encoding.

Gotchas and Tips

  • TOTP time drift – always pass a window (e.g., 1 or 2) when verifying to tolerate clock skew. Ensure your server’s time is synced via NTP.
  • JWS algorithm pinning – never trust the alg header from an untrusted token. Always pass the expected algorithm explicitly to verify(). The package likely enforces this, but double-check.
  • WebAuthn challenge reuse – store the challenge in the session and invalidate it after one verification attempt. Also verify the origin and rpId to prevent phishing.
  • Key storage – keep JWS/HMAC secrets in .env or a secrets manager, not in version control. The config file should only reference env('CRYPTO_JWS_KEY').
  • Base64 vs base64url – JOSE and WebAuthn require URL-safe base64 without padding. Use the provided codec instead of PHP’s base64_encode.
  • Testing – freeze time with Carbon::setTestNow() when testing TOTP. Use known test vectors from RFC 6238 for HOTP/TOTP to validate your integration.
  • Zero-config ≠ no keys – the package provides sensible defaults for encoding and random tokens, but primitives like JWS and HMAC require you to supply a key (either via config or per-call). Don’t assume a default key is safe for production.
  • Extension points – if you need a custom algorithm or codec, check whether the package binds contracts (e.g., TotpContract) in the container. You can swap implementations via the service provider if needed.
  • Error handling – verification methods should throw exceptions on invalid signatures or expired tokens. Catch these and return a generic failure response to avoid leaking information.
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.
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core
nodisrupt/laravel-agent
sierratecnologia/media-manager