Skip to content

Latest commit

 

History

History
87 lines (71 loc) · 2.42 KB

encrypter.md

File metadata and controls

87 lines (71 loc) · 2.42 KB

Security - Data Encryption

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

$ composer require spiral/encrypter

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:

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

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

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

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

Encrypter is also available as prototype property encrypter:

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

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