Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Clase para encriptacion con el metodo AES128.
- *
- * @author Roberto I Ramirez N <robertoiran [at] gmail.com>
- */
- final class CipherAES
- {
- private $_key = NULL;
- private $_iv = NULL;
- public function __construct($key = NULL, $iv = NULL, $bin = TRUE)
- {
- $this->setKey($key, $bin);
- $this->setIV($iv, $bin);
- }
- public function setKey($key = NULL, $bin = TRUE)
- {
- $this->_key = $bin ? hex2bin($key) : $key;
- }
- public function setIV($iv = NULL, $bin = TRUE)
- {
- $this->_iv = $bin ? hex2bin($iv) : $iv;
- }
- public function encrypt($string = NULL, $output_hex = TRUE)
- {
- $enc = NULL;
- $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
- $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
- if(mcrypt_generic_init($td, $this->_key, $this->_iv) != -1)
- {
- $clearPadd = $this->_pkcs5_pad($string,$size);
- $enc = mcrypt_generic($td, $clearPadd);
- mcrypt_generic_deinit($td);
- }
- mcrypt_module_close($td);
- return $output_hex ? bin2hex($enc) : $enc;
- }
- public function decrypt($string = NULL, $input_hex = TRUE)
- {
- $dec = NULL;
- $string = $input_hex ? hex2bin($string) : $string;
- $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
- $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
- if(mcrypt_generic_init($td, $this->_key, $this->_iv) != -1)
- {
- $dec = mdecrypt_generic($td, $string);
- $decWOPadding = $this->_pkcs5_unpad($dec);
- mcrypt_generic_deinit($td);
- }
- mcrypt_module_close($td);
- return $decWOPadding;
- }
- private function _pkcs5_pad($text, $blocksize)
- {
- $pad = $blocksize - (strlen($text) % $blocksize);
- return $text . str_repeat(chr($pad), $pad);
- }
- private function _pkcs5_unpad($text)
- {
- $pad = ord($text{strlen($text)-1});
- if ($pad > strlen($text)) return false;
- if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
- return substr($text, 0, -1 * $pad);
- }
- }
- if(!function_exists('hex2bin'))
- {
- function hex2bin($str)
- {
- return pack('H*',$str);
- }
- }
- /**
- * Ejemplo de uso
- */
- $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
- $_iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
- $_key = '74e6ac8eec9f8e9d2401f318cbd361551e3f721a4f4f9aab313bdfb9f61af932';
- $CipherAES = new CipherAES($_key, bin2hex($_iv));
- $string = 'Hola Mundo!';
- $strEnc = $CipherAES->encrypt($string);
- $strDec = $CipherAES->decrypt($strEnc);
- echo 'Cadena original: ', $string, '<br />';
- echo 'Cadena encriptada: ', $strEnc, '<br />';
- echo 'Cadena desencriptada: ', $strDec;
Advertisement
Add Comment
Please, Sign In to add comment