I'm writing a small script in PHP to backup my files. Before I transfer the files from the server I want to encrypt them.
I did that in previous versions of my script by using exec() and OpenSSL on my Linuxserver. Now I'm looking for a native PHP-Function to do this job, mainly for better error handling.
The thing is that my files may get big (like 20gb). Furthermore it's a must that I can use a command on my shell to decrypt the file again.
Does anyone know how to encrypt big files in PHP and then decrypt on the commandline?
I'm now using PHP's mcrypt functions to encrypt:
// IV:
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
// Create new random Key:
$key = openssl_random_pseudo_bytes(32);
// Encrypt:
$fileStream = fopen($file, "r");
$encFileStream = fopen($file . ".enc.data", "w");
$opts = [
'iv' => $iv,
'key' => $key,
'mode' => 'cbc'
];
stream_filter_append($encFileStream, 'mcrypt.rijndael-256', STREAM_FILTER_WRITE, $opts);
stream_copy_to_stream($fileStream, $encFileStream);
fclose($fileStream);
fclose($encFileStream);
// Encrypt random generated key and save it:
$encryptedKey = null;
openssl_public_encrypt($key, $encryptedKey, $publickey);
file_put_contents($file . ".enc.key", $encryptedKey);
// Save Initial Vetor:
file_put_contents($file . ".enc.iv", $iv);
// Delete unencrypted file:
unlink($file);
Now to decrypt on the linux commandline I tried to use mcrypt as well. But the big problem I have with that is that I have no idea how to add the IV to mdecrypt
. My command I have so far is:
mdecrypt --decrypt -m CBC -f key.key archive_hallo.tar.gz.enc.data
Which of course does not work because the IV is missing. So, does anyone know how to add the IV to my mdecrypt command?