+/**
+ * Crypt file and returns decrypt key.
+ * @param $fp_src file path to the file to crypt.
+ * @param $fp_dst file path to the file to write crypted file (could be the same).
+ * @return decrypt key composed of the key and the iv separated by a point ('.')
+ */
+function
+jirafeau_encrypt_file ($fp_src, $fp_dst)
+{
+ $fs = filesize ($fp_src);
+ if ($fs === false || $fs == 0 || !extension_loaded('mcrypt'))
+ return '';
+
+ /* Prepare module. */
+ $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
+ $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($m), MCRYPT_DEV_URANDOM);
+ /* Generate key. */
+ $ks = mcrypt_enc_get_key_size($m);
+ $key = substr(md5(jirafeau_gen_random(12)), 0, $ks);
+ /* Init module. */
+ mcrypt_generic_init($m, $key, $iv);
+ /* Crypt file. */
+ $r = fopen ($fp_src, 'r');
+ $w = fopen ($fp_dst, 'c');
+ while (!feof ($r))
+ {
+ $enc = mcrypt_generic($m, fread ($r, 1024));
+ if (fwrite ($w, $enc) === false)
+ return '';
+ }
+ fclose ($r);
+ fclose ($w);
+ /* Cleanup. */
+ mcrypt_generic_deinit($m);
+ mcrypt_module_close($m);
+ return $key . "." . base64_encode($iv);
+}
+
+/**
+ * Decrypt file.
+ * @param $fp_src file path to the file to decrypt.
+ * @param $fp_dst file path to the file to write decrypted file (could be the same).
+ * @param $k string composed of the key and the iv separated by a point ('.')
+ * @return key used to decrypt. a string of length 0 is returned if failed.
+ */
+function
+jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
+{
+ $fs = filesize ($fp_src);
+ if ($fs === false || $fs == 0 || !extension_loaded('mcrypt'))
+ return false;
+
+ /* Extract key and iv. */
+ $ex = explode (".", $k);
+ $key = $ex[0];
+ $iv = base64_decode($ex[1]);
+ /* Init module */
+ $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
+ mcrypt_generic_init($m, $key, $iv);
+ /* Decrypt file. */
+ $r = fopen ($fp_src, 'r');
+ $w = fopen ($fp_dst, 'c');
+ while (!feof ($r))
+ {
+ $dec = mdecrypt_generic($m, fread ($r, 1024));
+ if (fwrite ($w, $dec) === false)
+ return false;
+ }
+ fclose ($r);
+ fclose ($w);
+ /* Cleanup. */
+ mcrypt_generic_deinit($m);
+ mcrypt_module_close($m);
+ return true;
+}