Revision: Tue, 29 Oct 2024 10:57:42 GMT

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 the bootloader Spiral\Bootloader\Security\EncrypterBootloader to activate the component.

Application Key

The encryption component is 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.

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));
}