Home > Dev > Crypto > Secure File Encryption and Decryption

Secure File Encryption and Decryption

This code snippet encrypts and decrypts files securely using AES-256.

function encrypt_file($file_path, $key) {
    $iv_length = openssl_cipher_iv_length('aes-256-cbc');
    $iv = openssl_random_pseudo_bytes($iv_length);
    $data = file_get_contents($file_path);
    $ciphertext = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    file_put_contents($file_path . '.enc', $iv . $ciphertext);
    unlink($file_path);
}

function decrypt_file($file_path, $key) {
    $iv_length = openssl_cipher_iv_length('aes-256-cbc');
    $ciphertext = file_get_contents($file_path);
    $iv = substr($ciphertext, 0, $iv_length);
    $ciphertext = substr($ciphertext, $iv_length);
    $data = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, 0, $iv);
    file_put_contents(str_replace('.enc', '', $file_path), $data);
    unlink($file_path);
}

// Usage example
$key = 'your-encryption-key';  // Must be 32 bytes for AES-256
$file_path = 'secret.txt';

encrypt_file($file_path, $key);
decrypt_file($file_path . '.enc', $key);
Back