PHP: How to Encrypt and Decrypt Files

Updated: January 12, 2024 By: Guest Contributor Post a comment

Introduction

As developers and users become increasingly conscious of data security, encryption becomes a critical part of managing and transferring files. In this tutorial, you’ll learn how to use PHP to encrypt and decrypt files, to ensure the confidentiality and integrity of your data. We will cover the concepts of encryption and decryption, generate secure keys, and provide a real-world example of a PHP script designed to handle these tasks.

What is Encryption & Decryption?

Encryption is a security measure that uses algorithms to scramble data into an unintelligible format that can only be reverted back to its original form with the correct decryption key. The primary aim is to protect data from unauthorized access.

Decryption is the process of converting encrypted data back into its original form, so it can be accessed and understood.

Generating Encryption Keys

Secure encryption depends on strong keys. PHP provides functions to generate random bytes that can be used as keys.

$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

Here we generate a 256-bit key suitable for AES-256 encryption, and an initialization vector (IV) matching the block size of the cipher.

Encrypting Files with PHP

To encrypt files, you can use the OpenSSL functions provided by PHP. The following example demonstrates how to perform AES-256 encryption on a file.

function encryptFile($fileToEncrypt, $key, $iv) {
    $plaintext = file_get_contents($fileToEncrypt);
    $ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, $options=0, $iv);
    file_put_contents($fileToEncrypt . '.enc', $ciphertext);
}

This function reads the file, encrypts the data, and then saves it with an ‘.enc’ extension to denote its encrypted state.

Decrypting Files with PHP

Decryption is the inverse of the encryption process. Use the following function to decrypt a file using the same key and IV.

function decryptFile($encryptedFile, $key, $iv) {
    $ciphertext = file_get_contents($encryptedFile);
    $plaintext = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, $options=0, $iv);
    file_put_contents(str_replace('.enc', '', $encryptedFile), $plaintext);
}

This function takes the encrypted file, decrypts the content, and saves it back to its original filename without the ‘.enc’ extension.

End-to-End Example

Let’s build an end-to-end script that allows users to choose whether to encrypt or decrypt a file, handling both processes.

// Define key and IV
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
// Check user input
if ($argc !== 4 || !in_array($argv[1], ['--encrypt', '--decrypt'])) {
    echo "Usage: {$argv[0]} --encrypt|--decrypt file keyFile
";
    exit(1);
}
$action = $argv[1];
$file = $argv[2];
$keyFile = $argv[3];
// Read or save the key and IV
if ($action === '--encrypt') {
    file_put_contents($keyFile, json_encode(['key' => base64_encode($key), 'iv' => base64_encode($iv)]));
    encryptFile($file, $key, $iv);
} elseif ($action === '--decrypt') {
    if (!file_exists($keyFile)) {
        echo "Key file does not exist.
";
        exit(1);
    }
    $keyData = json_decode(file_get_contents($keyFile), true);
    $key = base64_decode($keyData['key']);
    $iv = base64_decode($keyData['iv']);
    decryptFile($file, $key, $iv);
} else {
    echo "Invalid action.
";
    exit(1);
}

Security Considerations

Encryption is not a silver bullet. Proper key management, awareness of security risks, and using well-tested encryption algorithms are essential. The OpenSSL PHP extension is a mature and widely used module that offers strong encryption capabilities, but as a developer, you also need to ensure that your keys are stored securely and that your code does not introduce vulnerabilities.

Conclusion

By now, you should have a working example of how to encrypt and decrypt files in PHP using OpenSSL. Remember, the above code is a simple representation to demonstrate the concept. In a production environment, you should enforce stricter error handling and security checks.

Encryption is a vital tool in your security arsenal — use it wisely, keep your keys secure, and test your implementation thoroughly. With the rise of data breaches, having the know-how to protect your data properly is more important than ever.