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

Jwt Encryption Algorithm Aesgcm Laravel Package

web-token/jwt-encryption-algorithm-aesgcm

JWT encryption algorithm implementation using AES-GCM for the web-token/jwt framework. Adds AESGCM-based JWE support with authenticated encryption, suitable for securing tokens with modern AEAD cryptography in PHP applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require web-token/jwt-encryption-algorithm-aesgcm
    

    Add to composer.json under require if not using Composer globally.

  2. Basic Usage Import the algorithm in your Laravel project:

    use WebToken\JWTEncryptionAlgorithm\AESGCM;
    
  3. First Use Case: Encrypting JWT Payload

    use Firebase\JWT\JWT;
    use WebToken\JWTEncryptionAlgorithm\AESGCM;
    
    $key = 'your-32-byte-secret-key'; // Must be 32 bytes for AES-256-GCM
    $algorithm = new AESGCM($key);
    
    $payload = [
        'user_id' => 123,
        'exp' => time() + 3600,
        'data' => ['secret' => 'sensitive_info']
    ];
    
    $token = JWT::encode($payload, '', 'HS256', $algorithm);
    
  4. Decoding the Token

    $decoded = JWT::decode($token, '', ['HS256'], $algorithm);
    

Implementation Patterns

Workflow: Secure Data in JWT

  1. Key Management

    • Store keys in Laravel’s .env (e.g., JWT_AES_KEY=base64:32bytekey).
    • Use Laravel’s config() helper to fetch keys securely:
      $key = base64_decode(config('jwt.aes_key'));
      
  2. Integration with Laravel Sanctum/Passport

    • Extend Sanctum’s CreateFreshApiToken or Passport’s TokenRepository to encrypt sensitive claims:
      $userToken = $user->createToken('API Token');
      $token = $userToken->accessToken;
      $token->setPayloadAttribute('encrypted_data', $encryptedPayload);
      
  3. Middleware for Decryption

    • Create middleware to decrypt and validate payloads:
      public function handle($request, Closure $next) {
          $token = $request->bearerToken();
          $decoded = JWT::decode($token, '', ['HS256'], new AESGCM(config('jwt.aes_key')));
          $request->merge(['decrypted_data' => $decoded->data]);
          return $next($request);
      }
      
  4. Batch Processing

    • Use the algorithm in queue jobs for bulk encryption/decryption:
      public function handle() {
          $tokens = Token::all();
          foreach ($tokens as $token) {
              $decrypted = JWT::decode($token->encrypted_payload, '', ['HS256'], $algorithm);
              // Process decrypted data...
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Key Length Requirements

    • Error: Invalid key length for AES-GCM (must be 32 bytes for AES-256).
    • Fix: Ensure keys are exactly 32 bytes. Use:
      $key = random_bytes(32); // For new keys
      $key = base64_decode('your_base64_key'); // For existing keys
      
  2. Nonce Handling

    • Gotcha: GCM requires a unique nonce per encryption. The package auto-generates one, but ensure no collisions in high-throughput systems.
    • Tip: Log nonces for debugging if decryption fails with tag mismatch.
  3. Compatibility with Other Libraries

    • Issue: Some JWT libraries (e.g., firebase/php-jwt) may not natively support custom algorithms.
    • Workaround: Use the package’s AESGCM class directly with the library’s encode/decode methods, as shown in Getting Started.
  4. Performance Overhead

    • Tip: AES-GCM is slower than HS256. Benchmark in your stack:
      php artisan tinker
      >>> \WebToken\JWTEncryptionAlgorithm\AESGCM::bench();
      

Debugging

  1. Decryption Failures

    • Check:
      • Key correctness (var_dump($key === config('jwt.aes_key'))).
      • Token integrity (corrupted payloads may fail silently).
    • Log:
      try {
          $decoded = JWT::decode($token, '', ['HS256'], $algorithm);
      } catch (\Exception $e) {
          \Log::error('JWT Decode Error', ['token' => $token, 'error' => $e->getMessage()]);
      }
      
  2. Tag Mismatch Errors

    • Cause: Reused nonce or corrupted ciphertext.
    • Fix: Regenerate the token with a new nonce:
      $algorithm = new AESGCM($key, ['nonce' => random_bytes(12)]); // Custom nonce
      

Extension Points

  1. Custom Nonce Generation

    • Override the default nonce (12 bytes) for specific use cases:
      $algorithm = new AESGCM($key, [
          'nonce' => 'custom-nonce-123', // Must be 12 bytes
      ]);
      
  2. Integration with Laravel’s Encryption

    • Combine with Laravel’s Crypt facade for hybrid encryption:
      $encryptedKey = Crypt::encrypt($key);
      $algorithm = new AESGCM(Crypt::decrypt($encryptedKey));
      
  3. Testing

    • Use PHPUnit to mock the algorithm for unit tests:
      $mockAlgorithm = $this->createMock(AESGCM::class);
      $mockAlgorithm->method('encrypt')->willReturn('mocked-ciphertext');
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky