Back to OpenSSL class

Method encrypt

public string
encrypt
(mixed $plainText, mixed $key, mixed $iv = null)
Encrypts a string. Returns the raw binary ciphertext.
Parameters
  • string $plainText The plaintext to encrypt
  • string $key The raw binary key (will be zero-padded or chopped if its size is different than the block size)
  • null|string $iv The initialization vector (for CBC mode algorithms)
Returns
  • string The raw encrypted binary string.
Class: OpenSSL
Project: Joomla

Method encrypt - Source code

/**
 * Encrypts a string. Returns the raw binary ciphertext.
 *
 * WARNING: The plaintext is zero-padded to the algorithm's block size. You are advised to store the size of the
 * plaintext and trim the string to that length upon decryption.
 *
 * @param   string       $plainText  The plaintext to encrypt
 * @param   string       $key        The raw binary key (will be zero-padded or chopped if its size is different than the block size)
 * @param   null|string  $iv         The initialization vector (for CBC mode algorithms)
 *
 * @return  string  The raw encrypted binary string.
 */
public function encrypt($plainText, $key, $iv = null)
{
    $iv_size = $this->getBlockSize();
    $key = $this->resizeKey($key, $iv_size);
    $iv = $this->resizeKey($iv, $iv_size);
    if (empty($iv)) {
        $randVal = new Randval();
        $iv = $randVal->generate($iv_size);
    }
    $plainText .= $this->getZeroPadding($plainText, $iv_size);
    $cipherText = openssl_encrypt($plainText, $this->method, $key, $this->openSSLOptions, $iv);
    $cipherText = $iv . $cipherText;
    return $cipherText;
}