<?php 

class encrypthelper
{

    protected static $skey = "bcb04b7e103a0cd8b547630fdebae5e1";
    protected static $method = 'BF-OFB';


    private static function safe_b64encode($text) {
        $data = base64_encode($text);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

    private static function safe_b64decode($payload) {
        $data = str_replace(array('-','_'),array('+','/'),$payload);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }


    public static function encode($text){ 
        if(empty($text))
            return false;

        $iv_length = openssl_cipher_iv_length(self::$method);
        $iv = openssl_random_pseudo_bytes($iv_length);
        $crypted = openssl_encrypt($text, self::$method, self::$skey, null, $iv);
        $iv_b64 = self::safe_b64encode($iv);
        $payload = $iv_b64 . '$' . $crypted;
        return trim(self::safe_b64encode($payload)); 
    }


    public static function decode($crypted){
        if(empty($crypted))
            return false;

        $decoded = self::safe_b64decode($crypted);                 
        $a = explode('$', $decoded);
        $iv_b64 = $a[0];
        $payload = $a[1];
        $text = openssl_decrypt($payload, self::$method, self::$skey, null, self::safe_b64decode($iv_b64));
        return trim($text);
    }

}

