Example #1
0
 public static function decrypt($string, $key = null, $salt = null, $iv = null)
 {
     $config = ConfigManager::getConfig('Crypto', 'AES256')->AuxConfig;
     if ($key === null) {
         $key = $config->key;
     }
     if ($salt === null) {
         $salt = $config->salt;
     }
     if ($iv === null) {
         $iv = $config->iv;
     }
     $td = mcrypt_module_open('rijndael-128', '', MCRYPT_MODE_CBC, '');
     $ks = mcrypt_enc_get_key_size($td);
     $bs = mcrypt_enc_get_block_size($td);
     $iv = substr(hash("sha256", $iv), 0, $bs);
     // Create key
     $key = Crypto::pbkdf2("sha512", $key, $salt, $config->pbkdfRounds, $ks);
     // Initialize encryption module for decryption
     mcrypt_generic_init($td, $key, $iv);
     $decryptedString = "";
     // Decrypt encrypted string
     try {
         if (ctype_xdigit($string)) {
             $decryptedString = trim(mdecrypt_generic($td, pack("H*", $string)));
         }
     } catch (ErrorException $e) {
     }
     // Terminate decryption handle and close module
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     // Show string
     return $decryptedString;
 }
Example #2
0
 public function encrypt($origData)
 {
     $origData = pkcs5padding($origData, mcrypt_enc_get_block_size($this->encrypter));
     mcrypt_generic_init($this->encrypter, $this->key, substr($this->key, 0, 16));
     $ciphertext = mcrypt_generic($this->encrypter, $origData);
     mcrypt_generic_deinit($this->encrypter);
     return $ciphertext;
 }
 public static function getAuthCode($uid)
 {
     $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
     mcrypt_generic_init($td, self::$authKey, self::$authIv);
     $lose_time = time() + self::$timeLimit;
     $_authstr = $uid . '_' . $lose_time;
     $blockSize = mcrypt_enc_get_block_size($td);
     $_authstr = self::pkcs5_pad($_authstr, $blockSize);
     $encrypted = mcrypt_generic($td, $_authstr);
     $mdata = base64_encode($encrypted);
     return $mdata;
 }
 /**
  * @param string $key encryption key should be 16, 24 or 32 characters long form 128, 192, 256 bit encryption
  */
 public function __construct($key)
 {
     $this->mcryptModule = mcrypt_module_open('rijndael-256', '', 'cbc', '');
     if ($this->mcryptModule === false) {
         throw new \InvalidArgumentException("Unknown algorithm/mode.");
     }
     $keyLength = strlen($key);
     if ($keyLength > ($keyMaxLength = mcrypt_enc_get_key_size($this->mcryptModule))) {
         throw new \InvalidArgumentException("The key length must be less or equal than {$keyMaxLength}.");
     }
     if (!in_array($keyLength, array(16, 24, 32))) {
         throw new \InvalidArgumentException("Key length must be 16, 24 or 32 bytes for 128, 192, 256 bit encryption.");
     }
     $this->key = $key;
     $this->initializationVectorSize = mcrypt_enc_get_iv_size($this->mcryptModule);
     $this->blockSize = mcrypt_enc_get_block_size($this->mcryptModule);
 }
Example #5
0
 public function encrypt(string $data, string $key, bool $encode = true) : string
 {
     if (strlen($key) == 0) {
         throw new CryptException("You need to supply a password for the encryption");
     }
     $fd = mcrypt_module_open($this->mCipher, "", $this->mMode, "");
     if (is_resource($fd)) {
         $ivSize = mcrypt_enc_get_iv_size($fd);
         $keySize = mcrypt_enc_get_key_size($fd);
         $blocksize = mcrypt_enc_get_block_size($fd);
         /*
          * The chosen algorithm might not always want the IV, but we still need one for our own checks and key generation
          */
         if ($keySize <= 0) {
             throw new CryptException("Key Size is to small");
         } elseif ($ivSize <= 0) {
             $ivSize = $keySize;
         }
         if ($blocksize <= 0) {
             throw new CryptException("Invalid block size");
         }
         $iv = random_bytes($ivSize);
         $kdf = $this->kdf($key, $keySize, $iv, true);
         if ($this->mTwoStep) {
             $data = $this->sign($data, $key);
         } else {
             $data = "raw:{$data}";
         }
         $result = mcrypt_generic_init($fd, $kdf, $iv);
         if ($result !== 0) {
             throw new CryptException("Initiation error ({$result})");
         }
         $data = mcrypt_generic($fd, $this->pad($data, $blocksize));
         $data = $this->sign($data, $kdf, $iv);
         mcrypt_generic_deinit($fd);
         mcrypt_module_close($fd);
         return $this->mask($data, $key, $encode);
     } else {
         throw new Exception("Could not open the MCrypt module");
     }
     return null;
 }
Example #6
0
 /**
  * @param string    $key      base64-encoded encryption key
  * @param integer   $key_len  length of raw key in bits
  */
 public function __construct($key, $key_len = 192)
 {
     $this->_td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
     $key = self::urlsafe_b64decode($key);
     if (strlen($key) != $key_len / 8) {
         $len = strlen($key);
         $expected = $key_len / 8;
         throw new Fuze_Crypt_Exception("Incorrect key length: got {$len} bytes, expected {$expected}");
     }
     if (strlen($key) > mcrypt_enc_get_key_size($this->_td)) {
         $max = mcrypt_enc_get_key_size($this->_td);
         throw new Fuze_Crypt_Exception("Given key is longer than {$max} bytes");
     }
     $iv_size = mcrypt_enc_get_iv_size($this->_td);
     $block_size = mcrypt_enc_get_block_size($this->_td);
     if ($iv_size != self::AES_BLOCK_SIZE || $block_size != self::AES_BLOCK_SIZE) {
         throw new Fuze_Crypt_Exception('Incorrect IV or block size!');
     }
     $this->_key = $key;
 }
 function openSRS_crypt($key, $cipher = 'DES')
 {
     if (!extension_loaded('mcrypt')) {
         throw new Exception("oSRS Error - mcrypt module is not compiled into PHP");
     }
     if (!function_exists('mcrypt_module_open')) {
         throw new Exception("oSRS Error - libmcrypt version insufficient");
     }
     if (function_exists('mcrypt_generic_deinit')) {
         $this->deinit_function = 'mcrypt_generic_deinit';
     } else {
         if (function_exists('mcrypt_generic_end')) {
             $this->deinit_function = 'mcrypt_generic_end';
         } else {
             throw new Exception("oSRS Error - PHP version insufficient");
         }
     }
     srand((double) microtime() * 1000000);
     $this->header_spec = 'RandomIV';
     if (!$key) {
         throw new Exception("oSRS Error - no key specified");
     }
     $cipher = strtoupper($cipher);
     // check for cipher
     if (!isset($this->known_ciphers[$cipher])) {
         throw new Exception("oSRS Error - unknown cipher - " . $cipher);
     }
     $this->cipher = $this->known_ciphers[$cipher];
     // initialize cipher
     $this->TD = mcrypt_module_open($this->cipher, '', 'ecb', '');
     $this->blocksize = mcrypt_enc_get_block_size($this->TD);
     $this->keysize = mcrypt_enc_get_key_size($this->TD);
     // mangle key with MD5
     $this->keyhash = $this->_md5perl($key);
     while (strlen($this->keyhash) < $this->keysize) {
         $this->keyhash .= $this->_md5perl($this->keyhash);
     }
     $this->key = substr($this->keyhash, 0, $this->keysize);
     return true;
 }
 function decryptString($ciphertext)
 {
     $bs = mcrypt_enc_get_block_size($this->cipher);
     // get block size
     $iv_size = mcrypt_enc_get_iv_size($this->cipher);
     if (strlen($ciphertext) % $bs != 0) {
         // check string is proper size
         exit(1);
     }
     $iv = substr($ciphertext, 0, $iv_size);
     // retrieve IV
     $ciphertext = substr($ciphertext, $iv_size);
     mcrypt_generic_init($this->cipher, $this->key, $iv);
     $result = mdecrypt_generic($this->cipher, $ciphertext);
     // decrypt
     //echo var_dump(unpack('c*',$iv))."\n";
     $padding = ord(substr($result, -1));
     // retrieve padding
     $result = substr($result, 0, $padding * -1);
     // and remove it
     mcrypt_generic_deinit($this->cipher);
     return $result;
 }
Example #9
0
 /**
  * Decrypts an encrypted text
  *
  *<code>
  *    echo $crypt->decrypt($encrypted, "decrypt password");
  *</code>
  *
  * @param string $text
  * @param string $key
  *
  * @return string
  * @throws \ManaPHP\Security\Crypt\Exception
  */
 public function decrypt($text, $key = null)
 {
     if ($key === null) {
         $key = $this->_key;
     }
     $ivSize = mcrypt_enc_get_block_size($this->_mcrypt);
     if (strlen($text) < $ivSize * 3) {
         throw new CryptException('encrypted data is too short.');
     }
     $encryptKey = md5($key, true);
     mcrypt_generic_init($this->_mcrypt, $encryptKey, substr($text, 0, $ivSize));
     $decrypted = mdecrypt_generic($this->_mcrypt, substr($text, $ivSize));
     $length = unpack('N', $decrypted)[1];
     if ($length < 16 || 4 + $length > strlen($decrypted)) {
         throw new CryptException('decrypted data length is too short.');
     }
     $decrypted = substr($decrypted, 4, $length);
     $plainText = substr($decrypted, 0, -16);
     if (md5($plainText, true) !== substr($decrypted, -16)) {
         throw new CryptException('decrypted md5 is not valid.');
     }
     return $plainText;
 }
 public function Decrypt($strEncryptedData)
 {
     // Initialize Encryption
     $intReturnValue = mcrypt_generic_init($this->objMcryptModule, $this->strKey, $this->strIv);
     if ($intReturnValue === false || $intReturnValue < 0) {
         throw new QCryptographyException('Incorrect Parameters used in LibMcrypt Initialization');
     }
     if ($this->blnBase64) {
         $strEncryptedData = str_replace('_', '/', $strEncryptedData);
         $strEncryptedData = str_replace('-', '+', $strEncryptedData);
         $strEncryptedData = base64_decode($strEncryptedData);
     }
     $intBlockSize = mcrypt_enc_get_block_size($this->objMcryptModule);
     $strDecryptedData = mdecrypt_generic($this->objMcryptModule, $strEncryptedData);
     // Figure Out Length and Truncate
     $intPosition = strpos($strDecryptedData, '/');
     if (!$intPosition) {
         throw new QCryptographyException('Invalid Length Header in Decrypted Data');
     }
     $intLength = substr($strDecryptedData, 0, $intPosition);
     $strDecryptedData = substr($strDecryptedData, $intPosition + 1);
     $strDecryptedData = substr($strDecryptedData, 0, $intLength);
     // Deinitialize Encryption
     if (!mcrypt_generic_deinit($this->objMcryptModule)) {
         throw new QCryptographyException('Unable to deinitialize encryption buffer');
     }
     return $strDecryptedData;
 }
 /**
  * Constructor
  * $key is the key to use for encryption. $cipher can be DES, BLOWFISH or
  * BLOWFISH-COMPAT
  *
  * @param    $key        encryption key
  * @param    $cipher     which algorithm to use, defaults to DES
  *
  * @return   $return     either a PEAR error or true
  *
  * @access   public
  *
  */
 function Crypt_CBC($key, $cipher = 'DES')
 {
     if (!extension_loaded('mcrypt')) {
         return $this->raiseError('mcrypt module is not compiled into PHP', null, PEAR_ERROR_DIE, null, 'compile PHP using "--with-mcrypt"');
     }
     if (!function_exists('mcrypt_module_open')) {
         return $this->raiseError('libmcrypt version insufficient', null, PEAR_ERROR_DIE, null, 'this class requires libmcrypt >= 2.4.x, preferably >= 2.5.5');
     }
     if (function_exists('mcrypt_generic_deinit')) {
         $this->deinit_function = 'mcrypt_generic_deinit';
     } else {
         if (function_exists('mcrypt_generic_end')) {
             $this->deinit_function = 'mcrypt_generic_end';
         } else {
             return $this->raiseError('PHP version insufficient', null, PEAR_ERROR_DIE, null, 'this class requires PHP >= 4.0.2, preferably >= 4.1.1');
         }
     }
     /* seed randomizer */
     srand((double) microtime() * 1000000);
     /* initialize */
     $this->header_spec = 'RandomIV';
     /* check for key */
     if (!$key) {
         return $this->raiseError('no key specified');
     }
     /* check for cipher */
     $cipher = strtoupper($cipher);
     if (!isset($this->known_ciphers[$cipher])) {
         return $this->raiseError('unknown cipher "' . $cipher . '"');
     }
     $this->cipher = $this->known_ciphers[$cipher];
     /* initialize cipher */
     $this->TD = mcrypt_module_open($this->cipher, '', 'ecb', '');
     $this->blocksize = mcrypt_enc_get_block_size($this->TD);
     $this->keysize = mcrypt_enc_get_key_size($this->TD);
     /* mangle key with MD5 */
     $this->keyhash = $this->_md5perl($key);
     while (strlen($this->keyhash) < $this->keysize) {
         $this->keyhash .= $this->_md5perl($this->keyhash);
     }
     $this->key = substr($this->keyhash, 0, $this->keysize);
     return true;
 }
Example #12
0
 function _Decryption_Loop()
 {
     // If legacy drop to legacy function
     if ($this->job['legacy']) {
         return $this->_Legacy_Decryption_Loop();
     }
     // Grab the real block size and adjust the configured block size to ensure it is an exact divisor
     $real_blocksize = mcrypt_enc_get_block_size($this->cipher);
     $blocksize = $this->WPOnlineBackup->Get_Setting('max_block_size');
     if (($rem = $blocksize % $real_blocksize) != 0) {
         $blocksize += $real_blocksize - $rem;
     }
     // Grab total length of data - increase it to block size and calculate the amount we'll need to trim after decryption
     $len = $this->job['header']['len'];
     if (($rem = $len % $real_blocksize) != 0) {
         $len += $trim = $real_blocksize - $rem;
     } else {
         $trim = 0;
     }
     // Take off what we've already done
     $len -= $this->job['done_bytes'];
     // Decrypt loop - if we've already done the last block break out
     while ($len - $trim > 0) {
         $block = min($blocksize, $len);
         if (($data = @fread($this->file, $block)) === false) {
             return OBFW_Exception();
         }
         if (strlen($data) != $block) {
             return 'Partially read ' . strlen($data) . ' of ' . $block . ' bytes from encrypted data file for decryption.';
         }
         // Change the IV for the next block to the encrypted data of the last block we're about to decrypt
         $this->job['current_iv'] = substr($data, $block - $real_blocksize, $real_blocksize);
         $data = mdecrypt_generic($this->cipher, $data);
         if (($len -= $block) <= 0) {
             if ($trim != 0) {
                 $data = substr($data, 0, $trim * -1);
             }
         }
         $block = strlen($data);
         if (true !== ($ret = $this->stream->Write($data))) {
             return 'Write to stream failed. ' . $ret;
         }
         if ($this->hash_ctx !== false) {
             hash_update($this->hash_ctx, $data);
             $this->job['hash_len'] += $block;
         } else {
             if ($this->job['crc'] !== false) {
                 $this->job['crc'] = WPOnlineBackup_Functions::Combine_CRC32($this->job['crc'], crc32($data), $block);
             } else {
                 $this->job['crc'] = crc32($data);
             }
         }
         $this->job['done_bytes'] += $block;
         // Update the progress
         if ($this->job['done_bytes'] >= $this->job['header']['len']) {
             $this->job['progress'] = 99;
         } else {
             $this->job['progress'] = 10 + floor($this->job['done_bytes'] * 89 / $this->job['header']['len']);
             if ($this->job['progress'] > 99) {
                 $this->job['progress'] = 99;
             }
         }
         $this->bootstrap->Tick();
     }
     if ($this->hash_ctx !== false && $this->job['hash_len'] > 0) {
         list($crc) = array_values(unpack('N', hash_final($this->hash_ctx, true)));
         if ($this->job['crc'] !== false) {
             $this->job['crc'] = WPOnlineBackup_Functions::Combine_CRC32($this->job['crc'], $crc, $this->job['hash_len']);
         } else {
             $this->job['crc'] = $crc;
         }
         $this->hash_ctx = false;
     }
     if ($this->job['crc'] != $this->job['header']['crc']) {
         return false;
     }
     $this->bootstrap->Log_Event(WPONLINEBACKUP_EVENT_INFORMATION, 'File integrity check was successful.');
     // Prevent duplicated messages
     $this->bootstrap->Tick(false, true);
     return true;
 }
Example #13
0
$key = "123456789012345678901234567890123456789012345678901234567890";
$CC = "4007000000027";
$encrypted = mcrypt_ofb(MCRYPT_RIJNDAEL_128, substr($key, 0, 32), $CC, MCRYPT_ENCRYPT, substr($key, 32, 16));
$decrypted = mcrypt_ofb(MCRYPT_RIJNDAEL_128, substr($key, 0, 32), $encrypted, MCRYPT_DECRYPT, substr($key, 32, 16));
VERIFY($encrypted !== $decrypted);
VS($decrypted, $CC);
//////////////////////////////////////////////////////////////////////
VS(mcrypt_get_block_size("tripledes", "ecb"), 8);
VS(mcrypt_get_cipher_name(MCRYPT_TRIPLEDES), "3DES");
VS(mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB), 16);
VS(mcrypt_get_iv_size("des", "ecb"), 8);
VS(mcrypt_get_key_size("tripledes", "ecb"), 24);
$td = mcrypt_module_open("cast-256", "", "cfb", "");
VS(mcrypt_enc_get_algorithms_name($td), "CAST-256");
$td = mcrypt_module_open("tripledes", "", "ecb", "");
VS(mcrypt_enc_get_block_size($td), 8);
$td = mcrypt_module_open("cast-256", "", "cfb", "");
VS(mcrypt_enc_get_iv_size($td), 16);
$td = mcrypt_module_open("tripledes", "", "ecb", "");
VS(mcrypt_enc_get_key_size($td), 24);
$td = mcrypt_module_open("cast-256", "", "cfb", "");
VS(mcrypt_enc_get_modes_name($td), "CFB");
$td = mcrypt_module_open("rijndael-256", "", "ecb", "");
VS(mcrypt_enc_get_supported_key_sizes($td), array(16, 24, 32));
$td = mcrypt_module_open("tripledes", "", "ecb", "");
VS(mcrypt_enc_is_block_algorithm_mode($td), true);
$td = mcrypt_module_open("tripledes", "", "ecb", "");
VS(mcrypt_enc_is_block_algorithm($td), true);
$td = mcrypt_module_open("tripledes", "", "ecb", "");
VS(mcrypt_enc_is_block_mode($td), true);
$td = mcrypt_module_open("tripledes", "", "ecb", "");
Example #14
0
 /**
 	| @name
 	|      - logfrm_proc
 	|
 	| @params
 	|      - 
 	|
 	| @return
 	|      - 
 	|
 	| @description
 	|      - process new user profile
 	|
 	**/
 function logfrm_proc()
 {
     global $g_SYSTEM_DATA;
     $this->etc->sec_logout();
     //params
     log_message("INFO", "logfrm_proc() : start here");
     $chiphername = mcrypt_enc_get_algorithms_name($cipher);
     $blocksize = mcrypt_enc_get_block_size($cipher);
     $mykeysize = mcrypt_enc_get_supported_key_sizes($cipher);
     log_message("INFO", "logfrm_proc() : {$chiphername}/{$blocksize} bytes ");
     foreach ($mykeysize as $value) {
         log_message("INFO", "logfrm_proc() : {$value} bytes ");
     }
     unset($value);
     //sess
     $dmp = @var_export($g_SYSTEM_DATA['_SESSION'], true);
     //get chk post
     $email = trim($this->input->post('email'));
     $pass = trim($this->input->post('pass'));
     $me = @intval(trim($this->input->post('me')));
     //params
     log_message("INFO", "logfrm_proc() : info-params [ {$email} : {$pass} : {$me} ] {$dmp};");
     //cancel?
     if (!$this->input->get_post('Login')) {
         //set status
         log_message("INFO", "logfrm_proc() : info [ NOT CLICKED ]");
         //fwd
         redirect(site_url(DEFAULT_LOGGED_IN_PAGE));
         return;
     }
     //exec
     $pdata = $this->etc->sec_login($email, $pass, $me);
     $dmp = @var_export($pdata, true);
     $by = $this->etc->get_name();
     log_message("INFO", "logfrm_proc() : INFO-LOGIN [ {$dmp}  ]");
     if (!$pdata['status']) {
         //set status
         $smsg = intval($pdata['pdata']['data']->fieldtrial) >= intval($pdata['pdata']['data']->trial) ? $this->config->item('USER_LOGIN_ERROR_MAX') : $this->config->item('USER_LOGIN_ERROR');
         $this->etc->set_error_message($smsg);
         log_message("INFO", "logfrm_proc() : INFO-LOGIN-ERR [ {$smsg} ]");
         //fwd
         redirect(site_url(DEFAULT_LOGGED_IN_PAGE));
         return;
     }
     //chk if its locked ???
     if (intval($pdata['pdata']['data']->fieldtrial) >= intval($pdata['pdata']['data']->trial)) {
         //max reached
         $this->etc->set_error_message($this->config->item('USER_LOGIN_ERROR_MAX'));
         log_message("INFO", "logfrm_proc() : INFO-LOGIN-ERR [ LOCKED ]");
         //fwd
         redirect(site_url(DEFAULT_LOGGED_IN_PAGE));
         return;
     }
     //pass expired
     if (intval($pdata['pdata']['data']->expired) > 0) {
         //max reached
         $this->etc->set_error_message($this->config->item('USER_LOGIN_PASS_EXPIRED'));
         log_message("INFO", "logfrm_proc() : INFO-LOGIN-ERR [ PWD-EXPIRED ]");
         //fwd
         redirect(site_url(DEFAULT_LOGGED_IN_PAGE));
         return;
     }
     //in-active
     if (intval($pdata['pdata']['data']->flag_id) != 1) {
         //max reached
         $this->etc->set_error_message($this->config->item('USER_LOGIN_IN_ACTIVE'));
         log_message("INFO", "logfrm_proc() : INFO-LOGIN-ERR [ IN-ACTIVE ]");
         //fwd
         redirect(site_url(DEFAULT_LOGGED_IN_PAGE));
         return;
     }
     //flag_first=1, then fwd to change pass	and NOT SUPER ROOT + can_change
     if (intval($pdata['pdata']['data']->flagfirst) == 1 && intval($pdata['pdata']['data']->can_change) == 1 && intval($pdata['pdata']['data']->usertype) != DEFAULT_USERTYPE_ROOT_ID) {
         /**
         			//FLAGFIRST++ ( HOW MANY TIMES LOGGED IN)
         			$this->secuser_model->set_column_ctr(array(
         					'id'  => $pdata['pdata']['data']->user_id,
         					'by'  => $by,
         					'col' => 'FLAGFIRST',
         					'val' => sprintf("%d",1+$pdata['pdata']['data']->flagfirst)));
         			**/
         log_message("INFO", "afrm_proc() : INFO-LOGIN [ FLAGFIRST=1 ]");
         redirect(site_url('secuser/chpass'));
         return;
     }
     log_message("INFO", "afrm_proc() : login is GOOD [ goto admin ]");
     //fwd
     redirect(site_url('admin'));
     return;
 }
Example #15
0
 /**
  * Generates Encryption Header message part.
  *
  * @param string $key       Key generated from the password and salt
  * @param string $plainText Request message type data
  *
  * @return array
  * @throws Net_Growl_Exception on wrong hash/crypt algorithms usage
  */
 private function _genEncryption($key, $plainText)
 {
     static $ivVal;
     $hash_algorithm = strtolower($this->options['passwordHashAlgorithm']);
     $crypt_algorithm = strtolower($this->options['encryptionAlgorithm']);
     $crypt_mode = MCRYPT_MODE_CBC;
     $k = array_search($hash_algorithm, $this->_passwordHashAlgorithm);
     switch ($crypt_algorithm) {
         case 'aes':
             if ($k < 2) {
                 $message = "Password hash ({$hash_algorithm})" . " and encryption ({$crypt_algorithm}) algorithms" . " are not compatible." . " Please uses SHA256 or SHA512 instead.";
                 throw new Net_Growl_Exception($message);
             }
             $cipher = MCRYPT_RIJNDAEL_128;
             // Be compatible with Gfw 2, PHP Mcrypt ext. returns 32 in this case
             $key_size = 24;
             break;
         case 'des':
             $cipher = MCRYPT_DES;
             break;
         case '3des':
             if ($k < 2) {
                 $message = "Password hash ({$hash_algorithm})" . " and encryption ({$crypt_algorithm}) algorithms" . " are not compatible." . " Please uses SHA256 or SHA512 instead.";
                 throw new Net_Growl_Exception($message);
             }
             $cipher = MCRYPT_3DES;
             break;
         case 'none':
             // No encryption required
             return array('NONE', $plainText);
         default:
             // Encryption algorithm unknown
             $message = "Invalid encryption algorithm ({$crypt_algorithm})";
             throw new Net_Growl_Exception($message);
     }
     // All encryption algorithms should use
     // a block mode of CBC (Cipher Block Chaining)
     $td = mcrypt_module_open($cipher, '', $crypt_mode, '');
     $iv_size = mcrypt_enc_get_iv_size($td);
     $block_size = mcrypt_enc_get_block_size($td);
     if (!isset($key_size)) {
         $key_size = mcrypt_enc_get_key_size($td);
     }
     // Here's our 128-bit IV which is used for both 256-bit and 128-bit keys.
     if (!isset($ivVal)) {
         $ivVal = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     }
     $ivHex = bin2hex($ivVal);
     // Different encryption algorithms require different key lengths
     // and IV sizes, so use the first X bytes of the key as required.
     $key = substr($key, 0, $key_size);
     $init = mcrypt_generic_init($td, $key, $ivVal);
     if ($init != -1) {
         if ($crypt_mode == MCRYPT_MODE_CBC) {
             /**
              * Pads a string using the RSA PKCS7 padding standards
              * so that its length is a multiple of the blocksize.
              * $block_size - (strlen($text) % $block_size) bytes are added,
              * each of which is equal to
              * chr($block_size - (strlen($text) % $block_size)
              */
             $length = $this->strByteLen($plainText);
             $pad = $block_size - $length % $block_size;
             $plainText = str_pad($plainText, $length + $pad, chr($pad));
         }
         $cipherText = mcrypt_generic($td, $plainText);
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
     } else {
         $cipherText = $plainText;
     }
     return array(strtoupper("{$crypt_algorithm}:{$ivHex}"), $cipherText);
 }
Example #16
0
 /**
  * Construct mcrypt mixer
  */
 public function __construct()
 {
     $this->mcrypt = mcrypt_module_open($this->getCipher(), '', MCRYPT_MODE_ECB, '');
     $this->blockSize = mcrypt_enc_get_block_size($this->mcrypt);
     $this->initv = str_repeat(chr(0), mcrypt_enc_get_iv_size($this->mcrypt));
 }
Example #17
0
$encyprted1 = "aacef0cef8450657af223aa3e1104fe168e1389cb2c9c31b4d7e0f950b972885fb59262358f6508355346d5b7940e6b9f8ec4c270c8fc923fc069cbc0d317dfbb9bf8ae549b289ec2ff2cbd188c94beaaaac25d026dc28f7";
$encyprted2 = "aacef0cef8450657af223aa3e1104fe168e1389cb2c9c31b4d7e0f950b972885fb59262358f6508355346d5b7940e6b9f8ec4c270c8fc923fc069cbc0d317dfb";
$encyprted3 = "7ec97505b3e5fe5b7ec97505b3e5fe5b7ec97505b3e5fe5b7ec97505b3e5fe5b7ec97505b3e5fe5b7ec97505b3e5fe5b7ec97505b3e5fe5b7ec97505b3e5fe5bb9bf8ae549b289ec2ff2cbd188c94beaaaac25d026dc28f7";
$encyprted4 = "7ec97505b3e5fe5b";
// 8 byte long
if (!function_exists("hex2bin")) {
    // PHP 5.4起引入的hex2bin
    function hex2bin($data)
    {
        return pack("H*", $data);
    }
}
// ECB模式加密用不到IV,CBC模式才会用到IV
// 所以IV不管如何随机变化,ECB模式下完全不受IV变化的影响,固定明文输入,确定密文输出
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$block_size = mcrypt_enc_get_block_size($td);
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
//var_dump(bin2hex($iv));
mcrypt_generic_init($td, $key, $iv);
$encrypted_data1 = mcrypt_generic($td, $input1);
$encrypted_data2 = mcrypt_generic($td, $input2);
$encrypted_data3 = mcrypt_generic($td, $input3);
$encrypted_data4 = mcrypt_generic($td, $input4);
$plaintext1 = mdecrypt_generic($td, hex2bin($encyprted1));
$plaintext2 = mdecrypt_generic($td, hex2bin($encyprted2));
$plaintext3 = mdecrypt_generic($td, hex2bin($encyprted3));
$plaintext4 = mdecrypt_generic($td, hex2bin($encyprted4));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
print_r($block_size . "\n");
print_r(bin2hex($encrypted_data1) . "\n");
Example #18
0
 /**
  * Strip PKCS7 padding and decrypt
  * data encrypted by encrypt().
  *
  * @param string $data
  *   JSON string containing the encrypted data and meta information in the
  *   excact format as returned by encrypt().
  *
  * @return mixed
  *   Decrypted data in it's original form.
  */
 public function decrypt($data, $key)
 {
     /* Decode the JSON string */
     $data = json_decode($data, true);
     $dataStructure = array('algo' => true, 'mode' => true, 'iv' => true, 'cdata' => true, 'mac' => true);
     if ($data === NULL || $this->psl->arrayCheck($data, $dataStructure, false) !== true) {
         throw new \phpSec\Exception\GeneralSecurityException('Invalid data passed to decrypt()');
         return false;
     }
     /* Everything looks good so far. Let's continue.*/
     $td = mcrypt_module_open($data['algo'], '', $data['mode'], '');
     $block = mcrypt_enc_get_block_size($td);
     /* Using PBKDF with constant salts dedicated to each purpose 
      * can securely derivce two keys from one */
     $keySize = strlen($key);
     $key1 = $this->pbkdf2($key, "encrypt", 1, $keySize);
     $key2 = $this->pbkdf2($key, "HMAC", 1, $keySize);
     /* Check MAC. */
     if (base64_decode($data['mac']) != $this->pbkdf2($data['cdata'], $key2, 1, 32)) {
         throw new \phpSec\Exception\GeneralSecurityException('Message authentication code invalid');
         return false;
     }
     /* Init mcrypt. */
     mcrypt_generic_init($td, $key1, base64_decode($data['iv']));
     $decrypted = rtrim(mdecrypt_generic($td, base64_decode($this->stripPadding($block, $data['cdata']))));
     /* Close up. */
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     /*Return decrypted data. */
     return unserialize($decrypted);
 }
Example #19
0
 /**
  * Encrypt clear-text data using the mycrpt library. Optionally, a
  * configuration tag-id can be passed as the second parameter to specify
  * the actual encryption algorithm to be used.
  *
  * Parameters:
  * text - (string) clear text subject to be encrypted
  * cid - (int) encryption configuration to be used. @see $this->ciphers
  */
 function encrypt($text, $cid = 0)
 {
     if (!$this->exists() || !$text || !($cipher = $this->getCipher($cid)) || !$cipher['cid']) {
         return false;
     }
     if (!($td = mcrypt_module_open($cipher['name'], '', $cipher['mode'], ''))) {
         return false;
     }
     $keysize = mcrypt_enc_get_key_size($td);
     $ivsize = mcrypt_enc_get_iv_size($td);
     $iv = Crypto::random($ivsize);
     //Add padding
     $blocksize = mcrypt_enc_get_block_size($td);
     $pad = $blocksize - strlen($text) % $blocksize;
     $text .= str_repeat(chr($pad), $pad);
     // Do the encryption.
     mcrypt_generic_init($td, $this->getKeyHash($iv, $ivsize), $iv);
     $ciphertext = $iv . mcrypt_generic($td, $text);
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     return sprintf('$%s$%s', $cipher['cid'], $ciphertext);
 }
    function Open(&$disk, $cipher_spec, $key, $extra = 0, $rjct_intention = false)
    {
        // ASSERTION - The file is closed
        // First thing first, check we actually have encryption available... If not, server configuration has changed
        if (!$this->WPOnlineBackup->Get_Env('encryption_available') || !array_key_exists($cipher_spec, $this->WPOnlineBackup->Get_Env('encryption_types'))) {
            return __('The selected encryption type is no longer available on the server. The server configuration must have changed since encryption was configured. Please change the encryption details and run the backup again. If this was an online backup you may need to contact your host about this as your encryption details cannot be changed.', 'wponlinebackup');
        }
        // Store the cipher specification and key
        $this->cipher_spec = $cipher_spec;
        $this->key = $key;
        // Store the file handle
        $this->disk =& $disk;
        // Attempt to open the cipher module
        list($module, $module_str, $key_size) = $this->Get_Cipher($this->cipher_spec);
        if (($this->cipher = @mcrypt_module_open($module, '', MCRYPT_MODE_CBC, '')) === false) {
            return 'Failed to open encryption module. PHP: ' . OBFW_Exception();
        }
        // Get the IV size
        $iv_size = mcrypt_enc_get_iv_size($this->cipher);
        // Randomly generate an IV - the IV will be stored in the file
        $this->iv = '';
        mt_srand(time());
        for ($i = 0; $i < $iv_size; $i++) {
            $this->iv .= chr(rand(0, 255));
        }
        // Generate the encryption key and password authentication value - allow $extra parameter to use a different section of the key
        $dk = WPOnlineBackup_Functions::PBKDF2($this->key, $this->iv, 1148, $key_size * (2 + $extra) + 2);
        $this->key = substr($dk, $extra ? $key_size * (1 + $extra) + 2 : 0, $key_size);
        $pass_auth = substr($dk, $key_size * 2, 2);
        // Now initialise the cipher so we can start encrypting. Returns -2/-3 on errors, false on incorrect parameters
        if (($ret = @mcrypt_generic_init($this->cipher, $this->key, $this->iv)) === false || $ret < 0) {
            $e = 'Failed to initialise encryption. PHP: ' . OBFW_Exception();
            @mcrypt_module_close($this->cipher);
            return $e;
        }
        // Is the caller intending to write a rejection header through this writer?
        // If so, we'll have to write our own since the one we get given will be encrypted and mangled
        if ($rjct_intention) {
            // We don't need to store this, the disk itself will keep track of positioning, much like it will with our header
            // Decryption is not an issue since it will search for the OBFWEN descriptor in the first 1024 bytes
            $header = <<<HEADER
<?php
/*Rejection header*/
__halt_compiler();
}
HEADER;
            if (($ret = $this->disk->Write($header)) !== true) {
                @mcrypt_generic_deinit($this->cipher);
                @mcrypt_module_close($this->cipher);
                return $ret;
            }
        }
        // This must be called AFTER we write rejection header otherwise we'll fail to adjust the header during Close()
        $this->header_pos = $this->disk->Pos();
        // Write the file header
        // We used to encrypt the header but we don't any more so we can get the actual backup file size without needing the key
        // We'll set an unencrypted size of 0 and fill it in as we close
        $fields = array(array('a6', 'OBFWEN'), array('v', 3), array('v', 0), array('C', ord($pass_auth[0])), array('C', ord($pass_auth[1])), array('V', $iv_size), array('V', 0), array('V', 0), array('V', 0));
        $fields = WPOnlineBackup_Functions::Pack_Fields($fields) . $this->iv;
        if (($ret = $this->disk->Write($fields)) !== true) {
            @mcrypt_generic_deinit($this->cipher);
            @mcrypt_module_close($this->cipher);
            return $ret;
        }
        // Grab the real block size and adjust the configured block size to ensure it is an exact divisor
        $this->real_blocksize = mcrypt_enc_get_block_size($this->cipher);
        if (($rem = $this->WPOnlineBackup->Get_Setting('encryption_block_size') % $this->real_blocksize) != 0) {
            $this->blocksize = $this->WPOnlineBackup->Get_Setting('encryption_block_size') + ($this->real_blocksize - $rem);
        } else {
            $this->blocksize = $this->WPOnlineBackup->Get_Setting('encryption_block_size');
        }
        // Prepare the counters
        $this->data = '';
        $this->data_len = 0;
        if ($this->WPOnlineBackup->Get_Env('inc_hash_available')) {
            $this->hash_ctx = hash_init('crc32b');
        } else {
            $this->hash_ctx = false;
        }
        $this->hash_len = 0;
        $this->crc = false;
        $this->last_cipher = null;
        $this->totalsize = 0;
        $this->encsize = strlen($fields);
        $this->volatile = false;
        $this->volatile_len = 0;
        $this->buffer_disk = false;
        // Open() called so set status
        $this->status = 1;
        return true;
    }
Example #21
0
 /**
  * Encrypts the given data (string) using the mcrypt-extension
  *
  * @param string $data
  * @return string
  */
 private function encryptMcrypt($data)
 {
     $td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
     // if IV has been defined, don't generate a new one
     if (!$this->iv) {
         $this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     }
     mcrypt_generic_init($td, $this->key, $this->iv);
     if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
         $bs = mcrypt_enc_get_block_size($td);
         switch ($this->cryptParams['padding']) {
             case 'pkcs7':
                 $datalen = strlen($data);
                 $rem = $bs - $datalen % $bs;
                 $data .= str_repeat(chr($rem), $rem);
                 break;
             case 'iso10126':
                 for ($datalen0 = $datalen = strlen($data); $datalen % $bs != $bs - 1; $datalen++) {
                     $data .= chr(mt_rand(1, 127));
                 }
                 $data .= chr($datalen - $datalen0 + 1);
                 break;
             default:
                 throw new Exception("Unsupported or invalid block padding scheme {$this->cryptParams['padding']}");
         }
     }
     $encrypted_data = $this->iv . mcrypt_generic($td, $data);
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     return $encrypted_data;
 }
<?php

$td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
var_dump(mcrypt_enc_get_block_size($td));
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
var_dump(mcrypt_enc_get_block_size($td));
$td = mcrypt_module_open(MCRYPT_WAKE, '', MCRYPT_MODE_STREAM, '');
var_dump(mcrypt_enc_get_block_size($td));
Example #23
0
 /**
  * Encode data into a single string
  *
  * @param    string  $data
  * @return   string
  */
 public function encode($plain_text, $key = null)
 {
     $cipher = $this->getCipher();
     if ($cipher == false) {
         return false;
     }
     if ($key == null) {
         $sdk = GiveItSdk::getInstance();
         $key = $sdk->data_key;
     }
     if ($key == null) {
         $this->addError('missing key for encryption');
         return false;
     }
     $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher, MCRYPT_MODE_CBC), MCRYPT_RAND);
     $td = mcrypt_module_open($cipher, '', MCRYPT_MODE_CBC, '');
     mcrypt_generic_init($td, $key, $iv);
     $text = $this->pkcs5Pad($plain_text, mcrypt_enc_get_block_size($td));
     // manually pad the data since mcrypt doesn't do this properly
     $encrypted = mcrypt_generic($td, $text);
     $crypt = base64_encode($iv . $encrypted);
     $crypt = urlencode($crypt);
     if ($this->debug) {
         echo "\n---- cipher ---\n" . $this->cipher;
         echo "\n---- text  ----\n" . $text;
         echo "\n---- crypt ----\n" . $crypt;
         echo "\n---------------\n";
     }
     return $crypt;
 }
Example #24
0
/**
 * Encrypt database password
 *
 * @throws EasySCP_Exception
 * @param string $db_pass Database password
 * @return string Encrypted database password
 * @todo Remove error operator
 */
function encrypt_db_password($db_pass)
{
    if (extension_loaded('mcrypt')) {
        $td = @mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
        $key = EasySCP_Registry::get('MCRYPT_KEY');
        $iv = EasySCP_Registry::get('MCRYPT_IV');
        // compatibility with used perl pads
        $block_size = @mcrypt_enc_get_block_size($td);
        $strlen = strlen($db_pass);
        $pads = $block_size - $strlen % $block_size;
        $db_pass .= str_repeat(' ', $pads);
        // Initialize encryption
        @mcrypt_generic_init($td, $key, $iv);
        // Encrypt string
        $encrypted = @mcrypt_generic($td, $db_pass);
        @mcrypt_generic_deinit($td);
        @mcrypt_module_close($td);
        $text = @base64_encode("{$encrypted}");
        // Show encrypted string
        return trim($text);
    } else {
        throw new EasySCP_Exception(tr("ERROR: PHP extension 'mcrypt' not loaded!"));
    }
}
Example #25
0
 private function encryptMcrypt($data)
 {
     $td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
     $this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     mcrypt_generic_init($td, $this->key, $this->iv);
     if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
         $bs = mcrypt_enc_get_block_size($td);
         for ($datalen0 = $datalen = strlen($data); $datalen % $bs != $bs - 1; $datalen++) {
             $data .= chr(mt_rand(1, 127));
         }
         $data .= chr($datalen - $datalen0 + 1);
     }
     $encrypted_data = $this->iv . mcrypt_generic($td, $data);
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     return $encrypted_data;
 }
 /**
  * Encrypt via MCrypt
  *
  * @param	string	$data	Input data
  * @param	array	$params	Input parameters
  * @return	string
  */
 protected function _mcrypt_encrypt($data, $params)
 {
     if (!is_resource($params['handle'])) {
         return FALSE;
     } elseif (!isset($params['iv'])) {
         // The greater-than-1 comparison is mostly a work-around for a bug,
         // where 1 is returned for ARCFour instead of 0.
         $params['iv'] = ($iv_size = mcrypt_enc_get_iv_size($params['handle'])) > 1 ? mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM) : NULL;
     }
     // CAST-128 compatibility (http://tools.ietf.org/rfc/rfc2144.txt)
     //
     // RFC2144 says that keys shorter than 16 bytes are to be padded with
     // zero bytes to 16 bytes, but (surprise) MCrypt doesn't do that.
     if ($params['cipher'] === 'cast-128' && ($kl = strlen($params['key'])) < 16) {
         $params['key'] .= str_repeat("", 16 - $kl);
     }
     if (mcrypt_generic_init($params['handle'], $params['key'], $params['iv']) < 0) {
         if ($params['handle'] !== $this->_handle) {
             mcrypt_module_close($params['handle']);
         }
         return FALSE;
     }
     // Use PKCS#7 padding in order to ensure compatibility with OpenSSL
     // and other implementations outside of PHP.
     if (in_array(strtolower(mcrypt_enc_get_modes_name($params['handle'])), array('cbc', 'ecb'), TRUE)) {
         $block_size = mcrypt_enc_get_block_size($params['handle']);
         $pad = $block_size - strlen($data) % $block_size;
         $data .= str_repeat(chr($pad), $pad);
     }
     // Work-around for yet another strange behavior in MCrypt.
     //
     // When encrypting in ECB mode, the IV is ignored. Yet
     // mcrypt_enc_get_iv_size() returns a value larger than 0
     // even if ECB is used AND mcrypt_generic_init() complains
     // if you don't pass an IV with length equal to the said
     // return value.
     //
     // This probably would've been fine (even though still wasteful),
     // but OpenSSL isn't that dumb and we need to make the process
     // portable, so ...
     $data = mcrypt_enc_get_modes_name($params['handle']) !== 'ECB' ? $params['iv'] . mcrypt_generic($params['handle'], $data) : mcrypt_generic($params['handle'], $data);
     mcrypt_generic_deinit($params['handle']);
     if ($params['handle'] !== $this->_handle) {
         mcrypt_module_close($params['handle']);
     }
     return $data;
 }
Example #27
0
 private static function PlainDecrypt($ciphertext, $key, $iv)
 {
     self::EnsureFunctionExists("mcrypt_module_open");
     $crypt = mcrypt_module_open(self::CIPHER, "", self::CIPHER_MODE, "");
     if ($crypt === FALSE) {
         throw new CannotPerformOperationException();
     }
     self::EnsureFunctionExists("mcrypt_enc_get_block_size");
     $block = mcrypt_enc_get_block_size($crypt);
     self::EnsureFunctionExists("mcrypt_generic_init");
     $ret = mcrypt_generic_init($crypt, $key, $iv);
     if ($ret !== 0) {
         throw new CannotPerformOperationException();
     }
     self::EnsureFunctionExists("mdecrypt_generic");
     $plaintext = mdecrypt_generic($crypt, $ciphertext);
     self::EnsureFunctionExists("mcrypt_generic_deinit");
     $ret = mcrypt_generic_deinit($crypt);
     if ($ret !== TRUE) {
         throw new CannotPerformOperationException();
     }
     self::EnsureFunctionExists("mcrypt_module_close");
     $ret = mcrypt_module_close($crypt);
     if ($ret !== TRUE) {
         throw new CannotPerformOperationException();
     }
     // Remove the padding.
     $pad = ord($plaintext[self::our_strlen($plaintext) - 1]);
     if ($pad <= 0 || $pad > $block) {
         throw new CannotPerformOperationException();
     }
     $plaintext = self::our_substr($plaintext, 0, self::our_strlen($plaintext) - $pad);
     if ($plaintext === FALSE) {
         throw new CannotPerformOperationException();
     }
     return $plaintext;
 }
 /**
  * Strip PKCS7 padding and decrypt
  * data encrypted by encrypt().
  *
  * @param string $data
  *   JSON string containing the encrypted data and meta information in the
  *   excact format as returned by encrypt().
  *
  * @return mixed
  *   Decrypted data in it's original form.
  */
 public static function decrypt($data, $key)
 {
     /* Decode the JSON string */
     $data = json_decode($data, true);
     $dataStructure = array('algo' => true, 'mode' => true, 'iv' => true, 'cdata' => true, 'mac' => true);
     if ($data === null || phpsec::arrayCheck($data, $dataStructure) !== true) {
         phpsec::error('Invalid data passed to decrypt()');
         return false;
     }
     /* Everything looks good so far. Let's continue.*/
     $td = mcrypt_module_open($data['algo'], '', $data['mode'], '');
     $block = mcrypt_enc_get_block_size($td);
     /* Check MAC. */
     if (base64_decode($data['mac']) != self::pbkdf2($data['cdata'], $key, 1000, 32)) {
         phpsec::error('Message authentication code invalid');
         return false;
     }
     /* Init mcrypt. */
     mcrypt_generic_init($td, $key, base64_decode($data['iv']));
     $decrypted = rtrim(mdecrypt_generic($td, base64_decode(self::stripPadding($block, $data['cdata']))));
     /* Close up. */
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     /*Return decrypted data. */
     return unserialize($decrypted);
 }
 /**
  * Encrypt via MCrypt
  *
  * @param	string	$data	Input data
  * @param	array	$params	Input parameters
  * @return	string
  */
 protected function _mcrypt_encrypt($data, $params)
 {
     if (!is_resource($params['handle'])) {
         return FALSE;
     }
     // The greater-than-1 comparison is mostly a work-around for a bug,
     // where 1 is returned for ARCFour instead of 0.
     $iv = ($iv_size = mcrypt_enc_get_iv_size($params['handle'])) > 1 ? mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM) : NULL;
     if (mcrypt_generic_init($params['handle'], $params['key'], $iv) < 0) {
         if ($params['handle'] !== $this->_handle) {
             mcrypt_module_close($params['handle']);
         }
         return FALSE;
     }
     // Use PKCS#7 padding in order to ensure compatibility with OpenSSL
     // and other implementations outside of PHP.
     if (in_array(strtolower(mcrypt_enc_get_modes_name($params['handle'])), array('cbc', 'ecb'), TRUE)) {
         $block_size = mcrypt_enc_get_block_size($params['handle']);
         $pad = $block_size - self::strlen($data) % $block_size;
         $data .= str_repeat(chr($pad), $pad);
     }
     // Work-around for yet another strange behavior in MCrypt.
     //
     // When encrypting in ECB mode, the IV is ignored. Yet
     // mcrypt_enc_get_iv_size() returns a value larger than 0
     // even if ECB is used AND mcrypt_generic_init() complains
     // if you don't pass an IV with length equal to the said
     // return value.
     //
     // This probably would've been fine (even though still wasteful),
     // but OpenSSL isn't that dumb and we need to make the process
     // portable, so ...
     $data = mcrypt_enc_get_modes_name($params['handle']) !== 'ECB' ? $iv . mcrypt_generic($params['handle'], $data) : mcrypt_generic($params['handle'], $data);
     mcrypt_generic_deinit($params['handle']);
     if ($params['handle'] !== $this->_handle) {
         mcrypt_module_close($params['handle']);
     }
     return $data;
 }
 /**
  * Adds a padding to the given data (PKCS #7).
  * @param string $data the data to pad
  * @return string the padded data
  */
 protected function addPadding($data)
 {
     $module = $this->getCryptModule();
     $blockSize = mcrypt_enc_get_block_size($module);
     $pad = $blockSize - StringHelper::byteLength($data) % $blockSize;
     return $data . str_repeat(chr($pad), $pad);
 }