Skip to content

Encryption & Decryption

NexusPHP provides a robust, highly secure symmetric authenticated encryption wrapper utilizing the modern Libsodium extension built into PHP.

This ensures that your encrypted values are strictly authenticated, preventing malicious actors from modifying the encrypted payload without detection.


Configuration

Before using NexusPHP's encrypter, you must set an APP_KEY environment variable in your .env file.

This key should be a securely generated, highly random string of at least 16 characters (preferably 32 bytes).

APP_KEY=your_securely_generated_32_byte_string

If this key is missing, left as the default placeholder, or is too short, the Encryptor class will throw a RuntimeException to prevent you from deploying an insecure application.


Basic Usage

You may inject or instantiate the Nexus\Security\Encryptor class to encrypt and decrypt string values.

The encryptor uses Libsodium's sodium_crypto_secretbox algorithm, which provides state-of-the-art authenticated encryption with a secure random nonce generated automatically for every encryption operation.

Encrypting a Value

use Nexus\Security\Encryptor;

$encryptor = new Encryptor();

$plainText = 'My secret social security number';
$cipherText = $encryptor->encrypt($plainText);

// $cipherText is a safe base64-encoded string containing both the nonce and the encrypted payload.

Decrypting a Value

$decrypted = $encryptor->decrypt($cipherText);

echo $decrypted; // 'My secret social security number'

If the payload cannot be decrypted (e.g., if the APP_KEY has changed, the payload was maliciously tampered with, or the data is corrupted), the decrypt method will gracefully return null instead of throwing a fatal cryptographic exception.

$tamperedText = $cipherText . 'A';
$result = $encryptor->decrypt($tamperedText); // Returns null

Warning: Key Rotation

The encrypted values generated by the Encryptor are inextricably linked to your APP_KEY. If you change your application's key in the future, you will permanently lose the ability to decrypt any data previously encrypted with the old key.

If you store encrypted PII (Personally Identifiable Information) in your database, always ensure you have a secure backup of your .env file and APP_KEY.