Revision: Thu, 25 Apr 2024 11:06:46 GMT
v2.14 – outdated
This version of the documentation is outdated. Consider upgrading your project to Spiral Framework 3.12
Edit this page

Security - Data Encryption

Both Web and GRPC application skeletons include Encrypter component by default. To install Encrypter in other builds:

composer require spiral/encrypter

Note
Please note that the spiral/framework >= 2.6 already includes this component.

You must register bootloader Spiral\Bootloader\Security\EncrypterBootloader to activate the component.

Application Key

The encryption component based on defuse/php-encryption; it requires an encryption key provided by your application.

By default, EncrypterBootloader will load Base64 encoded key from the environment variable ENCRYPTER_KEY.

If you use Dotenv extension you can specify this key value in .env file located in the root of your application. To issue new key into .env run:

php app.php encrypt:key -m .env

Note
The Encrypter is used to protect your cookie values, changing the key will automatically invalidate all the issued cookies.

Usage

You can use the Encrypter in your application via Spiral\Encrypter\EncrypterInterface:

php
/**
 * Immutable class responsible for encryption services.
 */
interface EncrypterInterface
{
    /**
     * Create and encrypter instance with new key.
     *
     * @throws EncrypterException
     */
    public function withKey(string $key): EncrypterInterface;

    /**
     * Encryption ket value. Returns in a format of ANSI string.
     */
    public function getKey(): string;

    /**
     * Encrypt data into encrypter specific payload string. Can be decrypted only using decrypt()
     * method.
     *
     * @param mixed $data
     *
     * @throws EncryptException
     * @throws EncrypterException
     */
    public function encrypt($data): string;

    /**
     * Decrypt payload string. Payload should be generated by same encrypter using encrypt() method.
     *
     * @return mixed
     *
     * @throws DecryptException
     * @throws EncrypterException
     */
    public function decrypt(string $payload);
}

Encrypter is also available as prototype property encrypter:

php
protected function index(EncrypterInterface $encrypter): void
{
    $payload = $encrypter->encrypt(['abc']);
    dump($payload);

    dump($this->encrypter->decrypt($payload));
}