How do you use Phalcon’s built-in encryption features?

How do you use Phalcon’s built-in encryption features?

To use Phalcon’s built-in encryption features, follow these minimal steps:

1. Set Up the Encryption Service

First, register the encryption service in the Dependency Injection (DI) container using a secure key.

Example

<?php
use Phalcon\Crypt;
use Phalcon\Di\FactoryDefault;

$di = new FactoryDefault();

$di->set('crypt', function () {
    $crypt = new Crypt();

    // Set a secret key for encryption (must be 16, 24, or 32 characters)
    $crypt->setKey('my-secret-key');
    
    return $crypt;
});
?>

2. Encrypt Data

Use the encrypt method to encrypt sensitive data.

Example

<?php
$encryptedData = $this->crypt->encrypt('Sensitive Data');
echo $encryptedData;  // Outputs encrypted string
?>

3. Decrypt Data

To decrypt the encrypted data, use the decrypt method.

Example

<?php
$decryptedData = $this->crypt->decrypt($encryptedData);
echo $decryptedData;  // Outputs: Sensitive Data
?>

4. Customize Encryption Settings (Optional)

You can customize the encryption algorithm or padding method if needed.

Example

<?php
$this->crypt->setCipher('aes-256-cfb');  // Set a different encryption algorithm
$this->crypt->useSigning(true);          // Enable message signing for integrity
?>

Related Questions & Topics