Encrypt/Decrypt a file in php with OpenSSL

In today's digital age, ensuring security of sensitive information is paramount. One effective way to safeguard data is through encryption. In this blog, we'll explore the fundamentals of file encryption and decryption using PHP OpenSSL extension.

First, you need to make sure you have OpenSSL library installed and You have installed and enabled PHP OpenSSL extension.

An example to encrypt a file look like this:

encrypt.php
$encryptionKey = 'YourEncryptionKey';
// Read the content of the file
$fileContent = file_get_content($file);

// Generate an initialization vector (IV)
$iv = openssl_random_pseudo_bytes(
    openssl_cipher_iv_length('AES-256-CBC')
);

// Encrypt the file content
$encryptedContent = openssl_encrypt(
    $fileContent,
    'AES-256-CBC',
    $encryptionKey,
    0,
    $iv
);

// Concatenate the IV and encrypted content
$encryptedData = $iv.$encryptedContent;

In this example, the file at $fileContent is read, encrypted using AES-256-CBC algorithm, and then saved to $encryptedFile. The encryption key $encryptionKey is used along with a randomly generated initialization vector $iv to encrypt the content.

An example to decrypt a file:

decrypt.php
$encryptionKey = 'YourEncryptionKey';
// Read the content of the file
$fileContent = file_get_content($file);

// Extract the IV and encrypted content
$iv = substr( 
    $fileContent,
    0,
    openssl_cipher_iv_length('AES-256-CBC')
);
$encryptedContent = substr(
    $fileContent,
    openssl_cipher_iv_length('AES-256-CBC')
);

// Decrypt the content
$decryptedContent = openssl_decrypt(
    $encryptedContent,
    'AES-256-CBC',
    $encryptionKey,
    0,
    $iv
);

In this example, the encrypted data is read from $fileContent. The initialization vector $iv and encrypted content are extracted from the data. The content is then decrypted using the same encryption key $encryptionKey and written to $decryptedFile.

Make sure to replace 'YourEncryptionKey' with a strong and secure encryption key of your choice.

Please note that symmetric encryption requires keeping the encryption key secure. If you need to transmit or store the encrypted file securely, you may also consider using asymmetric encryption (public-key cryptography) where different keys are used for encryption and decryption.