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 Urisoft\Filesystem;

// Replace these with the appropriate values for your application
$rootDirPath = __DIR__;
$filesystem = new Filesystem(); // Optional, , $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
}

use Urisoft\OpenSSLEncrypt;

$key = 'your-encryption-key'; // Replace with your secure key.
$cipher = 'AES-128-CBC'; // Optional, default is AES-128-CBC.

$encryptor = new OpenSSLEncrypt($key, $cipher);

$plainText = "Hello, World!";
$outputFormat = 'base64'; // Optional, formats: base64, hex, binary. Default is base64.

$encryptedText = $encryptor->encrypt($plainText, $outputFormat);

$inputFormat = 'base64'; // Should match the format used in encryption. Default is base64.

$decryptedText = $encryptor->decrypt($encryptedText, $inputFormat);