public function encrypt($text, $key = null)
{
if (!function_exists("mcrypt_get_iv_size")) {
throw new Exception("mcrypt extension is required");
}
if ($key === null) {
$encryptKey = $this->key;
} else {
$encryptKey = $key;
}
if (empty($encryptKey)) {
throw new Exception("Encryption key cannot be empty");
}
$ivSize = mcrypt_get_iv_size($this->cipher, $this->mode);
if (strlen($encryptKey) > $ivSize) {
throw new Exception("Size of key is too large for this algorithm");
}
$iv = strval(mcrypt_create_iv($ivSize, MCRYPT_RAND));
$blockSize = intval(mcrypt_get_block_size($this->cipher, $this->mode));
if ($this->padding != 0 && ($this->mode == MCRYPT_MODE_CBC || $this->mode == MCRYPT_MODE_ECB)) {
$padded = $this->cryptPadText($text, $this->mode, $blockSize, $this->padding);
} else {
$padded = $text;
}
return $iv . mcrypt_encrypt($this->cipher, $encryptKey, $padded, $this->mode, $iv);
}