<?
error_reporting(E_ALL ^ E_NOTICE);

class Cipher {

	public static function encrypt($text, $key='INSECURE') {
		// Our output text
		$outText = '';

		// Iterate through each character
		for($i=0;$i<strlen($text);) {
			for($j=0;$j<strlen($key);$j++,$i++) {
				$outText .= $text{$i} ^ $key{$j};
			}
		}
		return $outText;
	}

	public static function decrypt($text, $key='INSECURE') {
		return Cipher::encrypt($text, $key);
	}

	/*

	        function hex2bin($h) {
	                if (!is_string($h)) return null;
	                $r='';
	                for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
	                return $r;
	        }

		// Let's define our key here
		$key = 'G4E';

		// Our plaintext/ciphertext
		$text = 'Programming Forums';

		$encrypted = encrypt($text, $key);
		echo $encrypted."<BR>";
		$text = $encrypted;

		echo encrypt($text, $key);
	*/

	private static function crypto_rand_secure($min, $max) {
	    $range = $max - $min;
	    if ($range < 1) return $min; // not so random...
	    $log = ceil(log($range, 2));
	    $bytes = (int) ($log / 8) + 1; // length in bytes
	    $bits = (int) $log + 1; // length in bits
	    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
	    do {
	        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
	        $rnd = $rnd & $filter; // discard irrelevant bits
	    } while ($rnd >= $range);
	    return $min + $rnd;
	}

	/**
	 * Gets random tokens with or without uniqid
	 */
	public static function getToken($length, $withUniq = false) {
	    $token = "";
	    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
	    $codeAlphabet.= "0123456789";
	    $max = strlen($codeAlphabet) - 1;
	    for ($i=0; $i < $length; $i++) {
	        $token .= $codeAlphabet[Cipher::crypto_rand_secure(0, $max)];
	    }

		// plus uniqid 13 bytes
		if ($withUniq) $token .= uniqid();

	    return $token;
	}

	public static function toBase64($encryptText) {

		//encode cipher text to base64
		$encodeText = base64_encode($encryptText);
		$encodeText = str_replace('+','%2B',$encodeText);
		$encodeText = str_replace('/','%2F',$encodeText);
		$encodeText = str_replace('=','%3D',$encodeText);

		return $encodeText;

	}

	public static function fromBase64($encryptText) {

		return base64_decode($encryptText);

	}

}
