/** * @inheritdoc */ public function setCipher($cipher) { if (!in_array($cipher, openssl_get_cipher_methods())) { throw new EncryptionException("Invalid cipher \"{$cipher}\""); } $this->cipher = $cipher; }
public function setEncryptionMode($mode = 'cbc', $strength = 128) { static $availableAlgorithms = null; static $defaultAlgo = 'aes-128-cbc'; if (!is_array($availableAlgorithms)) { $availableAlgorithms = openssl_get_cipher_methods(); foreach (array('aes-256-cbc', 'aes-256-ecb', 'aes-192-cbc', 'aes-192-ecb', 'aes-128-cbc', 'aes-128-ecb') as $algo) { if (in_array($algo, $availableAlgorithms)) { $defaultAlgo = $algo; break; } } } $strength = (int) $strength; $mode = strtolower($mode); if (!in_array($strength, array(128, 192, 256))) { $strength = 256; } if (!in_array($mode, array('cbc', 'ebc'))) { $mode = 'cbc'; } $algo = 'aes-' . $strength . '-' . $mode; if (!in_array($algo, $availableAlgorithms)) { $algo = $defaultAlgo; } $this->method = $algo; }
public function testSetAlgorithm() { $algos = openssl_get_cipher_methods(true); $algo = $algos[array_rand($algos)]; $this->crypt->setAlgorithm($algo); $this->assertEquals($algo, $this->crypt->getAlgorithm()); }
public function testSupportedCiphersList() { $supported = $this->defaultCipher->getSupportedCiphers(); $this->assertInternalType('array', $supported); $cipherMethods = openssl_get_cipher_methods(); foreach ($supported as $method) { $this->assertTrue(in_array($method, $cipherMethods)); } }
public function __construct(array $options = []) { if (!empty($options)) { $this->config = $options; } if (!\in_array($this->config['cipher'] . '-ctr', \openssl_get_cipher_methods())) { throw new Error('Cipher ' . $this->config['cipher'] . '-ctr' . ' not found!'); } }
/** * EncryptedPrivateKey constructor. * @param PrivateKeyInterface $key * @param string $method * @param string $iv */ public function __construct(PrivateKeyInterface $key, $method, $iv) { $methods = openssl_get_cipher_methods(); if (!in_array($method, array_values($methods))) { throw new \RuntimeException('Unknown cipher method'); } $this->key = $key; $this->method = $method; $this->iv = $iv; }
/** * Encrypt the data * * @param string $data Data string to encrypt * @param string $key Encryption key * @param string $mode Default mode (openssl or mcrypt) * * @return string Encrypted data string. */ public function encrypt($data, $key, $mode = 'openssl') { if ($mode == 'openssl' && extension_loaded('openssl') && in_array('aes-256-cbc', openssl_get_cipher_methods())) { return $this->encryptOpenSsl($data, $key); } if ($mode != 'raw' && function_exists('mcrypt_create_iv') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) !== false) { return $this->encryptMcrypt($data, $key); } throw new EncException('Either "openssl" PHP extension with "aes-256-cbc" cypher' . ' or "mcrypt" PHP extension with "MCRYPT_RIJNDAEL_128" cypher is required for AES encryption'); }
public function __construct(string $cipher = null, string $hash = null, string $mode = null, bool $twoStep = false) { parent::__construct($cipher, $hash, $mode, $twoStep); $this->mCipher = $cipher ?? "AES-256"; $this->mMode = $mode ?? "CBC"; if (!function_exists("openssl_get_cipher_methods")) { throw new Exception("Could not find the OpenSSL module"); } elseif (!in_array(strtoupper($this->mCipher . "-" . $this->mMode), openssl_get_cipher_methods())) { throw new Exception("The cipher '" . strtoupper($this->mCipher . "-" . $this->mMode) . "' is not supported by this platform installation"); } }
/** * Select which method we will use for our crypto stuff * * @return string The selected method that is available */ private function getMethod() { $availableMethods = openssl_get_cipher_methods(); if (in_array('AES-256-CBC-HMAC-SHA256', $availableMethods)) { return 'AES-256-CBC-HMAC-SHA256'; } elseif (in_array('AES-256-CBC', $availableMethods)) { return 'AES-256-CBC'; } // just take the first one coming, it's better than nothing return $availableMethods[0]; }
public function __construct($password, $method = null) { $this->_password = $password; if ($method) { $methods = openssl_get_cipher_methods(true); if (!in_array($method, $methods)) { throw new \LogicException('Unknown cipher algorithm'); } $this->_method = $method; } }
/** * EncryptedSubjectIdentifier constructor. * * @param string $pairwise_encryption_key * @param string $algorithm * @param null|string $iv * @param string $salt */ public function __construct($pairwise_encryption_key, $algorithm, $iv, $salt) { Assertion::nullOrString($iv); Assertion::string($salt); Assertion::string($pairwise_encryption_key); Assertion::string($algorithm); Assertion::inArray($algorithm, openssl_get_cipher_methods(), sprintf('The algorithm "%s" is not supported.', $algorithm)); $this->pairwise_encryption_key = $pairwise_encryption_key; $this->algorithm = $algorithm; $this->salt = $salt; $this->iv = $iv; }
public function getSupportedAlgs() { $ciphers = openssl_get_cipher_methods(); $hashes = hash_algos(); $results = array(); foreach (self::$alg_params as $alg => $param) { if (in_array($param['cipher'], $ciphers) && in_array($param['hash'], $hashes)) { $results[] = $alg; } } return $results; }
/** * Get cipher method and verify that it's supported. * * @throws \RuntimeException * @return string */ protected final function _getCipherMethod() { static $supported_ciphers; if (!isset($supported_ciphers)) { $supported_ciphers = array_flip(openssl_get_cipher_methods()); } $method = $this->_cipherMethod(); if (!isset($supported_ciphers[$method])) { throw new \RuntimeException("Cipher method {$method} is not" . " supported by this version of OpenSSL."); } return $method; }
private function setMethod() { // select the right method $this->availableMethods = openssl_get_cipher_methods(); if (in_array('AES-256-CBC-HMAC-SHA256', $this->availableMethods)) { $this->method = 'AES-256-CBC-HMAC-SHA256'; } elseif (in_array('AES-256-CBC', $this->availableMethods)) { $this->method = 'AES-256-CBC'; } else { // just take the first one coming, I guess it's better than nothing. $this->method = $this->availableMethods[0]; } }
/** * checks if the encryption and hash methods are supported * @param $enc the encryption method. * @param $hash the hash method. * @throw Exception in case a method is not supported. */ private static function check_methods($enc, $hash) { if (!function_exists('openssl_encrypt')) { throw new Exception('openssl_encrypt() not supported.'); } else { if (!in_array($enc, openssl_get_cipher_methods())) { throw new Exception('Encryption method ' . $enc . ' not supported.'); } else { if (!in_array(strtolower($hash), hash_algos())) { throw new Exception('Hashing method ' . $hash . ' not supported.'); } } } }
public function __construct($config_array) { $expected_keys = array("cipher_method", "block_byte_size", "key_byte_size", "salt_byte_size", "mac_byte_size", "hash_function_name", "encryption_info_string", "authentication_info_string"); if (sort($expected_keys) !== true) { throw Ex\CannotPerformOperationException("sort() failed."); } $actual_keys = array_keys($config_array); if (sort($actual_keys) !== true) { throw Ex\CannotPerformOperationException("sort() failed."); } if ($expected_keys !== $actual_keys) { throw new Ex\CannotPerformOperationException("Trying to instantiate a bad configuration."); } $this->cipher_method = $config_array["cipher_method"]; $this->block_byte_size = $config_array["block_byte_size"]; $this->key_byte_size = $config_array["key_byte_size"]; $this->salt_byte_size = $config_array["salt_byte_size"]; $this->mac_byte_size = $config_array["mac_byte_size"]; $this->hash_function_name = $config_array["hash_function_name"]; $this->encryption_info_string = $config_array["encryption_info_string"]; $this->authentication_info_string = $config_array["authentication_info_string"]; Core::ensureFunctionExists('openssl_get_cipher_methods'); if (\in_array($this->cipher_method, \openssl_get_cipher_methods()) === false) { throw new Ex\CannotPerformOperationException("Configuration contains an invalid OpenSSL cipher method."); } if (!\is_int($this->block_byte_size) || $this->block_byte_size <= 0) { throw new Ex\CannotPerformOperationException("Configuration contains an invalid block byte size."); } if (!\is_int($this->key_byte_size) || $this->key_byte_size <= 0) { throw new Ex\CannotPerformOperationException("Configuration contains an invalid key byte size."); } if ($this->salt_byte_size !== false) { if (!is_int($this->salt_byte_size) || $this->salt_byte_size <= 0) { throw new Ex\CannotPerformOperationException("Configuration contains an invalid salt byte size."); } } if (!\is_int($this->mac_byte_size) || $this->mac_byte_size <= 0) { throw new Ex\CannotPerformOperationException("Configuration contains an invalid MAC byte size."); } if (\in_array($this->hash_function_name, \hash_algos()) === false) { throw new Ex\CannotPerformOperationException("Configuration contains an invalid hash function name."); } if (!\is_string($this->encryption_info_string) || $this->encryption_info_string === "") { throw new Ex\CannotPerformOperationException("Configuration contains an invalid encryption info string."); } if (!\is_string($this->authentication_info_string) || $this->authentication_info_string === "") { throw new Ex\CannotPerformOperationException("Configuration contains an invalid authentication info string."); } }
/** * Cipher constructor. * @param string $cipherMethod * @throws CipherException */ public function __construct(string $cipherMethod = "aes-256-cbc") { // Check requirements if (!extension_loaded("openssl") || !function_exists("hash")) { throw CipherException::initError(); } // Cipher Method if (!in_array($cipherMethod, openssl_get_cipher_methods())) { throw CipherException::badCipherMethod($cipherMethod); } // Bootstrap $this->cipherMethod = $cipherMethod; $this->defaultSecret = $this->validateKey(self::createKey("comely", 1), __METHOD__); $this->defaultHashAlgo = $this->defaultHashAlgo("sha1"); $this->ivSize = openssl_cipher_iv_length($this->cipherMethod); }
/** * Runs the runtime tests. * * @throws Ex\EnvironmentIsBrokenException */ public static function runtimeTest() { // 0: Tests haven't been run yet. // 1: Tests have passed. // 2: Tests are running right now. // 3: Tests have failed. static $test_state = 0; if ($test_state === 1 || $test_state === 2) { return; } if ($test_state === 3) { /* If an intermittent problem caused a test to fail previously, we * want that to be indicated to the user with every call to this * library. This way, if the user first does something they really * don't care about, and just ignores all exceptions, they won't get * screwed when they then start to use the library for something * they do care about. */ throw new Ex\EnvironmentIsBrokenException('Tests failed previously.'); } try { $test_state = 2; Core::ensureFunctionExists('openssl_get_cipher_methods'); if (\in_array(Core::CIPHER_METHOD, \openssl_get_cipher_methods()) === false) { throw new Ex\EnvironmentIsBrokenException('Cipher method not supported. This is normally caused by an outdated ' . 'version of OpenSSL (and/or OpenSSL compiled for FIPS compliance). ' . 'Please upgrade to a newer version of OpenSSL that supports ' . Core::CIPHER_METHOD . ' to use this library.'); } RuntimeTests::AESTestVector(); RuntimeTests::HMACTestVector(); RuntimeTests::HKDFTestVector(); RuntimeTests::testEncryptDecrypt(); if (Core::ourStrlen(Key::createNewRandomKey()->getRawBytes()) != Core::KEY_BYTE_SIZE) { throw new Ex\EnvironmentIsBrokenException(); } if (Core::ENCRYPTION_INFO_STRING == Core::AUTHENTICATION_INFO_STRING) { throw new Ex\EnvironmentIsBrokenException(); } } catch (Ex\EnvironmentIsBrokenException $ex) { // Do this, otherwise it will stay in the "tests are running" state. $test_state = 3; throw $ex; } // Change this to '0' make the tests always re-run (for benchmarking). $test_state = 1; }
/** * @param string $string * @return array */ public function parseDekInfo($string) { $dek = explode(",", $string); if (count($dek) !== 2) { throw new \RuntimeException('Malformed DEK-Info'); } $cipher = $dek[0]; $iv = $dek[1]; if (!in_array($cipher, openssl_get_cipher_methods())) { throw new \RuntimeException('Unknown cipher method'); } if (strlen($iv) / 2 !== openssl_cipher_iv_length($cipher)) { throw new \RuntimeException('Bad IV length'); } if (!ctype_xdigit($iv)) { throw new \RuntimeException('Bad IV'); } $iv = pack("H*", $iv); return [$cipher, $iv]; }
/** * Decrypts a string encoded with mcrypt.<br /> * If mcrypt is not available, decrypts with xor * * @param string $text The text to decode * @param string $key [optionnal] The key to use. Default is the application key * @return string The decrypted string */ public static function decrypt($text, $key = null) { // Get the application key if no key is given if ($key === null) { $key = self::_getKey(); } // Use openssl_decrypt with PHP >= 5.3.0 if (Config::get('general.crypt_method', 'openssl') === 'openssl' && function_exists('openssl_decrypt') && in_array('BF-ECB', openssl_get_cipher_methods())) { $method = 'BF-ECB'; $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method)); $msg = openssl_decrypt(strtr($text, '-_', '+/'), 'BF-ECB', $key); } else { if (function_exists('mcrypt_encrypt')) { $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($size, MCRYPT_RAND); $text = base64_decode(str_pad(strtr($text, '-_', '+/'), strlen($text) % 4, '=', STR_PAD_RIGHT)); $msg = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv), ""); } else { // ... else decrypt with xor technique $n = mb_strlen($text, '8bit'); $m = mb_strlen($key, '8bit'); if ($n !== $m) { $key = mb_substr(str_repeat($key, ceil($n / $m)), 0, $n, '8bit'); } $msg = base64_decode($text) ^ $key; } } // If zlib is active we uncompress the crypted value if (function_exists('gzinflate')) { $msg = @gzinflate($msg); } // To avoid truncated encoded strings @(list($hash, $value) = explode('~~~', $msg)); if (self::check($value, $hash)) { return $value; } return false; }
public static function Decrypt($ciphertext, $key) { self::RuntimeTest(); $method = self::CIPHER . '-' . self::CIPHER_MODE; self::EnsureFunctionExists('openssl_get_cipher_methods'); if (in_array($method, openssl_get_cipher_methods()) === FALSE) { throw new CannotPerformOperationException("Cipher method not supported."); } // Extract the HMAC from the front of the ciphertext. if (self::our_strlen($ciphertext) <= self::MAC_BYTE_SIZE) { throw new InvalidCiphertextException(); } $hmac = self::our_substr($ciphertext, 0, self::MAC_BYTE_SIZE); if ($hmac === FALSE) { throw new CannotPerformOperationException(); } $ciphertext = self::our_substr($ciphertext, self::MAC_BYTE_SIZE); if ($ciphertext === FALSE) { throw new CannotPerformOperationException(); } // Regenerate the same authentication sub-key. $akey = self::HKDF(self::HASH_FUNCTION, $key, self::KEY_BYTE_SIZE, self::AUTHENTICATION_INFO); if (self::VerifyHMAC($hmac, $ciphertext, $akey)) { // Regenerate the same encryption sub-key. $keysize = self::KEY_BYTE_SIZE; $ekey = self::HKDF(self::HASH_FUNCTION, $key, $keysize, self::ENCRYPTION_INFO); // Extract the initialization vector from the ciphertext. self::EnsureFunctionExists("openssl_cipher_iv_length"); $ivsize = openssl_cipher_iv_length($method); if ($ivsize === FALSE || $ivsize <= 0) { throw new CannotPerformOperationException(); } if (self::our_strlen($ciphertext) <= $ivsize) { throw new InvalidCiphertextException(); } $iv = self::our_substr($ciphertext, 0, $ivsize); if ($iv === FALSE) { throw new CannotPerformOperationException(); } $ciphertext = self::our_substr($ciphertext, $ivsize); if ($ciphertext === FALSE) { throw new CannotPerformOperationException(); } $plaintext = self::PlainDecrypt($ciphertext, $ekey, $iv); return $plaintext; } else { /* * We throw an exception instead of returning FALSE because we want * a script that doesn't handle this condition to CRASH, instead * of thinking the ciphertext decrypted to the value FALSE. */ throw new InvalidCiphertextException(); } }
/** * Set document protection * Remark: the protection against modification is for people who have the full Acrobat product. * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access. * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts. * @param $permissions (Array) the set of permissions (specify the ones you want to block):<ul><li>print : Print the document;</li><li>modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';</li><li>copy : Copy or otherwise extract text and graphics from the document;</li><li>annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);</li><li>fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;</li><li>extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);</li><li>assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;</li><li>print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.</li><li>owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.</li></ul> * @param $user_pass (String) user password. Empty by default. * @param $owner_pass (String) owner password. If not specified, a random value is used. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit. * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print'))) * @public * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ public function SetProtection($permissions = array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass = '', $owner_pass = null, $mode = 0, $pubkeys = null) { if ($this->pdfa_mode) { // encryption is not allowed in PDF/A mode return; } $this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode); if ($pubkeys !== null and is_array($pubkeys)) { // public-key mode $this->encryptdata['pubkeys'] = $pubkeys; if ($mode == 0) { // public-Key Security requires at least 128 bit $mode = 1; } if (!function_exists('openssl_pkcs7_encrypt')) { $this->Error('Public-Key Security requires openssl library.'); } // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec) $this->encryptdata['pubkey'] = true; $this->encryptdata['Filter'] = 'Adobe.PubSec'; $this->encryptdata['StmF'] = 'DefaultCryptFilter'; $this->encryptdata['StrF'] = 'DefaultCryptFilter'; } else { // standard mode (password mode) $this->encryptdata['pubkey'] = false; $this->encryptdata['Filter'] = 'Standard'; $this->encryptdata['StmF'] = 'StdCF'; $this->encryptdata['StrF'] = 'StdCF'; } if ($mode > 1) { // AES if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) { $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).'); } if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) { $this->Error('AES encryption requires openssl/aes-256-cbc cypher.'); } if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) { $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.'); } if ($mode == 3 and !function_exists('hash')) { // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).'); } } if ($owner_pass === null) { $owner_pass = md5(TCPDF_STATIC::getRandomSeed()); } $this->encryptdata['user_password'] = $user_pass; $this->encryptdata['owner_password'] = $owner_pass; $this->encryptdata['mode'] = $mode; switch ($mode) { case 0: // RC4 40 bit $this->encryptdata['V'] = 1; $this->encryptdata['Length'] = 40; $this->encryptdata['CF']['CFM'] = 'V2'; break; case 1: // RC4 128 bit $this->encryptdata['V'] = 2; $this->encryptdata['Length'] = 128; $this->encryptdata['CF']['CFM'] = 'V2'; if ($this->encryptdata['pubkey']) { $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4'; $this->encryptdata['Recipients'] = array(); } break; case 2: // AES 128 bit $this->encryptdata['V'] = 4; $this->encryptdata['Length'] = 128; $this->encryptdata['CF']['CFM'] = 'AESV2'; $this->encryptdata['CF']['Length'] = 128; if ($this->encryptdata['pubkey']) { $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5'; $this->encryptdata['Recipients'] = array(); } break; case 3: // AES 256 bit $this->encryptdata['V'] = 5; $this->encryptdata['Length'] = 256; $this->encryptdata['CF']['CFM'] = 'AESV3'; $this->encryptdata['CF']['Length'] = 256; if ($this->encryptdata['pubkey']) { $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5'; $this->encryptdata['Recipients'] = array(); } break; } $this->encrypted = true; $this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id); $this->_generateencryptionkey(); }
public static function runtimeTest() { // 0: Tests haven't been run yet. // 1: Tests have passed. // 2: Tests are running right now. // 3: Tests have failed. static $test_state = 0; if ($test_state === 1 || $test_state === 2) { return; } if ($test_state === 3) { /* If an intermittent problem caused a test to fail previously, we * want that to be indicated to the user with every call to this * library. This way, if the user first does something they really * don't care about, and just ignores all exceptions, they won't get * screwed when they then start to use the library for something * they do care about. */ throw new Ex\CryptoTestFailed("Tests failed previously."); } try { $test_state = 2; self::ensureFunctionExists('openssl_get_cipher_methods'); if (\in_array(self::CIPHER_METHOD, \openssl_get_cipher_methods()) === FALSE) { throw new Ex\CryptoTestFailed("Cipher method not supported."); } self::AESTestVector(); self::HMACTestVector(); self::HKDFTestVector(); self::testEncryptDecrypt(); if (self::ourStrlen(self::createNewRandomKey()) != self::KEY_BYTE_SIZE) { throw new Ex\CryptoTestFailed(); } if (self::ENCRYPTION_INFO == self::AUTHENTICATION_INFO) { throw new Ex\CryptoTestFailed(); } } catch (Ex\CryptoTestFailed $ex) { // Do this, otherwise it will stay in the "tests are running" state. $test_state = 3; throw $ex; } // Change this to '0' make the tests always re-run (for benchmarking). $test_state = 1; }
public static function getCipherMethods($aliases = false) { return openssl_get_cipher_methods($aliases); }
/** * Return the OpenSSL supported encryption algorithms * * @return array */ protected function getOpensslAlgos() { if (empty($this->opensslAlgos)) { $this->opensslAlgos = openssl_get_cipher_methods(true); } return $this->opensslAlgos; }
/** * {@inheritdoc} */ public function decrypt($text, $key = null) { if (!function_exists('openssl_cipher_iv_length')) { throw new Exception('openssl extension is required'); } if ($decrypt_key = $key === null) { $decrypt_key = $this->_key; } if (empty($decrypt_key)) { throw new Exception('Decryption key cannot be empty.'); } $cipher = $this->_cipher; $mode = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher))); if (!in_array($cipher, openssl_get_cipher_methods())) { throw new Exception('Cipher algorithm is unknown'); } $ivSize = openssl_cipher_iv_length($cipher); $block_size = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher)); if ($ivSize > 0) { $block_size = $ivSize; } $decrypted = openssl_decrypt(substr($text, $ivSize), $cipher, $decrypt_key, $this->_getOptions(), substr($text, 0, $ivSize)); $padding_type = $this->_padding; if ($mode == '-cbc' || $mode == '-ecb') { return $this->_cryptUnpadText($decrypted, $mode, $block_size, $padding_type); } return $decrypted; }
/** * @param string $encryptionMethod * @return bool */ private function isEncryptionSupported($encryptionMethod) { if (!extension_loaded('openssl')) { return false; } if (!in_array($encryptionMethod, openssl_get_cipher_methods('true'))) { return false; } return true; }
/** * Test for engine validity * * @see self::__construct() * @param int $engine * @access public * @return bool */ function isValidEngine($engine) { switch ($engine) { case self::ENGINE_OPENSSL: if ($this->mode == self::MODE_STREAM && $this->continuousBuffer) { return false; } $this->openssl_emulate_ctr = false; $result = $this->cipher_name_openssl && extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.3', '>='); if (!$result) { return false; } // prior to PHP 5.4.0 OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING were not defined. instead of expecting an integer // $options openssl_encrypt expected a boolean $raw_data. if (!defined('OPENSSL_RAW_DATA')) { $this->openssl_options = true; } else { $this->openssl_options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING; } $methods = openssl_get_cipher_methods(); if (in_array($this->cipher_name_openssl, $methods)) { return true; } // not all of openssl's symmetric cipher's support ctr. for those // that don't we'll emulate it switch ($this->mode) { case self::MODE_CTR: if (in_array($this->cipher_name_openssl_ecb, $methods)) { $this->openssl_emulate_ctr = true; return true; } } return false; case self::ENGINE_MCRYPT: return $this->cipher_name_mcrypt && extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()); case self::ENGINE_INTERNAL: return true; } return false; }
/** * Initialize OpenSSL * * @param array $params Configuration parameters * @return void */ protected function _openssl_initialize($params) { if (!empty($params['cipher'])) { $params['cipher'] = strtolower($params['cipher']); $this->_cipher_alias($params['cipher']); $this->_cipher = $params['cipher']; } if (!empty($params['mode'])) { $params['mode'] = strtolower($params['mode']); if (!isset($this->_modes['openssl'][$params['mode']])) { log_message('error', 'Encryption: OpenSSL mode ' . strtoupper($params['mode']) . ' is not available.'); } else { $this->_mode = $this->_modes['openssl'][$params['mode']]; } } if (isset($this->_cipher, $this->_mode)) { // This is mostly for the stream mode, which doesn't get suffixed in OpenSSL $handle = empty($this->_mode) ? $this->_cipher : $this->_cipher . '-' . $this->_mode; if (!in_array($handle, openssl_get_cipher_methods(), TRUE)) { $this->_handle = NULL; log_message('error', 'Encryption: Unable to initialize OpenSSL with method ' . strtoupper($handle) . '.'); } else { $this->_handle = $handle; log_message('info', 'Encryption: OpenSSL initialized with method ' . strtoupper($handle) . '.'); } } }
/** * Gets all the supported cipher methods. * * @return array Returns a numerically indexed array containing the list of supported cipher methods. * @since 0.1 */ public static function allAvailable() : array { OpenSSL::isAvailable(true); if (self::$availableMethods === null) { $methods = array_unique(array_map('strtoupper', openssl_get_cipher_methods(true))); self::$availableMethods = array_unique(self::trimCipherMode($methods)); } return self::$availableMethods; }