function _key($v, $arg) { echo ' key: ' . $v; if (count($arg) > 0) { echo "\n\n Arguments:"; foreach ($arg as $a) { echo "\n\t{$a}"; } } if ($v == 'generate') { if (!is_dir(CONFIG_KEYS_PATH)) { mkdir(CONFIG_KEYS_PATH, 0777); } $base = ['I', 'u', 'h', '5', 'B', 'A', 'r', 'i', '7', '9', 'z', 'd', 'n', 't', 'F', '2', 'W', 'X', 'f', 'e', 'x', 'v', '_', '8', 'm', 'T', 'N', 'R', 'L', 'c', '6', 'P', 'k', 'Q', 'q', 'j', 'Y', 'M', '4', 'S', 'G', 'o', '0', '$', 'K', 's', 'g', 'H', 'E', 'b', 'a', 'J', 'U', 'Z', 'l', '1', 'O', '3', 'y', 'p', 'V', 'D', 'C', 'w']; $extra = ['$', '!', '#', '%', '&', '*', '+', '-', '?', '@', '(', ')', '/', '\\', '[', ']', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; shuffle($base); shuffle($extra); file_put_contents(CONFIG_KEYS_PATH . 'can.key', implode($base) . "\n" . implode($extra)); echo "\n\n New CAN key generated - success!"; //Now, OPEN_SSL include CLI_PATH . 'open.php'; return "\n\n OpenSSL keys & certificates - success!"; } elseif ($v == 'list') { echo "\n\n Ciphers:"; foreach (mcrypt_list_algorithms() as $x) { echo "\n\t" . $x; } echo "\n\n Cipher Modes:"; foreach (mcrypt_list_modes() as $x) { echo "\n\t" . $x; } } else { return "\n\n ----- ERROR: Command 'key:{$v}' not found!\n" . _help(); } }
public static function get_system_requirements() { return [['name' => 'Memory limit', 'expected_value' => '640M', 'current_value' => function () { return ini_get('memory_limit'); }, 'check' => function ($current_value, $expected_value) { return intval($current_value) >= intval($expected_value); }], ['name' => 'Max execution time', 'expected_value' => '30', 'current_value' => function () { return ini_get('max_execution_time'); }, 'check' => function ($current_value, $expected_value) { return intval($current_value) >= intval($expected_value); }], ['name' => 'cUrl enabled', 'expected_value' => 'Yes', 'current_value' => function () { return extension_loaded('curl') ? 'Yes' : 'No'; }, 'check' => function ($current_value, $expected_value) { return $current_value == 'Yes'; }], ['name' => 'mCrypt enabled', 'expected_value' => 'Yes', 'current_value' => function () { return extension_loaded('mcrypt') ? 'Yes' : 'No'; }, 'check' => function ($current_value, $expected_value) { return $current_value == 'Yes'; }], ['name' => 'RIJNDAEL 128 available', 'expected_value' => 'Yes', 'current_value' => function () { return extension_loaded('mcrypt') && in_array('rijndael-128', mcrypt_list_algorithms()) ? 'Yes' : 'No'; }, 'check' => function ($current_value, $expected_value) { return $current_value == 'Yes'; }], ['name' => 'CBC mode available', 'expected_value' => 'Yes', 'current_value' => function () { return extension_loaded('mcrypt') && in_array('cbc', mcrypt_list_modes()) ? 'Yes' : 'No'; }, 'check' => function ($current_value, $expected_value) { return $current_value == 'Yes'; }], ['name' => 'SHA512 available', 'expected_value' => 'Yes', 'current_value' => function () { return in_array('sha512', hash_algos()) ? 'Yes' : 'No'; }, 'check' => function ($current_value, $expected_value) { return $current_value == 'Yes'; }]]; }
function encryptmode($config) { if (@function_exists('mcrypt_list_modes')) { $listed = array(); if (!isset($config['mcrypt_mode'])) { $config['mcrypt_mode'] = 'cbc'; /* MCRYPT_MODE_CBC */ } $modes = @mcrypt_list_modes(); $found = False; while (list($key, $value) = each($modes)) { $found = True; /* Only show each once - seems this is a problem in some installs */ if (!in_array($value, $listed)) { if ($config['mcrypt_mode'] == $value) { $selected = ' selected'; } else { $selected = ''; } $descr = strtoupper($value); $out .= '<option value="' . $value . '"' . $selected . '>' . $descr . '</option>' . "\n"; $listed[] = $value; } } if (!$found) { /* Something is wrong with their mcrypt install or php.ini */ $out = '<option value="" selected>' . lang('no modes available') . '</option>' . "\n"; } } else { $out = '<option value="cbc" selected>CBC</option>' . "\n"; } return $out; }
public function setMode($mode) { $modes = mcrypt_list_modes("/usr/local/lib/libmcrypt"); if (in_array($mode, $modes)) { $this->mode = $mode; } }
/** * @return array */ public static function listModes() { if (!self::$listModes) { $listModes = mcrypt_list_modes(); self::$listModes = array_combine($listModes, $listModes); } return self::$listModes; }
function vidtrial_crypto_mode() { $modes = mcrypt_list_modes(); foreach (array("cfb", "ctr") as $mode) { if (in_array($mode, $modes)) { return $mode; } } throw new Exception("bad installation"); }
/** * 设置mode * @param [type] $mode [description] */ function setMode($mode) { if (!strlen($mode)) { return false; } if (!in_array($mode, mcrypt_list_modes())) { return false; } $this->mode = $mode; }
/** * Encrypt function * @param algo (string) algorithm to use * @param data (string) data to encrypt * @param mode (sting) mode to use for the encryption * @return (array) with encrypted data, key and iv size or null if the * algo or mode does not exist */ public static function encrypt($algo, $data, $mode = "cbc") { if (!in_array(strtolower($algo), mcrypt_list_algorithms())) { return null; } if (!in_array(strtolower($mode), mcrypt_list_modes())) { return null; } $r = self::_encrypt($algo, $data, $mode); return $r; }
public function __construct(string $cipher = null, string $hash = null, string $mode = null, bool $twoStep = true) { parent::__construct($cipher, $hash, $mode, $twoStep); if (!function_exists("mcrypt_list_algorithms")) { throw new Exception("Could not find the MCrypt module"); } elseif (!in_array($this->mCipher, mcrypt_list_algorithms())) { throw new Exception("The cipher '" . $this->mCipher . "' is not supported by this platform installation"); } elseif (!in_array($this->mMode, mcrypt_list_modes())) { throw new Exception("The block mode '" . $this->mMode . "' is not supported by this platform installation"); } }
public function action_check() { $version = explode('.', phpversion()); if ($version[0] != "5" or $version[0] == "5" and intval($version[1]) < 3) { return $this->_view->send_error_message("PHP 5.3 Required: Found " . implode('.', $version)); } if (!function_exists('mysql_connect')) { return $this->_view->send_error_message("Missing MySQL support in PHP."); } if (!function_exists('imagepng')) { return $this->_view->send_error_message("Missing GD support in PHP."); } if (!function_exists('mcrypt_encrypt') or !in_array('rijndael-128', mcrypt_list_algorithms()) or !in_array('nofb', mcrypt_list_modes())) { return $this->_view->send_error_message("Missing MCrypt support or Rjindael 128."); } $this->request->redirect('/install/database'); }
/** * Constructor * * @param string $secret * @param string $cipher * @param string $mode */ public function __construct($secret, $cipher = 'rijndael-256', $mode = 'ctr') { if (!extension_loaded('mcrypt')) { throw new \RuntimeException('The mcrypt extension must be loaded.'); } if (!in_array($cipher, mcrypt_list_algorithms(), true)) { throw new \InvalidArgumentException(sprintf('The cipher "%s" is not supported.', $cipher)); } if (!in_array($mode, mcrypt_list_modes(), true)) { throw new \InvalidArgumentException(sprintf('The mode "%s" is not supported.', $mode)); } $this->cipher = $cipher; $this->mode = $mode; if (0 === strlen($secret)) { throw new \InvalidArgumentException('$secret must not be empty.'); } $key = hash('sha256', $secret, true); if (strlen($key) > ($size = mcrypt_get_key_size($this->cipher, $this->mode))) { $key = substr($key, 0, $size); } $this->key = $key; }
/** * RIJNDAEL 256: two-way encryption/decryption, with a URL-safe base64 wrapper. * * Falls back on XOR encryption/decryption when mcrypt is not available. * * @package s2Member\Utilities * @since 3.5 * * @param str $base64 A string of data to decrypt. Should still be base64 encoded. * @param str $key Optional. Key used originally for encryption. Defaults to the one configured for s2Member. Short of that, defaults to: ``wp_salt()``. * @return str Decrypted string. */ public static function decrypt($base64 = FALSE, $key = FALSE) { $base64 = is_string($base64) ? $base64 : ""; $e = strlen($base64) ? c_ws_plugin__s2member_utils_strings::base64_url_safe_decode($base64) : ""; if (function_exists("mcrypt_decrypt") && in_array("rijndael-256", mcrypt_list_algorithms()) && in_array("cbc", mcrypt_list_modes()) && strlen($e) && preg_match("/^~r2\\:([a-zA-Z0-9]+)(?:\\:([a-zA-Z0-9]+))?\\|(.*?)\$/s", $e, $iv_md5_e)) { $key = c_ws_plugin__s2member_utils_encryption::key($key); $key = substr($key, 0, mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)); if (strlen($iv_md5_e[3]) && (!$iv_md5_e[2] || $iv_md5_e[2] === md5($iv_md5_e[3]))) { $d = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $iv_md5_e[3], MCRYPT_MODE_CBC, $iv_md5_e[1]); } if (isset($d) && is_string($d) && strlen($d)) { if (strlen($d = preg_replace("/^~r2\\|/", "", $d, 1, $r2)) && $r2) { $d = rtrim($d, ""); } else { // Else we need to empty this out. $d = ""; } } return isset($d) && is_string($d) && strlen($d) ? $string = $d : ""; } else { // Fallback on XOR decryption. return c_ws_plugin__s2member_utils_encryption::xdecrypt($base64, $key); } }
/** * DB_eSession - Constructor * You could change to always pass by reference like this: (&$_param) * Or you could leave as is, and pass by reference to save on memory, like * this: $sess = new DB_eSession($sess_param); * * @param array $_param Various database and session setting options * @return obj New instance of DB_eSession class * @access private */ function DB_eSession($_param = array()) { define('STOP', TRUE); /** * Check minimum PHP version number for script to work, and * produce error if it doesn't meet that requirement. * version_compare() requires PHP v4.1.0 to work but shouldn't * use here because current PHP might be less than that. */ if (strcmp($this->_REQ_VER, PHP_VERSION) > 0) { $this->_errors = PHP_VERSION . ' < ' . $this->_REQ_VER . "\n"; /** * Display error and stop execution regardless of _stop_on_error * setting. */ $this->_handleErrors(STOP); // Severe error - exit script } if (is_array($_param)) { $_not_array = NULL; } else { $_not_array = 'NOT_ARRAY'; // For producing a warning $_param = array(); } /** * Set the default and current language codes for displaying error and * warning messages. Default is 'en' for English. */ $this->_DEFAULT_LANG = isset($_param['default_lang']) ? $_param['default_lang'] : 'en'; $this->_CURRENT_LANG = isset($_param['current_lang']) ? $_param['current_lang'] : isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : 'en'; /** * Set $_param['stop_on_error'] => FALSE to not have this class * stop execution upon an error. This means you will handle the * error checking and displays in your script. Default is to stop * (TRUE). This is used as the initial setting. This can be turned * on and off at any time by using stopOnErrors() or endStopOnErrors(). */ $this->_stop_on_error = (bool) isset($_param['stop_on_error']) ? $_param['stop_on_error'] : TRUE; /** * Set the font color for error messages (any valid HTML syntax) */ $this->_ERR_COLOR = isset($_param['error_color']) ? $_param['error_color'] : 'RED'; /** * Set the font size for error messages (any valid HTML syntax) */ $this->_ERR_SIZE = isset($_param['error_size']) ? $_param['error_size'] : '+0'; /** * Set $_param['stop_on_warn'] => TRUE to have this class * stop execution upon a warning. Default is not to stop (FALSE). This * is used as the initial setting. This can be turned on and off at any * time by using stopOnWarnings() or endStopOnWarnings(). */ $this->_stop_on_warn = (bool) isset($_param['stop_on_warn']) ? $_param['stop_on_warn'] : FALSE; /** * Set the font color for warning messages (any valid HTML syntax) */ $this->_WRN_COLOR = isset($_param['warn_color']) ? $_param['warn_color'] : 'BLUE'; /** * Set the font size for warning messages (any valid HTML syntax) */ $this->_WRN_SIZE = isset($_param['warn_size']) ? $_param['warn_size'] : '+0'; /** * Set to TRUE to display SQL syntax and other values when displaying * errors or warning messages encountered. Default is FALSE for security * purposes. Turn on mostly when in development or testing your site, * but remember to turn it off for a production ready site. */ $this->_DETAIL_ERR_MSGS = (bool) isset($_param['detail_err_msgs']) ? $_param['detail_err_msgs'] : FALSE; /** * Set $_param['buffer'] => TRUE to have this class * execute the ob_start() command to start buffering the output. * You may want to use if you can't resolve the 'headers already sent' * warning message generated by PHP/this script. The ob_end_flush() * is called implicitly at the end of your script. It flushes out the * contents of the buffer to the browser, and destroys the current * output buffer. */ $_buffer = (bool) isset($_param['buffer']) ? $_param['buffer'] : FALSE; if ($_buffer) { ob_start(); } /** * Set the path and filename of the file containing the errors array * constants. You can use relative (recommended) or absolute file paths. * For security, specify a filename without the '.php' because the * class will automatically add '.php' to the end. i.e. If you specify * 'errors.php' this class will try to locate a file called * 'errors.php.php'. So, just specify 'errors'. The default path is * the current directory (where your script is running from), but * but recommend to put the errors file off the web directory along * with this class.DB_eSession.php file. */ $_errors_path = isset($_param['errors_path']) ? $_param['errors_path'] : './'; $_errors_file = isset($_param['errors_file']) ? $_param['errors_file'] : 'errors.DB_eSession'; $_filename = $_errors_path . $_errors_file . '.php'; if ($this->pregMatches('/^[a-z0-9_.]+$/i', $_errors_file) && file_exists($_filename)) { $_loaded = (require_once $_filename); } else { $this->_errors = "xxxx --> " . $_filename . " <-- xxxx\n"; $this->_handleErrors(STOP); // Severe error - exit script } if (0 === strcmp($_loaded, 'LOAD_OK') && isset($_ERR) && isset($_WRN)) { $this->_ERR_MSGS = $_ERR; $this->_WRN_MSGS = $_WRN; unset($_ERR, $_WRN); } else { $this->_errors = '$_ERR $_WRN xxxx --> ' . $_filename . " <-- xxxx\n"; $this->_handleErrors(STOP); // Severe error - exit script } if (!empty($_not_array)) { // Warning: parameter passed to class is not an array $this->_setWrnMsg($_not_array); } /** * Whether or not to encrypt/decrypt the WHOLE session data. This will * trigger the use of the mcrypt library or sessEncode/sessDecode. * This can be set on or off on the fly and it will work accordingly. * The default is off since encryption takes extra resources/time. */ $this->_ENCRYPT = (bool) isset($_param['encrypt']) ? $_param['encrypt'] : FALSE; /** * The key used to encrypt/decrypt individual field data or the whole * session data. Keep this key a secret (keep off the web directory). * Use readable characters and make at least 62 UNIQUE characters long. */ $this->_ENCRYPT_KEY = isset($_param['encrypt_key']) ? $_param['encrypt_key'] : "z1Mc6KRxAfNwZ0dGjY5qBXhtrPgJO7eCaUmHvQT3yW8nDsI2VkEpiS4blFoLu9"; /** * Determine if libmcrypt is installed and if it's one of the * latest versions. */ $this->_MCRYPT = extension_loaded('mcrypt'); $this->_MCRYPT_LATEST = FALSE; if ($this->_MCRYPT) { if (defined('MCRYPT_TRIPLEDES')) { // Only defined in >= 2.4.x $this->_MCRYPT_LATEST = TRUE; } /** * The key field used to encrypt/decrypt using the mcrypt library. */ $this->_ENC_KEY_HASHED = md5($this->_ENCRYPT_KEY); $this->_ENC_ALGO = isset($_param['encrypt_cipher']) ? $_param['encrypt_cipher'] : MCRYPT_GOST; $_algo = mcrypt_list_algorithms(); if (!in_array($this->_ENC_ALGO, $_algo)) { // Could not assign the encryption algorithm... $this->_setErrMsg('BAD_ALGO', NULL, $this->_ENC_ALGO); $this->_handleErrors(); $this->_ENC_ALGO = NULL; } $this->_ENC_MODE = isset($_param['encrypt_mode']) ? $_param['encrypt_mode'] : MCRYPT_MODE_CFB; $_modes = mcrypt_list_modes(); if (!in_array($this->_ENC_MODE, $_modes)) { // Could not assign the encryption mode... $this->_setErrMsg('BAD_ENC_MODE', NULL, $this->_ENC_MODE); $this->_handleErrors(); $this->_ENC_MODE = NULL; } else { if ($this->_ENC_MODE != MCRYPT_MODE_ECB && $this->_ENC_MODE != MCRYPT_MODE_CBC && $this->_ENC_MODE != MCRYPT_MODE_CFB && $this->_ENC_MODE != MCRYPT_MODE_OFB) { // Could not assign the encryption mode...Use class supported $this->_setErrMsg('BAD_MODE_SUPP', NULL, $this->_ENC_MODE, 'ECB, CBC, CFB, OFB.'); $this->_handleErrors(); $this->_ENC_MODE = NULL; } } } else { $this->_ENC_KEY_HASHED = NULL; $this->_ENC_ALGO = NULL; $this->_ENC_MODE = NULL; } /** * As of PHP 4.2.0, there is no need to seed the random number * generator, however, we'll do it here for portability. This will be * needed for use with the encryption/decryption mcrypt routines and * generating of a new session ID. */ mt_srand((double) microtime() * 1000000); srand((double) microtime() * 1000000); /** * See if MD5 hashing keys have been passed, otherwise set defaults. */ $this->_KEY_PREFIX = isset($_param['key_prefix']) ? $_param['key_prefix'] : 'O9R^3mp#i|34'; $this->_KEY_SUFFIX = isset($_param['key_suffix']) ? $_param['key_suffix'] : '+t97!u0K-2L5'; /** * A password used to pass to the delete all session/lock functions as a * way to confirm the intent of modifying all rows in the sessions * table. */ $this->_CONF_PSWD = isset($_param['confirm_pswd']) ? $_param['confirm_pswd'] : '!*CONFIRMED*!'; /** * Database related variables with assigned default values when not set. * Assign these necessary fields to allow connection to the database. * Remember to give 'sess_user' access privileges to 'db_esessions'. * Make sure the password is correct (sess1234 is the default). */ $this->_db['db_host'] = isset($_param['db_host']) ? $_param['db_host'] : 'rivendell'; $this->_db['db_user'] = isset($_param['db_user']) ? $_param['db_user'] : '******'; $this->_db['db_pswd'] = isset($_param['db_pswd']) ? $_param['db_pswd'] : 'sess1234'; $this->_db['db_name'] = isset($_param['db_name']) ? $_param['db_name'] : 'db_esessions'; $this->_db['db_persistent'] = isset($_param['db_persistent']) ? (bool) $_param['db_persistent'] : FALSE; $this->_db['db_resource'] = isset($_param['db_resource']) ? $_param['db_resource'] : NULL; /** * Optionally supply a database resource link. This class will NOT * attempt to connect to MySQL and use the link instead. */ if (is_resource($this->_db['db_resource'])) { $this->_dbh = $this->_db['db_resource']; } else { $this->_dbh = NULL; } /** * Table related variables with assigned default values when not set. * Assign these necessary fields to allow connection to the 'sessions' * table. Specify what each column name is defined as in the table. */ $this->_db['tb_name'] = isset($_param['tb_name']) ? $_param['tb_name'] : 'eSessions'; $this->_db['tb_id_col'] = isset($_param['tb_id_col']) ? $_param['tb_id_col'] : 'sess_id'; $this->_db['tb_sl_col'] = isset($_param['tb_sl_col']) ? $_param['tb_sl_col'] : 'sess_sec_level'; $this->_db['tb_cr_col'] = isset($_param['tb_cr_col']) ? $_param['tb_cr_col'] : 'sess_created'; $this->_db['tb_ex_col'] = isset($_param['tb_ex_col']) ? $_param['tb_ex_col'] : 'sess_expiry'; $this->_db['tb_to_col'] = isset($_param['tb_to_col']) ? $_param['tb_to_col'] : 'sess_timeout'; $this->_db['tb_lk_col'] = isset($_param['tb_lk_col']) ? $_param['tb_lk_col'] : 'sess_locked'; $this->_db['tb_vl_col'] = isset($_param['tb_vl_col']) ? $_param['tb_vl_col'] : 'sess_value'; $this->_db['tb_iv_col'] = isset($_param['tb_iv_col']) ? $_param['tb_iv_col'] : 'sess_enc_iv'; $this->_db['tb_si_col'] = isset($_param['tb_si_col']) ? $_param['tb_si_col'] : 'sess_sec_id'; $this->_db['tb_tr_col'] = isset($_param['tb_tr_col']) ? $_param['tb_tr_col'] : 'sess_trace'; /** * Set $_param['sess_id_len'] to be the length of the session ID. * Default of $this->_MAX_SESS_ID_LEN will be used. */ $this->_sess_ID_len = (int) isset($_param['sess_id_len']) ? intval($_param['sess_id_len']) : $this->_MAX_SESS_ID_LEN; if ($this->_sess_ID_len < $this->_MIN_SESS_ID_LEN) { $this->_sess_ID_len = $this->_MIN_SESS_ID_LEN; } else { if ($this->_sess_ID_len > $this->_MAX_SESS_ID_LEN) { $this->_sess_ID_len = $this->_MAX_SESS_ID_LEN; } } /** * Set $_param['new_sid'] => TRUE to create a new session ID. * Default is FALSE. Takes effect before a session_start(). * This can be set TRUE without setting $_param['sess_id'], in * which case, a session ID will be automatically generated. */ $_new_sess_ID = (bool) isset($_param['new_sid']) ? $_param['new_sid'] : FALSE; /** * If desired, set $_param['sess_id'] to a valid custom session ID. * Works in conjunction with $_param['new_sid'] (must be set to TRUE). */ $_sess_ID = isset($_param['sess_id']) ? $_param['sess_id'] : NULL; if (!empty($_sess_ID)) { if (strlen($_sess_ID) != $this->_sess_ID_len) { // Warning: Custom session ID passed is not the right length $this->_setWrnMsg('SESS_LENGTH', NULL, $this->_sess_ID_len, $_param['sess_id']); $_sess_ID = NULL; } else { if (!$this->pregMatches('/^[a-zA-Z0-9]+/', $_sess_ID)) { // Warning: Custom session ID passed is invalid. $this->_setWrnMsg('SESS_INVALID', NULL, $_param['sess_id']); $_sess_ID = NULL; } } } /** * Set $_param['ie_fix'] => TRUE (default) to send a header output to * fix the IE bug. See further comments below. */ $_IE_fix = (bool) isset($_param['ie_fix']) ? $_param['ie_fix'] : TRUE; /** * When set to TRUE, locked session rows will be deleted right * away, regardless of their current expiry or timeout settings when * the Garbage Collection cleanup/delete function is invoked. */ $this->_GC_DEL_LOCKED = (bool) isset($_param['gc_del_locked']) ? $_param['gc_del_locked'] : FALSE; /** * Session Runtime Configurations. See: * http://us2.php.net/manual/en/ref.session.php * * Not all can be set or take effect outside of the php.ini * configuration file. Some options can be set at runtime without * an error produced, but have no effect. i.e. session.auto_start * * All session options are used here in case there is future support * to make option take effect at runtime. i.e. session.use_trans_sid * * When $_param['stop_on_warn'] is FALSE, check for warning messages * using warningsExist(). */ $this->_sess_opt['save_path'] = isset($_param['save_path']) ? $_param['save_path'] : 'db_esessions'; if (isset($_param['name'])) { // Check to make sure name is only alphanumeric if (!$this->pregMatches('/^[a-zA-Z0-9]+/', $_param['name'])) { // Warning: Session configuration option session.name alpha $this->_setWrnMsg('NAME_INVALID', NULL, $_param['name']); $this->_sess_opt['name'] = 'eSESSION'; } else { $this->_sess_opt['name'] = $_param['name']; } } else { $this->_sess_opt['name'] = 'eSESSION'; } $this->_sess_opt['save_handler'] = isset($_param['save_handler']) ? $_param['save_handler'] : 'user'; if (isset($_param['auto_start'])) { $this->_sess_opt['auto_start'] = (bool) $_param['auto_start']; } if (isset($_param['gc_probability'])) { $this->_sess_opt['gc_probability'] = (int) (0 == intval($_param['gc_probability'])) ? 10 : intval($_param['gc_probability']); } if (isset($_param['gc_divisor'])) { $this->_sess_opt['gc_divisor'] = (int) (0 == intval($_param['gc_divisor'])) ? 100 : intval($_param['gc_divisor']); } /** * There maybe a bug with sessions lifetime under Windows and FAT32 in * PHP version 4.1.0/1/2. See: http://bugs.php.net/bug.php?id=14798 */ if (isset($_param['gc_maxlifetime'])) { $this->_sess_opt['gc_maxlifetime'] = intval($_param['gc_maxlifetime']); } if (isset($_param['serialize_handler'])) { $this->_sess_opt['serialize_handler'] = $_param['serialize_handler']; } if (isset($_param['cookie_lifetime'])) { $this->_sess_opt['cookie_lifetime'] = intval($_param['cookie_lifetime']); } if (isset($_param['cookie_path'])) { $this->_sess_opt['cookie_path'] = $_param['cookie_path']; } if (isset($_param['cookie_domain'])) { $this->_sess_opt['cookie_domain'] = $_param['cookie_domain']; } if (isset($_param['cookie_secure'])) { $this->_sess_opt['cookie_secure'] = $_param['cookie_secure']; if (0 === strcmp($this->_sess_opt['cookie_secure'], '1') && !$this->secureConnection()) { // Warning: You are setting session.cookie_secure - not secure $this->_setWrnMsg('NOT_SECURE'); } } if (isset($_param['use_cookies'])) { $this->_sess_opt['use_cookies'] = (bool) $_param['use_cookies']; } if (isset($_param['use_only_cookies']) && version_compare(PHP_VERSION, '4.3.0', '>=')) { $this->_sess_opt['use_only_cookies'] = (bool) $_param['use_only_cookies']; } if (isset($_param['referer_check'])) { $this->_sess_opt['referer_check'] = $_param['referer_check']; } if (isset($_param['entropy_file'])) { $this->_sess_opt['entropy_file'] = $_param['entropy_file']; } if (isset($_param['entropy_length'])) { $this->_sess_opt['entropy_length'] = intval($_param['entropy_length']); } if (isset($_param['cache_limiter'])) { $this->_sess_opt['cache_limiter'] = $_param['cache_limiter']; } if (isset($_param['cache_expire'])) { // For PHP version >= 4.2.0 $this->_sess_opt['cache_expire'] = intval($_param['cache_expire']); } if (isset($_param['bug_compat_42'])) { $this->_sess_opt['bug_compat_42'] = (bool) $_param['bug_compat_42']; } if (isset($_param['bug_compat_warn'])) { $this->_sess_opt['bug_compat_warn'] = (bool) $_param['bug_compat_warn']; } if (version_compare(PHP_VERSION, '5.0.0', '>=')) { // session.use_trans_sid can be changed in a script from v5.0.0 on if (isset($_param['use_trans_sid'])) { $this->_sess_opt['use_trans_sid'] = $_param['use_trans_sid']; } if (isset($_param['hash_function'])) { $this->_sess_opt['hash_function'] = $_param['hash_function']; } if (isset($_param['hash_bits_per_character'])) { $this->_sess_opt['hash_bits_per_character'] = $_param['hash_bits_per_character']; } } /** * Set session configuration options. Values will remain during the * script's execution, and will be restored at the script's ending. */ foreach ($this->_sess_opt as $_key => $_value) { if (FALSE === $this->_setSessOption($_key, $_value)) { // Warning: Session configuration option ... not assigned $this->_setWrnMsg('SESS_OPTION', NULL, $_key, $_value); } } /** * Support for url_rewriter.tags option since it relates to sessions. * Example: Like you might want to add the iframe=src to it, as in: * a=href,area=href,frame=src,iframe=src,form=,fieldset=,input=src */ if (isset($_param['tags'])) { if (FALSE === $this->_setSessOption('url_rewriter.tags', $_param['tags'], FALSE)) { // Warning: Configuration option [url_rewriter.tags] not assign $this->_setWrnMsg('URL_TAGS', NULL, $_param['tags']); } } /** * Security Level: A numerical method to represent access authority for * current session/web page. The lower the number means the higher the * security clearance. In other words, security level 5 can only access * all level 5 or higher session/web pages, and nothing lower than 5. * Range 0-255. The default is 128. For administration or sensitive pages * use 0 (zero) or 1 (one) as a value. A security level can't be changed * after a session has been created. So, the first time the session * is created with a set security level, it dictates the access * authority for the rest of that active session. */ $this->_SEC_LEVEL = isset($_param['security_level']) ? intval($_param['security_level']) : 128; /** * Get current setting of sessions life duration in seconds. * This is the number of seconds that is allowed to pass since * the last time the session data was accessed. * Otherwise, default it to 1440 seconds (24 minutes). */ $this->_SESS_LIFE = intval(ini_get('session.gc_maxlifetime')); $this->_SESS_LIFE = (int) ($this->_SESS_LIFE < 1) ? 1440 : $this->_SESS_LIFE; /** * Calculates maximum life of session in seconds. It's three times * the length of gc_maxlifetime (for the default). For example: if * gc_maxlifetime is 1440 seconds (24 minutes), then session * timeout maximum is set to 4320 seconds (72 minutes). The timeout * value can't be less than the gc_maxlifetime value. */ if (isset($_param['timeout'])) { $this->_SESS_TIMEOUT = (int) (intval($_param['timeout']) < $this->_SESS_LIFE) ? $this->_SESS_LIFE * 3 : intval($_param['timeout']); } else { $this->_SESS_TIMEOUT = (int) $this->_SESS_LIFE * 3; } /** * Must not send any HTML output before session_start() is invoked. * Set a warning message if HTML headers have been sent to the browser. * Exception: ob_start() for buffering. */ if (!$_buffer) { if (version_compare(PHP_VERSION, '4.3.0', '>=')) { $_filename = ''; $_linenbr = (int) 0; if (headers_sent($_filename, $_linenbr)) { // Warning: HTTP headers already sent - with detail $this->_setWrnMsg('HEADER_SENT_1', NULL, $_filename, $_linenbr); } } else { if (headers_sent()) { // Warning: HTTP headers have already been sent - no detail $this->_setWrnMsg('HEADER_SENT_2'); } } } /** * Assign session storage tasks to methods in this class. */ if (!session_set_save_handler(array(&$this, '_sessDBOpen'), array(&$this, '_sessDBClose'), array(&$this, '_sessDBRead'), array(&$this, '_sessDBWrite'), array(&$this, '_sessDBDestroy'), array(&$this, '_sessDBGC'))) { // execution of session_set_save_handler() failed $this->_setErrMsg('HANDLER_FAIL'); $this->_handleErrors(STOP); // Severe error - exit script } $this->_sess_name = session_name(); /** * Set whether the magic quotes GPC that effects slashing quotes of * GET/POST/COOKIE data is set. */ $this->_MAGIC_QUOTES_GPC = (bool) get_magic_quotes_gpc(); /** * Set whether the magic quotes runtime that effects slashing quotes of * external data sources is set. */ $this->_MAGIC_QUOTES_RUNTIME = (bool) get_magic_quotes_runtime(); $this->_ARG_SEP = '' == ini_get('arg_separator.output') ? '&' : ini_get('arg_separator.output'); /** * Set TRUE to force addslashes() to occur on session data regardless * of the magic quotes runtime option setting. Default is on (TRUE). * If you find that data has slashes incorrectly, then turn this off. */ $this->_SLASH_ANYWAY = (bool) isset($_param['slash_anyway']) ? $_param['slash_anyway'] : TRUE; /** * Set TRUE to force stripslashes() to occur on encrypted session data * regardless of the magic quotes runtime option setting. The default * is on (TRUE). If you find that data is saved incorrectly, then * turn this off. */ $this->_STRIP_ANYWAY = (bool) isset($_param['strip_anyway']) ? $_param['strip_anyway'] : TRUE; /** * Try and save the current session ID if one is defined already. */ if (isset($_COOKIE[$this->_sess_name])) { $_sess_id_set = $_COOKIE[$this->_sess_name]; } else { if (isset($GLOBALS[$this->_sess_name])) { $_sess_id_set = $GLOBALS[$this->_sess_name]; } else { $_sess_id_set = NULL; } } /** * Create a new session ID when requested, or when the session ID length * is less than the standard maximum if a session hasn't been started * or created already ($_COOKIE or $GLOBALS[$this->_sess_name]). */ if ($_new_sess_ID || $this->_sess_ID_len < $this->_MAX_SESS_ID_LEN && !isset($_COOKIE[$this->_sess_name]) && !isset($GLOBALS[$this->_sess_name])) { $this->_setNewSessID($_sess_ID); } /** * When warning flag is set and there's warning messages, stop * execution here. No point in proceeding. */ $this->_handleErrors(); /** * By default this class will do a session_start(), however, you may * want to turn it off when using the maintenance type of functions. */ $_do_sess_start = (bool) isset($_param['session_start']) ? $_param['session_start'] : TRUE; /** * When session start is requested and $_SESSION doesn't exist, it * means that the auto start option is not on, and no session_start() * has been invoked yet. So, start a session. This is safer than * checking the 'session.auto_start' configuration setting with * ini_get(). Otherwise, just make a manual connection to the DB for * now (to make the maintenance type of member functions available for * use). You would then have to invoke the session_start() from within * your script (if desired). If the session is started in your script, * then another call to _sessDBOpen will be invoked but it will be * handled alright. */ if ($_do_sess_start && !isset($_SESSION)) { session_start(); } else { if (!$_do_sess_start) { $this->_sessDBOpen($this->_sess_opt['save_path'], $this->_sess_name); } } /** * If there was a previous session ID set and we now have a new one, * then delete the old session row right away without waiting for it to * expire first (for security reasons). */ if ($_do_sess_start && !empty($_sess_id_set)) { if (0 !== strcmp($_sess_id_set, session_id())) { $this->deleteSession($_sess_id_set); } } /** * There is a form bug in IE v6 while using PHP sessions which causes * the loss of filled-in information when returning to the form, after * already leaving the form page (by any means). A work around is to use * the HTTP 1.1 header "Cache-Control: private" */ if ($_IE_fix) { $this->sendCacheHeader('private'); } }
<?php $lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\neiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim\nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum\ndolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,\nsunt in culpa qui officia deserunt mollit anim id est laborum."; // Take a plaintext that's an integer number times 16 bytes long. // 96-byte plaintext is an integer number of blocks for block sizes 8, 16, 24 and 32. $plaintext = mb_substr($lipsum, 0, 96, '8bit'); $ikm = ''; $iiv = ''; for ($i = 0; $i <= 255; $i += 1) { $ikm .= chr($i); $iiv .= chr(($i + 128) % 256); } $ciphers = mcrypt_list_algorithms(); sort($ciphers); $modes = mcrypt_list_modes(); sort($modes); $mcryptCiphertexts = []; foreach ($ciphers as $cipher) { foreach ($modes as $mode) { $status = 'Yes'; $keySize = ''; $blockSize = ''; $module = @mcrypt_module_open($cipher, '', $mode, ''); if ($module === false || !is_resource($module)) { $status = 'No'; continue; } else { $keySize = mcrypt_get_key_size($cipher, $mode); $blockSize = mcrypt_get_block_size($cipher, $mode); $padding = $mode === 'cbc' || $mode === 'ecb' ? str_repeat(chr($blockSize), $blockSize) : ''; $iv = $mode === 'stream' ? '' : substr($iiv, 0, $blockSize);
$p_encoding = intval(@$_GET['encoding']); $p_mode = intval(@$_GET['mode']); $p_key_settings = intval(@$_GET['key']); $p_iv_settings = intval(@$_GET['iv']); if ($p_cipher == 0) { $p_cipher = 3; } if ($p_encoding == 0) { $p_encoding = 2; } if ($p_mode == 0) { $p_mode = 1; } $cipherList = mcrypt_list_algorithms(); $cipher = $cipherList[$p_cipher - 1]; $modeList = mcrypt_list_modes(); $mode = $modeList[$p_mode - 1]; $key_iv_list = getKeySettings(); $keysize = intval(mcrypt_get_key_size($cipher, $mode)); $blocksize = intval(mcrypt_get_block_size($cipher, $mode)); $key = genKey($keysize); $iv = genIV($blocksize); $encoding_list = list_encoding(); function list_encoding() { $encodings = array("base64", "lower hex", "upper hex", "websafe base64"); return $encodings; } function encode($text, $mode = 2) { switch ($mode) {
/** * Decryption Procedure * * @param string $msg output from encrypt() * @param string $key encryption key * @param boolean $base64 base64 decode msg * @param string $algorythm mcrypt algorithm * @param string $mode mcrypt mode * * @throws \Exception * @return string original message/data */ public function decrypt($msg, $key, $base64 = false, $algorythm, $mode) { if ($base64) { $msg = base64_decode($msg); } if (!in_array($algorythm, mcrypt_list_algorithms())) { throw new Exception('Wrong mcrypt algorithm. Use mcrypt_list_algorithms() for list available algorythm.'); } if (!in_array($mode, mcrypt_list_modes())) { throw new Exception('Wrong mcrypt mode. Use mcrypt_list_modes() for list available mode.'); } if (!($td = mcrypt_module_open($algorythm, '', $mode, ''))) { throw new Exception('Can not open mcrypt module'); } try { $initializationVector = substr($msg, 0, mcrypt_enc_get_iv_size($td)); $mo = strlen($msg) - mcrypt_enc_get_iv_size($td); $em = substr($msg, $mo); $msg = substr($msg, mcrypt_enc_get_iv_size($td), strlen($msg) - mcrypt_enc_get_iv_size($td) * 2); $mac = $this->pbkdf2($initializationVector . $msg, $key, 1000, mcrypt_enc_get_iv_size($td)); } catch (Exception $e) { return 'Caught exception: ' . $e->getMessage(); } if ($em !== $mac) { throw new Exception('Can not init mcrypt'); } if (mcrypt_generic_init($td, $key, $initializationVector) !== 0) { throw new Exception('Can not init mcrypt'); } try { $msg = mdecrypt_generic($td, $msg); $msg = unserialize($msg); mcrypt_generic_deinit($td); mcrypt_module_close($td); return trim($msg); } catch (Exception $e) { return 'Caught exception: ' . $e->getMessage(); } }
<?php /** * Lists all available mcrypt algorithms, all their respective modes as well as block, iv and key size. * Can be ran in a browser or on the command line */ header('Content-type: text/plain'); print "ALGORITHM: mode(block size, iv size, key size)[, mode(block size, iv size, key size)[, ...]]\n" . "-------------------------------\n"; foreach (mcrypt_list_algorithms() as $a) { print strtoupper($a) . ':'; foreach (mcrypt_list_modes() as $m) { if (@mcrypt_get_block_size($a, $m)) { print ' ' . $m . '(' . mcrypt_get_block_size($a, $m) . ',' . mcrypt_get_iv_size($a, $m) . ',' . mcrypt_get_key_size($a, $m) . ')'; } } print "\n"; }
protected function getEncryptConfig() { $config = $this->getConfig('encrypt') ?: array(); if (!isset($config[0]) || !$config[0]) { throw new \RuntimeException('Require encrypt salt string'); } $salt = $config[0]; $cipher = isset($config[1]) ? $config[1] : MCRYPT_RIJNDAEL_256; if (!in_array($cipher, mcrypt_list_algorithms())) { throw new \RuntimeException('Unsupport encrypt cipher: ' . $cipher); } $mode = isset($config[2]) ? $config[2] : MCRYPT_MODE_CBC; if (!in_array($mode, mcrypt_list_modes())) { throw new \RuntimeException('Unsupport encrypt mode: ' . $mode); } if (isset($config[3])) { $device = $config[3]; } elseif (defined('MCRYPT_DEV_URANDOM')) { $device = MCRYPT_DEV_URANDOM; } elseif (defined('MCRYPT_DEV_RANDOM')) { $device = MCRYPT_DEV_RANDOM; } else { mt_srand(); $device = MCRYPT_RAND; } return [$salt, $cipher, $mode, $device]; }
function vidtrial_check_dependencies() { $errors = array(); if (version_compare(PHP_VERSION, '5.3.0', '<')) { $errors[] = __("Your PHP version is too old. Please update to at least PHP5.3", VIDTRIAL_TD); } if (!function_exists("openssl_random_pseudo_bytes")) { $errors[] = __("Please install the PHP openssl module", VIDTRIAL_TD); } if (!function_exists("mcrypt_generic_init")) { $errors[] = __("Please install the PHP mcrypt module", VIDTRIAL_TD); } if (!count(array_intersect(mcrypt_list_algorithms(), array("rijndael-128", "twofish", "serpent")))) { $errors[] = __("Please ensure the mcrypt PHP module has one algorithm of 'rijndael', 'twofish' or 'serpent' available", VIDTRIAL_TD); } if (!count(array_intersect(mcrypt_list_modes(), array("cfb", "ctr")))) { $errors[] = __("Please ensure the mcrypt PHP module has one of 'cfb' or 'ctr' modes available", VIDTRIAL_TD); } if (count($errors)) { die(implode("<br>", $errors)); } }
public function set_mcrypt_modes() { $this->_mcrypt_modes = mcrypt_list_modes($this->_mcrypt_modes_dir); }
/** * Returns a list of available modes * * @return array */ public function getAvailableModes() { return mcrypt_list_modes(); }
public function providerAlgorithmMode() { $algorithms = mcrypt_list_algorithms(); $modes = mcrypt_list_modes(); $data = array(); foreach ($algorithms as $algorithm) { foreach ($modes as $mode) { if ($mode != MCRYPT_MODE_STREAM && @mcrypt_get_key_size($algorithm, $mode) !== false) { //Test algorithm/mode availability $data[] = array($algorithm, $mode); } } } return $data; }
<?php var_dump(mcrypt_list_modes());
/** * RIJNDAEL 256: two-way encryption/decryption, with a URL-safe base64 wrapper. * * Falls back on XOR encryption/decryption when mcrypt is not available. * * @package s2Member\Utilities * @since 3.5 * * @param string $base64 A string of data to decrypt. Should still be base64 encoded. * @param string $key Optional. Key used originally for encryption. Defaults to the one configured for s2Member. Short of that, defaults to: ``wp_salt()``. * * @return string Decrypted string. */ public static function decrypt($base64 = '', $key = '') { $base64 = is_string($base64) ? $base64 : ''; $e = isset($base64[0]) ? c_ws_plugin__s2member_utils_strings::base64_url_safe_decode($base64) : ''; if (function_exists('mcrypt_decrypt') && in_array('rijndael-256', mcrypt_list_algorithms()) && in_array('cbc', mcrypt_list_modes())) { if (isset($e[0]) && preg_match('/^~r2\\:([a-zA-Z0-9]+)(?:\\:([a-zA-Z0-9]+))?\\|(.*)$/s', $e, $iv_md5_e)) { $key = c_ws_plugin__s2member_utils_encryption::key($key); $key = substr($key, 0, mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)); if (isset($iv_md5_e[3][0]) && (empty($iv_md5_e[2]) || $iv_md5_e[2] === md5($iv_md5_e[3]))) { $d = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $iv_md5_e[3], MCRYPT_MODE_CBC, $iv_md5_e[1]); } if (isset($d) && is_string($d) && isset($d[0])) { if (strlen($d = preg_replace('/^~r2\\|/', '', $d, 1, $r2)) && $r2) { $d = rtrim($d, ""); } else { $d = ''; } } // Force empty string; bad decryption. return isset($d) && is_string($d) && isset($d[0]) ? $string = $d : ''; // Default to empty string. } } return c_ws_plugin__s2member_utils_encryption::xdecrypt($base64, $key); }
/** * Opens the module of the algorithm and the mode to be used. * * @param string $algorithm * @param string $algorithm_directory * @param string $mode * @param string $mode_directory * @return resource * @deprecated */ function mcrypt_module_open($algorithm, $algorithm_directory, $mode, $mode_directory) { // If the algorithm or mode isn't in the list of supported ones, // bail out early. if (!in_array($algorithm, mcrypt_list_algorithms())) { return false; } if (!in_array($mode, mcrypt_list_modes())) { return false; } // Since we can't actually return a resource, we have to fake it a bit. // Most code that doesn't call is_resource() will behave appropriately // in this case, but some amount of breakage is unavoidable. $resource = new McryptResource(); $resource->setCipher($algorithm)->setMode($mode); return $resource; }
/** * RIJNDAEL 256: two-way encryption/decryption, with a URL-safe base64 wrapper. * * @note This falls back on XOR encryption/decryption when/if mcrypt is not possible. * * @note Usually, it's better to use these `encrypt()` / `decrypt()` functions instead of XOR encryption; * because RIJNDAEL 256 offers MUCH better security. However, `xencrypt()` / `xdecrypt()` offer true consistency, * making them a better choice in certain scenarios. That is, XOR encrypted strings always offer the same representation * of the original string; whereas RIJNDAEL 256 changes randomly, making it difficult to use comparison algorithms. * * @param string $base64 A string of data to decrypt. * Should still be base64 encoded. * @param string $key Optional. Key used originally for encryption. * Defaults to the one configured for the plugin. * * @throws \exception If a validated RIJNDAEL 256 string decryption fails. * @return string Decrypted string, or an empty string if validation fails. * Validation may fail due to an invalid checksum, or a missing component in the encrypted string. * For security purposes, this returns an empty string on validation failures. * */ public function decrypt($base64, $key = '') { $base64 = (string) $base64; $key = (string) $key; if (!isset($base64[0])) { // Nothing to decrypt? return $string = ''; // Nothing to do. } if (!extension_loaded('mcrypt') || !in_array('rijndael-256', mcrypt_list_algorithms(), true) || !in_array('cbc', mcrypt_list_modes(), true) || !strlen($e = $this->base64UrlSafeDecode($base64)) || !preg_match('/^~r2\\:(?P<iv>[a-zA-Z0-9]+)(?:\\:(?P<md5>[a-zA-Z0-9]+))?\\|(?P<e>.*)$/s', $e, $iv_md5_e)) { return $this->xDecrypt($base64, $key); // Try XOR decryption instead :-) } if (!isset($iv_md5_e['iv'][0], $iv_md5_e['e'][0])) { return $string = ''; // Components missing. } if (isset($iv_md5_e['md5'][0]) && $iv_md5_e['md5'] !== md5($iv_md5_e['e'])) { return $string = ''; // Invalid checksum; automatic failure. } $key = (string) substr($this->key($key), 0, mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)); if (!is_string($string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $iv_md5_e['e'], MCRYPT_MODE_CBC, $iv_md5_e['iv'])) || !isset($string[0])) { throw new \exception(__('String decryption failed; `$string` is NOT a string, or it has no length.', 'comment-mail')); } if (!strlen($string = preg_replace('/^~r2\\|/', '', $string, 1, $r2)) || !$r2) { return $string = ''; // Missing packed components. } return $string = rtrim($string, ""); // See: <http://www.asciitable.com/>. }
function set_mode($encryptmode) { // make sure encryption mode is a valid mode if (in_array($encryptmode, mcrypt_list_modes())) { $this->mode = $encryptmode; } else { return 0; } }
/** * Returns an array of supported operation modes. * * @return array */ public static function getSupportedModes() { return mcrypt_list_modes(); }
/** * Sets new encryption options * * @param string|array $options Encryption options * @return Zend_Filter_File_Encryption */ public function setEncryption($options) { if (is_string($options)) { $options = array('key' => $options); } if (!is_array($options)) { #require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Invalid options argument provided to filter'); } $options = $options + $this->getEncryption(); $algorithms = mcrypt_list_algorithms($options['algorithm_directory']); if (!in_array($options['algorithm'], $algorithms)) { #require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("The algorithm '{$options['algorithm']}' is not supported"); } $modes = mcrypt_list_modes($options['mode_directory']); if (!in_array($options['mode'], $modes)) { #require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("The mode '{$options['mode']}' is not supported"); } if (!mcrypt_module_self_test($options['algorithm'], $options['algorithm_directory'])) { #require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('The given algorithm can not be used due an internal mcrypt problem'); } if (!isset($options['vector'])) { $options['vector'] = null; } $this->_encryption = $options; $this->setVector($options['vector']); return $this; }
/** * Return array of ciphers mode available * @return strAv Configuration file content */ function dol_efc_config() { // Make sure we can use mcrypt_generic_init if (!function_exists("mcrypt_generic_init")) { return -1; } // Set a temporary $key and $data for encryption tests $key = md5(time() . getmypid()); $data = mt_rand(); // Get and sort available cipher methods $ciphers = mcrypt_list_algorithms(); natsort($ciphers); // Get and sort available cipher modes $modes = mcrypt_list_modes(); natsort($modes); foreach ($ciphers as $cipher) { foreach ($modes as $mode) { // Not Compatible $result = 'false'; // open encryption module $td = @mcrypt_module_open($cipher, '', $mode, ''); // if we could open the cipher if ($td) { // try to generate the iv $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size ($td), MCRYPT_RAND); // if we could generate the iv if ($iv) { // initialize encryption @mcrypt_generic_init ($td, $key, $iv); // encrypt data $encrypted_data = mcrypt_generic($td, $data); // cleanup mcrypt_generic_deinit($td); // No error issued $result = 'true'; } // close @mcrypt_module_close($td); } if ($result == "true") $available["$cipher"][] = $mode; } } if (count($available) > 0) { // Content of configuration $strAv = "<?php\n"; $strAv.= "/* Copyright (C) 2003 HumanEasy, Lda. <*****@*****.**>\n"; $strAv.= " * Copyright (C) 2009 Regis Houssin <*****@*****.**>\n"; $strAv.= " *\n"; $strAv.= " * All rights reserved.\n"; $strAv.= " * This file is licensed under GNU GPL version 2 or above.\n"; $strAv.= " * Please visit http://www.gnu.org to now more about it.\n"; $strAv.= " */\n\n"; $strAv.= "/**\n"; $strAv.= " * Name: EasyFileCrypt Extending Crypt Class\n"; $strAv.= " * Version: 1.0\n"; $strAv.= " * Created: ".date("r")."\n"; $strAv.= " * Ciphers Installed on this system: ".count($ciphers)."\n"; $strAv.= " */\n\n"; $strAv.= " \$xfss = Array ( "; foreach ($ciphers as $avCipher) { $v = ""; if (count($available["$avCipher"]) > 0) { foreach ($available["$avCipher"] as $avMode) $v .= " '".$avMode."', "; $i = dol_strlen($v) - 2; if ($v[$i] == ",") $v = substr($v, 2, $i - 3); } if (!empty($v)) $v = " '".$v."' "; $strAv .= "'".$avCipher."' => Array (".$v."),\n "; } $strAv = rtrim($strAv); if ($strAv[dol_strlen($strAv) - 1] == ",") $strAv = substr($strAv, 0, dol_strlen($strAv) - 1); $strAv .= " );\n\n"; $strAv .= "?>"; return $strAv; } }