<?php
/**
 * @copyright ONE/DEPO Project
 * @license   PHP License 3.01 <http://www.php.net/license/3_01.txt>
 */


class Onedepo_Logic_Crypt
{
    var $td;
    var $iv_size;
    var $key;

    function setTd()
    {
        //アルゴリズムとモードのモジュールをオープンする
        $this -> td = mcrypt_module_open(MCRYPT_PARA1, MCRYPT_PARA2, MCRYPT_PARA3, MCRYPT_PARA4);
        $this -> iv_size = mcrypt_enc_get_iv_size($this -> td);
        $this -> key = md5(MCRYPT_KEY);
        $this -> key = substr($this -> key, 0, $this -> iv_size);

    }

    /** 暗号化を行う **/
    function encrypt ($string)
    {
        srand((double) microtime() * 1000000);
        $this -> setTd();

        $iv = mcrypt_create_iv($this -> iv_size, MCRYPT_RAND);
        if (mcrypt_generic_init($this -> td, $this -> key, $iv) != -1) {
            $c_t = mcrypt_generic($this -> td, $string);
            mcrypt_generic_deinit($this -> td);
            mcrypt_module_close($this -> td);
            $c_t = $iv.$c_t;
            $c_t = base64_encode($c_t);
            return $c_t;
        }
    }

    /** 復号化を行う **/
    function decrypt($string)
    {
        $this -> setTd();

        $string = base64_decode($string);
        $iv = substr($string, 0, $this -> iv_size);
        $string = substr($string, $this -> iv_size);
        if (mcrypt_generic_init($this -> td, $this -> key, $iv) != -1) {
            $c_t = mdecrypt_generic($this -> td, $string);
            mcrypt_generic_deinit($this -> td);
            mcrypt_module_close($this -> td);
            return $c_t;
        }
    }

}
?>