+ * Decrypt file using Sodium.
+ * @param $fp_src file path to the file to decrypt.
+ * @param $fp_dst file path to the file to write decrypted file (must not be the same).
+ * @param $k decryption key
+ * @return true if decryption succeeded, false otherwise
+ */
+function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
+{
+ $fs = filesize($fp_src);
+ if ($fs === false || $fs == 0 || extension_loaded('sodium') == false || $fp_src == $fp_dst) {
+ return false;
+ }
+
+ /* Decrypt file. */
+ $r = fopen($fp_src, 'rb');
+ $w = fopen($fp_dst, 'wb');
+
+ $crypt_header = fread($r, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES);
+
+ /* Init module. */
+ $crypt_state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($crypt_header, $k);
+
+ /* Decrypt file. */
+
+ for ($i = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES) {
+ $to_dec = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES);
+ [$dec, $crypt_tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($crypt_state, $to_dec);
+
+ if (fwrite($w, $dec) === false) {
+ return false;
+ }
+ }
+
+ fclose($r);
+ fclose($w);
+
+ /* Cleanup. */
+ sodium_memzero($crypt_state);
+
+ return true;
+}
+
+/**
+ * Decrypt file using mcrypt.