<?php

/*
 * Encrypt class for Droppy
 */

class Encrypt {
    function encryptfile($source,$destination,$passphrase,$stream=NULL) {
        // $source can be a local file...
        $fr = fopen($source, "rb");
        //$contents = fread($handle, filesize($source));
        //fclose($handle);

        $fw = fopen($destination, 'wb') or die("Could not open file for writing.");
        //stream_filter_append($fp, 'mcrypt.rijndael_256', STREAM_FILTER_WRITE, $opts);
        //fwrite($fp, $contents) or die("Could not write to file.");
        //fclose($fp);

        $iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
        $key = substr(md5("\x2D\xFC\xD8".$passphrase, true) . md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
        $opts = array('iv'=>$iv, 'key'=>$key);

        $stream = stream_filter_append($fw, 'mcrypt.rijndael_256', STREAM_FILTER_WRITE, $opts);

        while(!feof($fr))
        {
            $buff = fread($fr, 102400);

            fwrite($fw, $buff) or die("Could not write to file.");

            ob_flush();
            flush();
        }

        //stream_filter_remove($stream);

        fclose($fw);
        fclose($fr);

        return true;
    }
    function decryptfile($file,$passphrase) {

        $iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
        $key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
            md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
        $opts = array('iv'=>$iv, 'key'=>$key);

        $fp = fopen($file, 'rb');
        stream_filter_append($fp, 'mdecrypt.rijndael_256', STREAM_FILTER_READ, $opts);

        return $fp;
    }
    function generatePass()
    {
        // generate passphrase of 300 characters
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 300; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        return $randomString;
    }
}
