PHP code example of tuzelko / yii2-encrypted-attribute

1. Go to this page and download the library: Download tuzelko/yii2-encrypted-attribute library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tuzelko / yii2-encrypted-attribute example snippets


// config/main.php
use tuzelko\yii\keystorage\KeyProviderInterface;
use tuzelko\yii\keystorage\KeyStorage;
use tuzelko\yii\keystorage\types\SodiumSecretboxKey;

'container' => [
    'singletons' => [
        KeyProviderInterface::class => static fn () => new KeyStorage([
            'keys' => [
                'appCrypto' => [
                    'base64' => getenv('APP_CRYPTO_KEY'), // 32 bytes, base64-encoded
                    'type'   => SodiumSecretboxKey::class,
                ],
            ],
        ]),
    ],
],

use tuzelko\yii\encryptedattribute\ciphers\SodiumSecretboxCipher;
use tuzelko\yii\encryptedattribute\EncryptedAttributeBehavior;
use yii\db\ActiveRecord;

class Integration extends ActiveRecord
{
    public function behaviors(): array
    {
        return [
            [
                'class'      => EncryptedAttributeBehavior::class,
                'keyName'    => 'appCrypto',
                'attributes' => ['api_token', 'api_secret'],
                'cipher'     => SodiumSecretboxCipher::class,
            ],
        ];
    }
}

$integration = new Integration();
$integration->api_token_decrypted = $rawToken;   // encrypted on assignment
$integration->save();

echo $integration->api_token_decrypted;          // decrypted on read
echo $integration->api_token;                    // base64(nonce || ciphertext) — safe to log

$integration->api_token_decrypted = null;        // clears the column

use tuzelko\yii\encryptedattribute\ciphers\AesGcmCipher;

[
    'class'      => EncryptedAttributeBehavior::class,
    'keyName'    => 'appCrypto',
    'attributes' => ['api_token'],
    'cipher'     => AesGcmCipher::class,
]

use tuzelko\yii\encryptedattribute\ciphers\XChaCha20Poly1305Cipher;

public function behaviors(): array
{
    return [
        [
            'class'      => EncryptedAttributeBehavior::class,
            'keyName'    => 'appCrypto',
            'attributes' => ['api_token'],
            'cipher'     => XChaCha20Poly1305Cipher::class,
            'cipherOptionMethods' => [
                XChaCha20Poly1305Cipher::OPTION_AD => 'encryptionContext',
            ],
        ],
    ];
}

public function encryptionContext(string $attribute): string
{
    return self::tableName() . '.' . $attribute;
}
bash
php -r "echo base64_encode(random_bytes(32)), PHP_EOL;"