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

Php Aes Gcm Laravel Package

spomky-labs/php-aes-gcm

PHP library implementing AES-GCM (Galois/Counter Mode) authenticated encryption. Provides encrypt/decrypt with IV/nonce handling, auth tags, and AAD support for securing data with integrity. Useful for token payloads, messages, and secure storage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spomky-labs/php-aes-gcm
    

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

  2. First Use Case: Encrypt a sensitive string (e.g., API key, user token) and decrypt it later:

    use SpomkyLabs\AesGcm\AesGcm;
    
    $key = random_bytes(32); // 256-bit key (required for AES-256-GCM)
    $aesGcm = new AesGcm($key);
    
    // Encrypt
    $plaintext = 'My super secret data';
    $ciphertext = $aesGcm->encrypt($plaintext);
    // Output: base64-encoded string (e.g., "U2FsdGVkX1...")
    
    // Decrypt
    $decrypted = $aesGcm->decrypt($ciphertext);
    // Output: 'My super secret data'
    
  3. Key Management: Store the $key securely (e.g., environment variables, Laravel's .env):

    AES_GCM_KEY=your_32_byte_base64_encoded_key_here
    

    Retrieve it in Laravel:

    $key = base64_decode(env('AES_GCM_KEY'));
    

Implementation Patterns

Workflows

  1. Database Encryption: Encrypt sensitive fields (e.g., password, credit_card) before saving to the database:

    // Model Observer or Accessor
    public function setEncryptedAttribute($value) {
        $this->attributes['encrypted_field'] = $this->aesGcm->encrypt($value);
    }
    
    public function getEncryptedAttribute($value) {
        return $this->aesGcm->decrypt($value);
    }
    
  2. API Request/Response: Encrypt payloads for sensitive endpoints:

    // Encrypt before sending to client
    $response = response()->json([
        'data' => $this->aesGcm->encrypt($sensitiveData)
    ]);
    
    // Decrypt on incoming request
    $decryptedData = $this->aesGcm->decrypt(request('encrypted_data'));
    
  3. Caching Secrets: Store encrypted values in Laravel's cache:

    Cache::put('user_token', $this->aesGcm->encrypt($token), now()->addHours(1));
    $token = $this->aesGcm->decrypt(Cache::get('user_token'));
    

Integration Tips

  • Laravel Service Provider: Bind the AesGcm instance to the container for dependency injection:

    public function register() {
        $this->app->singleton(AesGcm::class, function ($app) {
            $key = base64_decode(env('AES_GCM_KEY'));
            return new AesGcm($key);
        });
    }
    

    Usage in controllers:

    public function __construct(private AesGcm $aesGcm) {}
    
  • Middleware for Encryption: Create middleware to auto-encrypt/decrypt request/response data:

    public function handle($request, Closure $next) {
        $request->merge([
            'decrypted_data' => $this->aesGcm->decrypt($request->encrypted_data)
        ]);
        return $next($request);
    }
    
  • Queue Jobs: Encrypt job payloads to avoid logging sensitive data:

    dispatch(new ProcessPaymentJob($this->aesGcm->encrypt($paymentData)));
    

Gotchas and Tips

Pitfalls

  1. Key Length:

    • Error: Invalid key length if key is not 16, 24, or 32 bytes.
    • Fix: Always use random_bytes(32) for AES-256-GCM (most secure option).
    • Note: Never hardcode keys in source files.
  2. Base64 Handling:

    • The library returns base64-encoded strings by default. Ensure your database/storage can handle this (e.g., TEXT fields in MySQL).
    • Tip: Use json_encode() if storing arrays/objects:
      $encrypted = $this->aesGcm->encrypt(json_encode($data));
      $decrypted = json_decode($this->aesGcm->decrypt($encrypted), true);
      
  3. Nonce Reuse:

    • Error: Tag mismatch if the same nonce is reused with the same key.
    • Fix: The library auto-generates nonces, but avoid manually reusing them.
  4. PHP Version:

    • Requires PHP 7.1+. Test on your target PHP version (e.g., Laravel Valet/XAMPP may lag behind).
  5. Error Handling:

    • Decryption fails silently on invalid data. Always wrap decryption in a try-catch:
      try {
          $data = $this->aesGcm->decrypt($ciphertext);
      } catch (\SpomkyLabs\AesGcm\Exception\DecryptionFailedException $e) {
          Log::error("Decryption failed: " . $e->getMessage());
          throw new \Exception("Invalid encrypted data");
      }
      

Debugging

  • Verify Keys: Compare keys using:
    var_dump(bin2hex($key)); // Should match your stored key
    
  • Test with Known Values: Use a fixed key and plaintext to verify the library works as expected:
    $testKey = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
    $aesGcm = new AesGcm($testKey);
    $encrypted = $aesGcm->encrypt('test');
    $decrypted = $aesGcm->decrypt($encrypted);
    assert($decrypted === 'test');
    

Extension Points

  1. Custom Nonces: Override nonce generation for specific use cases (e.g., deterministic encryption):

    $aesGcm = new AesGcm($key, null, true); // Force custom nonce
    $aesGcm->setNonce('your_custom_nonce_here');
    
  2. Authentication Tags: Verify tags manually if needed:

    $tag = $aesGcm->getTag($ciphertext);
    if (!$aesGcm->verifyTag($ciphertext, $tag)) {
        throw new \Exception("Tag verification failed");
    }
    
  3. Performance: For bulk operations, reuse the AesGcm instance (it’s stateless but avoids re-initialization):

    $aesGcm = new AesGcm($key);
    foreach ($data as $item) {
        $encrypted[] = $aesGcm->encrypt($item);
    }
    
  4. Laravel Filesystem: Store encrypted files:

    $encrypted = $this->aesGcm->encrypt(file_get_contents($filePath));
    Storage::disk('s3')->put('encrypted_' . $fileName, $encrypted);
    
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.
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
spatie/mailcoach-vapor