PHP code example of devuri / encryption

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

    

devuri / encryption example snippets


use Urisoft\EncryptionKey;

// Generate a new encryption key
$key = EncryptionKey::generate_key();

// Store the generated key securely (e.g., in a secret key file) for future use.

use Urisoft\Encryption;
use Symfony\Component\Filesystem\Filesystem;

// Replace these with the appropriate values for your application
$rootDirPath = __DIR__;
$filesystem = new Filesystem();
$secretKeyPath = '/path/to/secret_key_directory';
$keyId = 'secret'; // Optional, default is 'secret'

try {
    $encryption = new Encryption($rootDirPath, $filesystem, $secretKeyPath, $keyId);
} catch (InvalidArgumentException $e) {
    // Handle exception if the secret key file is not found
}

try {
    // Encrypt a file
    $inputFile = '/path/to/input_file.txt';
    $outputFile = '/path/to/encrypted_file.txt';
    $encryption->encrypt_file($inputFile, $outputFile);

    // Decrypt the encrypted file
    $encryptedFile = '/path/to/encrypted_file.txt';
    $decryptedFile = '/path/to/decrypted_file.txt';
    $encryption->decrypt_file($encryptedFile, $decryptedFile);
} catch (Exception $e) {
    // Handle encryption/decryption errors
}

$dataToEncrypt = 'This is sensitive data';
$encryptedData = $encryption->encrypt($dataToEncrypt);

// Optionally, encode the encrypted data in base64
$base64EncodedData = $encryption->encrypt($dataToEncrypt, true);

$encryptedData = '...'; // Replace this with the actual encrypted data
$decryptedData = $encryption->decrypt($encryptedData);

// Optionally, if the encrypted data was base64-encoded
$base64EncodedData = '...'; // Replace this with the actual base64-encoded data
$decodedDecryptedData = $encryption->decrypt($base64EncodedData, true);

if ($decryptedData === null || $decodedDecryptedData === null) {
    // Decryption failed or wrong key was loaded
    // Handle the error accordingly
}

try {
    // Encrypt the .env file
    $encryption->encrypt_envfile('/.env');
} catch (Exception $e) {
    // Handle encryption errors
}