PHP code example of tezmanian / utils-crypto

1. Go to this page and download the library: Download tezmanian/utils-crypto 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/ */

    

tezmanian / utils-crypto example snippets


use Tezmanian\Utils\Crypto\AesEncryptionService;
use Tezmanian\Utils\Crypto\AesCipher;

// Generate a 64-character hex key (32 bytes = AES-256)
$hexKey  = bin2hex(random_bytes(32));
$service = new AesEncryptionService($hexKey);

$encrypted = $service->encrypt('super-secret-value');
$plaintext = $service->decrypt($encrypted);

new AesEncryptionService(string $hexKey, AesCipher $cipher = AesCipher::Aes256Gcm)

$service->encrypt(string $plaintext): string   // returns base64-encoded ciphertext
$service->decrypt(string $encoded): string     // returns original plaintext
$service->getCipher(): AesCipher               // returns the active cipher variant

AesCipher::Aes256Gcm->>nonceLength();          // 12
AesCipher::Aes256Gcm->tagLength();            // 16
AesCipher::Aes256Gcm->label();                // 'AES-256-GCM (32 bytes / 256 bits)'

AesCipher::values();                          // ['aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm']
AesCipher::hasValue('aes-256-gcm');           // true
AesCipher::find('aes-256-gcm');               // AesCipher::Aes256Gcm

// AES-256-GCM (default, recommended)
$key256  = bin2hex(random_bytes(32)); // 64 hex chars
$service = new AesEncryptionService($key256);

// AES-192-GCM
$key192  = bin2hex(random_bytes(24)); // 48 hex chars
$service = new AesEncryptionService($key192, AesCipher::Aes192Gcm);

// AES-128-GCM
$key128  = bin2hex(random_bytes(16)); // 32 hex chars
$service = new AesEncryptionService($key128, AesCipher::Aes128Gcm);

// Wrong key length → InvalidArgumentException at construction time
new AesEncryptionService('tooshort', AesCipher::Aes256Gcm);

// Tampered ciphertext → RuntimeException
$service->decrypt(base64_encode(str_repeat('x', 64)));

// Invalid base64 → RuntimeException
$service->decrypt('not-base64!!!');