<?php
namespace Obj;

class Encoder {
	
	private $key;
	private $cipher;
	private $mode;
	
	/**
	 *
	 * args - array(
	 *	'hash' => hash method
	 *	'key' => path to private key
	 *	'encrypt' => encryption method
	 * )
	 */
	public function __construct($key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC) {
		$keyString = file_get_contents($key, true);
		$this->key = pack('H*', $keyString);
		$this->cipher = $cipher;
		$this->mode = $mode;
	}
	
	/**
	 * hash
	 */
	public static function hash($input, $hash = 'md5') {
		return hash($hash, $input);
	}
	
	public function encrypt($plaintext) {
		$key_size = strlen($this->key);
		
	    // create a random IV to use with CBC encoding
	    $iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
	    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
		
		$ciphertext = mcrypt_encrypt($this->cipher, $this->key,
			$plaintext, $this->mode, $iv);
										 
		$ciphertext = $iv . $ciphertext;
    
		// encode the resulting cipher text so it can be represented by a string
		$ciphertext_base64 = base64_encode($ciphertext);
		
		return $ciphertext_base64;
	}
	
	public function decrypt($ciphertext_base64) {
		$ciphertext_dec = base64_decode($ciphertext_base64);
		
		$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
    
		// retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
		$iv_dec = substr($ciphertext_dec, 0, $iv_size);
    
		// retrieves the cipher text (everything except the $iv_size in the front)
		$ciphertext_dec = substr($ciphertext_dec, $iv_size);

		// may remove 00h valued characters from end of plain text
		$plaintext_dec = mcrypt_decrypt($this->cipher, $this->key,
			$ciphertext_dec, $this->mode, $iv_dec);
			
		return $plaintext_dec;
	}
	
	/**
	 * Generates a random string from the given charset of input length
	 */
	public static function randomString($length = 10, $set = null) {
		
		if ($set == null) {
			$set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		}
		
		$len = strlen($set);
		$str = '';
		
		while ($length--) {
			$str .= $set[mt_rand(0, $len - 1)];
		}
		
		return $str;
	}
}
?>