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 Laravel Package

web-token/jwt-encryption

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require web-token/jwt-encryption
    

    Ensure you also install the main JWT framework for full functionality:

    composer require web-token/jwt-framework
    
  2. First Use Case: Encrypt a JWT payload using a shared secret or public/private key pair:

    use WebToken\JWT\Encryption\Encryption;
    use WebToken\JWT\Encryption\Key;
    
    // Shared secret (symmetric)
    $secret = 'your-256-bit-secret';
    $key = new Key($secret, Key::ENCRYPTION_ALGORITHM_A256KW);
    $encryption = new Encryption($key);
    
    // Encrypt a JWT payload
    $encrypted = $encryption->encrypt('{"user_id":123,"role":"admin"}');
    
  3. Where to Look First:

    • Official Documentation (focus on the "Encryption" section).
    • src/Encryption.php for core logic.
    • src/Key.php for key management.

Implementation Patterns

Common Workflows

  1. Symmetric Encryption (Shared Secret):

    $key = new Key('shared-secret', Key::ENCRYPTION_ALGORITHM_A256KW);
    $encryption = new Encryption($key);
    
    // Encrypt
    $encrypted = $encryption->encrypt(json_encode(['data' => 'sensitive']));
    
    // Decrypt
    $decrypted = $encryption->decrypt($encrypted);
    
  2. Asymmetric Encryption (RSA/OAEP):

    $privateKey = file_get_contents('private.pem');
    $publicKey = file_get_contents('public.pem');
    
    $privateKeyObj = new Key($privateKey, Key::ENCRYPTION_ALGORITHM_RSA_OAEP);
    $publicKeyObj = new Key($publicKey, Key::ENCRYPTION_ALGORITHM_RSA_OAEP);
    
    $encryption = new Encryption($publicKeyObj); // Encrypt with public key
    $encrypted = $encryption->encrypt('{"data":"sensitive"}');
    
    $decryption = new Encryption($privateKeyObj); // Decrypt with private key
    $decrypted = $decryption->decrypt($encrypted);
    
  3. Integration with Laravel:

    • Store keys in .env (e.g., JWT_SECRET=your-secret).
    • Create a service provider to bind the Encryption class:
      $this->app->singleton('jwt.encryption', function ($app) {
          $secret = config('jwt.secret');
          $key = new Key($secret, Key::ENCRYPTION_ALGORITHM_A256KW);
          return new Encryption($key);
      });
      
    • Use dependency injection in controllers:
      public function encryptData(Request $request, Encryption $encryption) {
          $encrypted = $encryption->encrypt($request->input('data'));
          return response()->json(['encrypted' => $encrypted]);
      }
      
  4. JWT-Specific Usage: Combine with web-token/jwt-framework for encrypted JWTs:

    use WebToken\JWT\Builder;
    use WebToken\JWT\Signature\Hmac\Sha256;
    
    $builder = new Builder();
    $builder->withPayload(['user_id' => 123]);
    $builder->withEncryption($encryption); // Inject Encryption instance
    $jwt = $builder->getToken($secret, 'HS256');
    

Gotchas and Tips

Pitfalls

  1. Key Management:

    • Never hardcode secrets in source files. Use environment variables or a secure secrets manager.
    • Algorithm Mismatch: Ensure the encryption algorithm (Key::ENCRYPTION_ALGORITHM_*) matches the key type (e.g., A256KW for AES, RSA_OAEP for RSA).
      // ❌ Wrong: Using RSA key with AES algorithm
      $key = new Key($rsaPrivateKey, Key::ENCRYPTION_ALGORITHM_A256KW);
      
  2. Key Size Requirements:

    • AES keys must be 256-bit (32 bytes) for A256KW. Shorter keys will throw exceptions.
    • RSA keys must be at least 2048-bit for RSA_OAEP.
  3. Base64 Encoding:

    • The package expects raw binary keys (not Base64-encoded). Decode keys if they’re stored as strings:
      $key = base64_decode('your-base64-key');
      $keyObj = new Key($key, Key::ENCRYPTION_ALGORITHM_A256KW);
      
  4. Thread Safety:

    • The Encryption class is not thread-safe. Avoid sharing instances across concurrent requests (e.g., in Laravel, bind it as a singleton only if keys are immutable).
  5. Error Handling:

    • Decryption failures (e.g., wrong key, corrupted data) throw WebToken\JWT\Exception\InvalidTokenException. Catch and handle gracefully:
      try {
          $decrypted = $encryption->decrypt($encryptedData);
      } catch (InvalidTokenException $e) {
          Log::error('Decryption failed: ' . $e->getMessage());
          abort(403, 'Invalid token');
      }
      

Debugging Tips

  1. Verify Key Format:

    • For AES, keys should be 32 bytes (256 bits). Validate with:
      $key = 'your-secret';
      if (strlen($key) !== 32) {
          throw new \RuntimeException('AES key must be 32 bytes (256 bits)');
      }
      
  2. Check Algorithm Support:

    • Ensure your PHP installation supports the required algorithms (e.g., openssl_encrypt for AES, openssl_private_decrypt for RSA). Test with:
      php -m | grep openssl
      
  3. Logging Encrypted Data:

    • Log hashed versions of encrypted data (not raw values) to avoid exposing sensitive info:
      Log::debug('Encrypted data hash:', hash('sha256', $encryptedData));
      

Extension Points

  1. Custom Key Storage:

    • Extend Key to support custom key sources (e.g., AWS KMS, HashiCorp Vault):
      class CustomKey extends Key {
          public function __construct(string $keyId, string $algorithm) {
              $key = $this->fetchFromVault($keyId); // Custom logic
              parent::__construct($key, $algorithm);
          }
      }
      
  2. Hybrid Encryption:

    • Combine with web-token/jwt-framework to encrypt JWT claims:
      $builder = new Builder();
      $builder->withPayload(['data' => $encryption->encrypt('sensitive')]);
      
  3. Performance Optimization:

    • Reuse Encryption instances (they are stateless) but avoid recreating keys unnecessarily:
      // Good: Reuse key and encryption instance
      $key = new Key($secret, Key::ENCRYPTION_ALGORITHM_A256KW);
      $encryption = new Encryption($key);
      
      // Encrypt/decrypt multiple times...
      
  4. Testing:

    • Mock the Encryption class in unit tests to avoid key leakage:
      $mockEncryption = $this->createMock(Encryption::class);
      $mockEncryption->method('encrypt')->willReturn('mocked-encrypted-data');
      $mockEncryption->method('decrypt')->willReturn('mocked-decrypted-data');
      
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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