Phalcon\Legacy\Crypt::encrypt PHP Method

encrypt() public method

$encrypted = $crypt->encrypt("Ultra-secret text", "encrypt password");
public encrypt ( string $text, mixed $key = null ) : string
$text string
$key mixed
return string
    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);
    }

Usage Example

Example #1
0
 /**
  * Tests the padding
  *
  * @author Nikolaos Dimopoulos <*****@*****.**>
  * @since  2014-10-17
  */
 public function testCryptPadding()
 {
     $this->specify("padding not return correct results", function () {
         $texts = [''];
         $key = '0123456789ABCDEF0123456789ABCDEF';
         $modes = [MCRYPT_MODE_ECB, MCRYPT_MODE_CBC, MCRYPT_MODE_CFB];
         $pads = [Crypt::PADDING_ANSI_X_923, Crypt::PADDING_PKCS7];
         for ($i = 1; $i < 128; ++$i) {
             $texts[] = str_repeat('A', $i);
         }
         $crypt = new Crypt();
         $crypt->setCipher(MCRYPT_RIJNDAEL_256)->setKey(substr($key, 0, 16));
         foreach ($pads as $padding) {
             $crypt->setPadding($padding);
             foreach ($modes as $mode) {
                 $crypt->setMode($mode);
                 foreach ($texts as $text) {
                     $encrypted = $crypt->encrypt($text);
                     expect($crypt->decrypt($encrypted))->equals($text);
                 }
             }
         }
     });
 }