2012년 11월 24일 토요일

AES php Example CBC, 128bit, PKCS7

AES CBC/RIJNDALE128/PKCS7

CLASS

class aes {
 
    protected $mcrypt_cipher = MCRYPT_RIJNDAEL_128;
    protected $mcrypt_mode = MCRYPT_MODE_CBC;
 
    private $_key;
    private $_iv;
 
    public function __construct($key, $iv)
 {
        self::setKey($key);
        self::setIV($iv);
    }
 
    public function setKey($key)
    {
        $this->_key = base64_decode($key);
 
    }
 
    public function setIV($iv)
    {
        $this->_iv = base64_decode($iv);
    }
 
    public function decrypt ($value)
    {
        if ( is_null ($value) ) $value = "" ;
        $value = base64_decode ($value);
        $output = mcrypt_decrypt($this->mcrypt_cipher, $this->_key, $value, $this->mcrypt_mode, $this->_iv);
 
        return self::unpadPkcs7($output, strlen($output));
    }
 
    function unpadPkcs7($text, $blocksize) {
        if (empty($text)) {
            return '';
        }
 
        if (strlen($text) % $blocksize !== 0) {
            return false;
        }
 
        $pad = ord($text{strlen($text)-1});
 
        if ($pad > $blocksize || $pad > strlen($text) || $pad === 0) {
            return false;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }
        return substr($text, 0, - $pad);
    }
}

Usage

$aesClass = new aes('key', 'iv');
$decrypted = $aesClass->decrypt(urldecode($token));

Web AES Encryptor/Decryptor: http://crypto.ilhwan.com/aes