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.
Installation:
composer require spomky-labs/php-aes-gcm
Add to composer.json under require if not using Composer globally.
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'
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'));
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);
}
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'));
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'));
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)));
Key Length:
Invalid key length if key is not 16, 24, or 32 bytes.random_bytes(32) for AES-256-GCM (most secure option).Base64 Handling:
TEXT fields in MySQL).json_encode() if storing arrays/objects:
$encrypted = $this->aesGcm->encrypt(json_encode($data));
$decrypted = json_decode($this->aesGcm->decrypt($encrypted), true);
Nonce Reuse:
Tag mismatch if the same nonce is reused with the same key.PHP Version:
Error Handling:
try {
$data = $this->aesGcm->decrypt($ciphertext);
} catch (\SpomkyLabs\AesGcm\Exception\DecryptionFailedException $e) {
Log::error("Decryption failed: " . $e->getMessage());
throw new \Exception("Invalid encrypted data");
}
var_dump(bin2hex($key)); // Should match your stored key
$testKey = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$aesGcm = new AesGcm($testKey);
$encrypted = $aesGcm->encrypt('test');
$decrypted = $aesGcm->decrypt($encrypted);
assert($decrypted === 'test');
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');
Authentication Tags: Verify tags manually if needed:
$tag = $aesGcm->getTag($ciphertext);
if (!$aesGcm->verifyTag($ciphertext, $tag)) {
throw new \Exception("Tag verification failed");
}
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);
}
Laravel Filesystem: Store encrypted files:
$encrypted = $this->aesGcm->encrypt(file_get_contents($filePath));
Storage::disk('s3')->put('encrypted_' . $fileName, $encrypted);
How can I help you explore Laravel packages today?