<?php
/*
TetraCrypt.php Ver 0.1
Copyright (c) 2007 Jeff Jones, www.tetraboy.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

class TetraCrypt {
    private 
$salt='tetraCRYPT--';
    private 
$mcrypt,$ctime;
    function 
__construct($salt='',$cipher='',$mode='') {
        if(
is_string($salt) && !empty($salt)){$this->salt=$salt;}
        
$this->setCipher($cipher,$mode);
        
$this->ctime=time();
    }
    private function 
setCipher($cipher,$mode='') {
        if(empty(
$cipher)){$cipher='rijndael-256';}
        if(empty(
$mode)){$mode 'cbc';}
        
$algo mcrypt_list_algorithms();
        
$modes mcrypt_list_modes();
        if(
in_array($cipher,$algo) && in_array($mode,$modes)) {
            
$this->mcrypt =  mcrypt_module_open($cipher,'',$mode,'');
        } else throw new 
Exception('Invalid algo/mode.');

    }
    private function 
init($key,$iv) {
        
$c_key substr($this->bighash($key), 0mcrypt_enc_get_key_size($this->mcrypt));
        
$c_iv substr($this->bighash($iv), 0mcrypt_enc_get_key_size($this->mcrypt));
        if (
mcrypt_generic_init($this->mcrypt$c_key$c_iv) != -1) {
            return 
$this->mcrypt;
        } else {throw new 
Exception('Invalid Init');}
    }
    private function 
bighash($string,$salt='') {
        
//Currently, the 512 bit output of this function is mostly useless. Will pad length for blowfish though.
        
if(strlen($string) > 64) {
            
$string1 substr($string,0,64);$string2 substr($string,64,128);
        } else {
$string1=$string;$string2=strrev($string);}
        if(empty(
$salt)){$salt=$this->salt;$salt $this->bighash($this->salt,'TetraCrypted');}
        
$bighash mhash(MHASH_SHA256,$string1.$salt).mhash(MHASH_SHA256,$string2.strrev($salt));

        return 
$bighash;
    }
    function 
encrypt($string,$key) {
        
$msgSalt=$this->random($string);
        
$iv=$this->getIV($string,$key);
        
$key=mhash(MHASH_SHA256,$key.$msgSalt);

        
$hmac mhash(MHASH_SHA256,$string,$key);
        
$string base64_encode($string);$base64=$string;
        
$strlen strlen($string);

        
$c $this->init($key,$iv);
        
$plaintext $hmac.$strlen.'|'.$string;
        
$ciphertext mcrypt_generic($c,$plaintext);
        
mcrypt_generic_deinit($c);
        
$encrypted $msgSalt.$iv.$ciphertext;
        return 
$encrypted;
    }
    function 
decrypt($string,$key) {
        
$msgSalt substr($string,0,32);
        
$iv substr($string,32,32);
        if(
strlen($msgSalt) != 32 || strlen($iv) != 32){throw new Exception('Invalid Encrypted');}
        
$key mhash(MHASH_SHA256,$key.$msgSalt);

        
$string substr($string,64);
        if(empty(
$string)){throw new Exception('Invalid Encrypted String');}

        
$c $this->init($key,$iv);
        
$decrypted mdecrypt_generic($c,$string);$plaintext=$decrypted;
        
mcrypt_generic_deinit($c);

        
$hmac substr($decrypted,0,32);
        
$decrypted substr($decrypted,32);
        
$strlen substr($decrypted,0,strpos($decrypted,'|'));
        
$decrypted substr($decrypted,strpos($decrypted,'|')+1);
        
$decrypted substr($decrypted,0,$strlen);$base64=$decrypted;
        
$decrypted base64_decode($decrypted);
        if(
$hmac == mhash(MHASH_SHA256,$decrypted,$key)) {return $decrypted;}else{throw new Exception('Invalid Decrypt\n');}
    }
    private function 
getIV($string,$key) {
        return  
$this->random(mhash(MHASH_SHA256,$string.sha1($key)));
    }
    private function 
random($seed='HAHA',$length='') {
        
$time=microtime();
        
$seedrnum min(strlen($seed),99999);
        if(
$seedrnum == 99999){$seedrnum $seedrnum/rand(2,3);}
        
$rand $seed.$this->salt;
        
$rand .= md5($seed.strrev(substr(sha1($seed.$this->salt),mt_rand(0,9),rand(24,32))).rand().base64_encode($seed.mt_rand()));
        
$rand .= mt_rand($seedrnum,mt_getrandmax())*mt_rand(1,$seedrnum)*rand(1,99999);
        
$rand .= mt_rand()+rand()+mt_rand()+mt_rand().mt_rand();
        
$rand .= serialize($GLOBALS);
        
$rand .= getmypid().getmyuid().getmygid().getmyinode().memory_get_usage().memory_get_peak_usage();
        
$dirs = array($_SERVER['DOCUMENT_ROOT'],$_SERVER['SCRIPT_FILENAME'],sys_get_temp_dir());
        foreach(
$dirs as $dir){if(!empty($dir)){$rand .= '||'.implode('/',stat($dir)).'||'.mt_rand();}}
        
$rand .= $this->ctime time() + (microtime() - $time);
        
$rand .= sha1($seed).md5(sha1($seed));
        
$rand mhash(MHASH_SHA256,$rand);
        return 
$rand;
    }

}
$c = new TetraCrypt();

$txt 'Hello World!';
echo 
'<h2>Plaintext</h2><pre>'.$txt.'</pre><hr />';

$txt $c->encrypt($txt,'SECRETSQUERLL');
echo 
'<h2>Encrypted</h2><pre>'.base64_encode($txt).'</pre><hr />';

$txt $c->decrypt($txt,'SECRETSQUERLL');
echo 
'<h2>Decrypted</h2><pre>'.$txt.'</pre><hr />';
?>