spiral/encrypter
Spiral Encryption Component for secure string encryption/decryption in PHP, using modern cryptography with integrity protection. Includes tests, static analysis, and documentation; designed to integrate with the Spiral Framework or be used standalone via Composer.
The Spiral Encrypter component is a lightweight, PSR-12-compliant encryption wrapper built around PHP’s openssl_* functions. To begin:
composer require spiral/encrypterSpiral\Encrypter\EncrypterInterfaceuse Spiral\Encrypter\Encrypter;
use Spiral\Encrypter\Key;
$key = Key::fromString('your-32-byte-base64-key-here'); // Must be 32 bytes for AES-256
$encrypter = new Encrypter($key);
$encrypted = $encrypter->encrypt('secret data');
$decrypted = $encrypter->decrypt($encrypted);
Key::fromBase64() or Key::fromString()—ensure keys are 32 bytes for AES-256-CBC (default).Start by replacing base64_encode/decode or manual openssl calls in your codebase with this component for safer, more consistent encryption.
Factory-based creation (via EncrypterFactory):
$factory = new EncrypterFactory([
'cipher' => 'AES-256-CBC',
'mac' => 'SHA256', // for authenticated encryption (HMAC)
]);
$encrypter = $factory->getEncrypter($key);
Configuration-driven setup (ideal for DI containers):
return [
'encrypter' => [
'key' => env('ENCRYPTER_KEY'),
'cipher' => 'AES-256-CBC',
'mac' => 'SHA256',
],
];
Store & retrieve encrypted config (e.g., DB passwords, API tokens):
$config = [
'db_password' => $encrypter->encrypt($rawPassword),
];
// Later...
$decrypted = $encrypter->decrypt($config['db_password']);
Integrate with environment variables:
# .env
ENCRYPTER_KEY=base64:your_base64_encoded_32_byte_key=
$key = Key::fromBase64($_ENV['ENCRYPTER_KEY']);
Typed encryption for objects:
// Serialize + encrypt
$payload = $encrypter->encrypt(json_encode($data));
$data = json_decode($encrypter->decrypt($payload), true);
Use EncrypterFactory for default-safe configurations (e.g., enabling authenticated encryption via hmac/mac).
openssl_get_cipher_methods() may list AES-256-CBC but key length must be correct.EncrypterFactory over direct Encrypter instantiation unless you’re certain about defaults—factory ensures authenticated encryption (HMAC) is used to prevent padding oracle attacks.mac algorithm required: By default, EncrypterFactory enables MAC verification (SHA256). Without it, decrypt failures may not be obvious (silent corruption risk).base64_decode() only when migrating.v1.0.0 used Manager; renamed to Factory in v1.0.1.Spiral\Encrypter → Spiral\Encrypter (no prefix change, but ensure no conflicts).How can I help you explore Laravel packages today?