Example #1
0
 /**
  * Encrypt a string using Mcrypt.
  *
  * The string will be encrypted using the AES-256 scheme and will be base64 encoded.
  *
  * @param  string  $value
  * @return string
  */
 public static function encrypt($value)
 {
     $iv = mcrypt_create_iv(static::iv_size(), static::randomizer());
     $value = static::pad($value);
     $value = mcrypt_encrypt(static::$cipher, static::key(), $value, static::$mode, $iv);
     return base64_encode($iv . $value);
 }
 public function confirmAction()
 {
     if (!$this->getRequest()->getParam('id')) {
         return $this->_redirect('/registration');
     }
     // Check if the user exists and has not already been activated
     $user_mapper = new Application_Model_UserMapper();
     $user = $user_mapper->find($this->getRequest()->getParam('id'));
     if ($user && !$user->getActive()) {
         /**
          * Generate a random activation key unique to the account. Insert
          * it into a link, and email it to the user. If the user opens the
          * link within 24 hours, the account will be activated
          */
         $user_activation_mapper = new Application_Model_UserActivationMapper();
         $user_activation = new Application_Model_UserActivation();
         $activation_key = '';
         $duplicate_activation_key = true;
         while ($duplicate_activation_key) {
             $random = mcrypt_create_iv(64);
             $activation_key = hash('sha256', $random . $user->getPassword_salt() . $user->getUsername() . $user->getPassword_hash());
             $duplicate_activation_key = $user_activation_mapper->findByActivation_key($activation_key);
         }
         $user_activation->setUser_id($user->getId())->setActivation_key($activation_key)->setCreated(date('Y-m-d H:i:s'));
         $user_activation_mapper->save($user_activation, true);
         $to = $user->getEmail();
         $subject = 'User Activation';
         $txt = "You have registered on zf1.\n                        <br/>\n                        <br/>\n                        To activate the account, follow this <a href='zf1.local/registration/activate/activation_key/{$activation_key}'>link</a>.\n                        <br/>\n                        <br/>\n                        This link will expire after 24 hours.\n                        <br/>\n                        If you follow the link after it expires and the account has not already been activated,\n                        <br/>\n                        another email will be sent with a fresh link.\n                        <br/>\n                        <br/>\n                        An email can also be sent by attempting to sign in with an account that has been registered but not yet activated.";
         $headers = '';
         //            mail($to, $subject, $txt, $headers);
         mail($to, $subject, $txt);
     } else {
         return $this->_redirect('/');
     }
 }
Example #3
0
 public function __construct($_key = '', $_bit = 128, $_type = 'ecb', $_use_base64 = true)
 {
     // 加密字节
     if (192 === $_bit) {
         $this->_bit = MCRYPT_RIJNDAEL_192;
     } elseif (128 === $_bit) {
         $this->_bit = MCRYPT_RIJNDAEL_128;
     } else {
         $this->_bit = MCRYPT_RIJNDAEL_256;
     }
     // 加密方法
     if ('cfb' === $_type) {
         $this->_type = MCRYPT_MODE_CFB;
     } elseif ('cbc' === $_type) {
         $this->_type = MCRYPT_MODE_CBC;
     } elseif ('nofb' === $_type) {
         $this->_type = MCRYPT_MODE_NOFB;
     } elseif ('ofb' === $_type) {
         $this->_type = MCRYPT_MODE_OFB;
     } elseif ('stream' === $_type) {
         $this->_type = MCRYPT_MODE_STREAM;
     } else {
         $this->_type = MCRYPT_MODE_ECB;
     }
     // 密钥
     if (!empty($_key)) {
         $this->_key = $_key;
     }
     // 是否使用base64
     $this->_use_base64 = $_use_base64;
     $this->_iv_size = mcrypt_get_iv_size($this->_bit, $this->_type);
     $this->_iv = mcrypt_create_iv($this->_iv_size, MCRYPT_RAND);
 }
 public static function decode($decrypt, $key)
 {
     $decoded = base64_decode($decrypt);
     $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
     $decrypted = mcrypt_decrypt(MCRYPT_DES, $key, $decoded, MCRYPT_MODE_ECB, $iv);
     return $decrypted;
 }
Example #5
0
 /**
  * Generate random bytes using OpenSSL or Mcrypt and mt_rand() as fallback
  *
  * @param  integer $length
  * @param  bool $strong true if you need a strong random generator (cryptography)
  * @return string
  * @throws Exception\RuntimeException
  */
 public static function getBytes($length, $strong = false)
 {
     if ($length <= 0) {
         return false;
     }
     if (extension_loaded('openssl')) {
         $rand = openssl_random_pseudo_bytes($length, $secure);
         if ($secure === true) {
             return $rand;
         }
     }
     if (extension_loaded('mcrypt')) {
         // PHP bug #55169
         // @see https://bugs.php.net/bug.php?id=55169
         if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' || version_compare(PHP_VERSION, '5.3.7') >= 0) {
             $rand = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
             if ($rand !== false && strlen($rand) === $length) {
                 return $rand;
             }
         }
     }
     if ($strong) {
         throw new Exception\RuntimeException('This PHP environment doesn\'t support secure random number generation. ' . 'Please consider to install the OpenSSL and/or Mcrypt extensions');
     }
     $rand = '';
     for ($i = 0; $i < $length; $i++) {
         $rand .= chr(mt_rand(0, 255));
     }
     return $rand;
 }
 private static function _decrypt($value, $key)
 {
     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($value), MCRYPT_MODE_ECB, $iv);
     return trim($decrypttext);
 }
Example #7
0
 /**
  *	Generate bcrypt hash of string
  *	@return string|FALSE
  *	@param $pw string
  *	@param $salt string
  *	@param $cost int
  **/
 function hash($pw, $salt = NULL, $cost = self::COST)
 {
     if ($cost < 4 || $cost > 31) {
         user_error(self::E_CostArg, E_USER_ERROR);
     }
     $len = 22;
     if ($salt) {
         if (!preg_match('/^[[:alnum:]\\.\\/]{' . $len . ',}$/', $salt)) {
             user_error(self::E_SaltArg, E_USER_ERROR);
         }
     } else {
         $raw = 16;
         $iv = '';
         if (extension_loaded('mcrypt')) {
             $iv = mcrypt_create_iv($raw, MCRYPT_DEV_URANDOM);
         }
         if (!$iv && extension_loaded('openssl')) {
             $iv = openssl_random_pseudo_bytes($raw);
         }
         if (!$iv) {
             for ($i = 0; $i < $raw; $i++) {
                 $iv .= chr(mt_rand(0, 255));
             }
         }
         $salt = str_replace('+', '.', base64_encode($iv));
     }
     $salt = substr($salt, 0, $len);
     $hash = crypt($pw, sprintf('$2y$%02d$', $cost) . $salt);
     return strlen($hash) > 13 ? $hash : FALSE;
 }
Example #8
0
 function phpFreaksCrypto($key = 'a843l?nv89rjfd}O(jdnsleken0', $iv = false, $algorithm = 'tripledes', $mode = 'ecb')
 {
     if (extension_loaded('mcrypt') === FALSE) {
         //$prefix = (PHP_SHLIB_SUFFIX == 'dll') ? 'php_' : '';
         //dl($prefix . 'mcrypt.' . PHP_SHLIB_SUFFIX) or die('The Mcrypt module could not be loaded.');
         die('The Mcrypt module is not loaded and is required.');
     }
     if ($mode != 'ecb' && $iv === false) {
         /*
           the iv must remain the same from encryption to decryption and is usually
           passed into the encrypted string in some form, but not always.
         */
         die('In order to use encryption modes other then ecb, you must specify a unique and consistent initialization vector.');
     }
     // set mcrypt mode and cipher
     $this->td = mcrypt_module_open($algorithm, '', $mode, '');
     // Unix has better pseudo random number generator then mcrypt, so if it is available lets use it!
     //$random_seed = strstr(PHP_OS, "WIN") ? MCRYPT_RAND : MCRYPT_DEV_RANDOM;
     $random_seed = MCRYPT_RAND;
     // if initialization vector set in constructor use it else, generate from random seed
     $iv = $iv === false ? mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), $random_seed) : substr($iv, 0, mcrypt_enc_get_iv_size($this->td));
     // get the expected key size based on mode and cipher
     $expected_key_size = mcrypt_enc_get_key_size($this->td);
     // we dont need to know the real key, we just need to be able to confirm a hashed version
     $key = substr(md5($key), 0, $expected_key_size);
     // initialize mcrypt library with mode/cipher, encryption key, and random initialization vector
     mcrypt_generic_init($this->td, $key, $iv);
 }
Example #9
0
 /**
  * Encrypts a string using AES
  *
  * @param   string  $stringToEncrypt  The plaintext to encrypt
  * @param   bool    $base64encoded    Should I Base64-encode the result?
  *
  * @return   string  The cryptotext. Please note that the first 16 bytes of the raw string is the IV (initialisation vector) which is necessary for decoding the string.
  */
 public function encryptString($stringToEncrypt, $base64encoded = true)
 {
     // Calculate the key to use for encryption
     $keySize = mcrypt_get_key_size($this->_cipherType, $this->_cipherMode);
     if (strlen($this->_keyString) != 32) {
         $key = hash('sha256', $this->_keyString, true);
     } else {
         $key = $this->_keyString;
     }
     // Set up the IV (Initialization Vector)
     $iv_size = mcrypt_get_iv_size($this->_cipherType, $this->_cipherMode);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
     if (empty($iv)) {
         $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_RANDOM);
     }
     if (empty($iv)) {
         $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     }
     // Encrypt the data
     $cipherText = mcrypt_encrypt($this->_cipherType, $key, $stringToEncrypt, $this->_cipherMode, $iv);
     // Prepend the IV to the ciphertext
     $cipherText = $iv . $cipherText;
     // Optionally pass the result through Base64 encoding
     if ($base64encoded) {
         $cipherText = base64_encode($cipherText);
     }
     // Return the result
     return $cipherText;
 }
Example #10
0
function gen_bytes($count)
{
    if (function_exists('random_bytes')) {
        return random_bytes($count);
    } else {
        if (function_exists('openssl_random_pseudo_bytes')) {
            return openssl_random_pseudo_bytes($count);
        } else {
            if (function_exists('mcrypt_create_iv')) {
                return mcrypt_create_iv($count);
            } else {
                if (is_readable('/dev/random')) {
                    $f = fopen("/dev/random", "rb");
                    $b = fread($f, $count);
                    fclose($f);
                    return $b;
                } else {
                    if (is_readable('/dev/urandom')) {
                        $f = fopen("/dev/urandom", "rb");
                        $rand = fread($f, $count);
                        fclose($f);
                        return $rand;
                    } else {
                        $rand = "";
                        for ($a = 0; $a < $count; $a++) {
                            $rand .= chr(mt_rand(0, 255));
                        }
                        return $rand;
                    }
                }
            }
        }
    }
}
 public function testHashVerify()
 {
     $iv = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
     $this->assertEquals(true, $this->passwordEncoder->verify($this->passwordEncoder->hash('password'), 'password'));
     $this->assertEquals(true, $this->passwordEncoder->verify($this->passwordEncoder->hash('password', $iv), 'password'));
     $this->assertEquals(false, $this->passwordEncoder->verify($this->passwordEncoder->hash('password'), 'notThePassword'));
 }
Example #12
0
 private function getToken($userID, $userName, $userRole)
 {
     $tokenId = base64_encode(mcrypt_create_iv(32));
     $issuedAt = time();
     $notBefore = $issuedAt + 10;
     $expire = $notBefore + 90000;
     $serverName = $_SERVER['SERVER_NAME'];
     /*
      * Create the token as an array
      */
     $payload = ['userID' => $userID, 'userName' => $userName, 'userRole' => $userRole];
     $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'user' => $payload];
     // Store key in local file, not in php
     $privateKey = $this->utils->readFile('private/apikey');
     $secretKey = base64_decode($privateKey);
     /*
      * Encode the array to a JWT string.
      * Second parameter is the key to encode the token.
      * 
      * The output string can be validated at http://jwt.io/
      */
     $jwt = JWT::encode($data, $secretKey, 'HS512');
     $unencodedArray = ['data' => $payload, 'token' => $jwt];
     echo json_encode($unencodedArray);
 }
Example #13
0
 /**
  * Encrypt data for security
  *
  * @param mixed $data
  * @return string
  */
 public static function encrypt($data)
 {
     // Don't do anything with empty data
     $data = trim($data);
     if (empty($data)) {
         return null;
     }
     // Check if encryption was turned off
     if (MagebridgeModelConfig::load('encryption') == 0) {
         return $data;
     }
     // Check if SSL is already in use, so encryption is not needed
     if (MagebridgeModelConfig::load('protocol') == 'https') {
         return $data;
     }
     // Check for mcrypt
     if (!function_exists('mcrypt_get_iv_size') || !function_exists('mcrypt_cfb')) {
         return $data;
     }
     // Generate a random key
     $random = str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
     $key = MageBridgeEncryptionHelper::getSaltedKey($random);
     try {
         $td = mcrypt_module_open(MCRYPT_CAST_256, '', 'ecb', '');
         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
         mcrypt_generic_init($td, $key, $iv);
         $encrypted = mcrypt_generic($td, $data);
         $encoded = MageBridgeEncryptionHelper::base64_encode($encrypted);
     } catch (Exception $e) {
         Mage::getSingleton('magebridge/debug')->error("Error while decrypting: " . $e->getMessage());
         return null;
     }
     return $encoded . '|=|' . $random;
 }
Example #14
0
 /**
  * Encrypt a string.
  *
  * @param string $str String to encrypt.
  *
  * @return string
  */
 public function encrypt($str)
 {
     $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
     $str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $str, MCRYPT_MODE_CBC, $iv);
     $str = $iv . $str;
     return base64_encode($str);
 }
 /**
  * funkce obstaravajici prihlaseni uzivatele
  */
 private function login()
 {
     $this->database = $this->context->getService("database.default.context");
     $data = Nette\Utils\Json::decode($this->request->getParameters()["data"]);
     $authenticator = new LoginAuthenticator($this->database);
     $user = $this->getUser();
     $user->setAuthenticator($authenticator);
     try {
         $user->login($data->username, $data->password);
     } catch (Nette\Security\AuthenticationException $e) {
         $error["err"] = true;
         $error["message"] = $e->getMessage();
         return $error;
     }
     $userIdent = (array) $user->getIdentity()->getData();
     $tokenId = base64_encode(mcrypt_create_iv(32));
     $issuedAt = time();
     $notBefore = $issuedAt;
     $expire = $notBefore + 60 * 60;
     $serverName = "lolnotepad";
     $token = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => $userIdent];
     $key = base64_decode(KEY);
     $jwt = JWT::encode($token, $key, 'HS256');
     return $jwt;
 }
 public function computeSign($sharedSecret)
 {
     if (!$this->isValid) {
         throw new Exception(__METHOD__ . ": Message was not validated.");
     }
     try {
         $bytesHash = sha1($this->GetSignatureBase(), true);
         $sharedSecret = pack('H*', $sharedSecret);
         // uprava pre PHP < 5.0
         if (strlen($bytesHash) != 20) {
             $bytes = "";
             for ($i = 0; $i < strlen($bytesHash); $i += 2) {
                 $bytes .= chr(hexdec(substr($str, $i, 2)));
             }
             $bytesHash = $bytes;
         }
         $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_ECB, "");
         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND);
         mcrypt_generic_init($cipher, $sharedSecret, $iv);
         $text = $this->pad(substr($bytesHash, 0, 16), mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
         $bytesSign = mcrypt_generic($cipher, $text);
         mcrypt_generic_deinit($cipher);
         mcrypt_module_close($cipher);
         $sign = substr(strtoupper(bin2hex($bytesSign)), 0, 32);
     } catch (Exception $e) {
         return false;
     }
     return $sign;
 }
Example #17
0
 public function encrypt_string($input, $key)
 {
     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $input, MCRYPT_MODE_CBC, $iv);
     return base64_encode($iv . $cipher);
 }
Example #18
0
 public function decrypt($data)
 {
     // if($this->input->ip_address() == '10.52.66.172') {
     // var_dump($data);
     // die;
     // }
     $key = "secret";
     $td = mcrypt_module_open(MCRYPT_DES, "", MCRYPT_MODE_ECB, "");
     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     mcrypt_generic_init($td, $key, $iv);
     // mcrypt_generic_deinit($td);
     // if($this->input->ip_address() == '10.52.66.172') {
     // var_dump($data);
     // die;
     // }
     $data = mdecrypt_generic($td, base64_decode($data));
     // if($this->input->ip_address() == '10.52.66.172') {
     // var_dump($data);
     // die;
     // }
     mcrypt_generic_deinit($td);
     if (substr($data, 0, 1) != '!') {
         return false;
     }
     $data = substr($data, 1, strlen($data) - 1);
     return unserialize($data);
 }
Example #19
0
function hash_pwd($pwd)
{
    $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
    $salt = sprintf("\$2a\$%02d\$", 10) . $salt;
    $hash = crypt($pwd, $salt);
    return $hash;
}
Example #20
0
 function enc_str($str, $key = '1234567890!')
 {
     $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
     $encrypted = base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hash('sha256', $key, true), $str, MCRYPT_MODE_CBC, $iv));
     echo "ENCRYPT> {$str} -> \${$encrypted}\n";
     return $encrypted;
 }
Example #21
0
function decrypt($encrypted_string, $encryption_key)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, base64_decode($encrypted_string), MCRYPT_MODE_ECB, $iv);
    return $decrypted_string;
}
Example #22
0
 /**
  * @param string $plain
  * @return string garble
  */
 public function encrypt($plain)
 {
     $iv = mcrypt_create_iv($this->ivSize, MCRYPT_DEV_URANDOM);
     $crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $plain, MCRYPT_MODE_CBC, $iv);
     $garble = base64_encode($iv . $crypt);
     return $garble;
 }
Example #23
0
 /**
  * Initialize mcrypt module
  *
  * @param string $key cipher private key
  * @return Varien_Crypt_Mcrypt
  */
 public function init($key)
 {
     if (!$this->getCipher()) {
         $this->setCipher(MCRYPT_BLOWFISH);
     }
     if (!$this->getMode()) {
         $this->setMode(MCRYPT_MODE_ECB);
     }
     $this->setHandler(mcrypt_module_open($this->getCipher(), '', $this->getMode(), ''));
     if (!$this->getInitVector()) {
         if (MCRYPT_MODE_CBC == $this->getMode()) {
             $this->setInitVector(substr(md5(mcrypt_create_iv(mcrypt_enc_get_iv_size($this->getHandler()), MCRYPT_RAND)), -mcrypt_enc_get_iv_size($this->getHandler())));
         } else {
             $this->setInitVector(mcrypt_create_iv(mcrypt_enc_get_iv_size($this->getHandler()), MCRYPT_RAND));
         }
     }
     $maxKeySize = mcrypt_enc_get_key_size($this->getHandler());
     if (strlen($key) > $maxKeySize) {
         // strlen() intentionally, to count bytes, rather than characters
         $this->setHandler(null);
         throw new Varien_Exception('Maximum key size must be smaller ' . $maxKeySize);
     }
     mcrypt_generic_init($this->getHandler(), $key, $this->getInitVector());
     return $this;
 }
Example #24
0
 public function SetEncryption()
 {
     $this->iv = mcrypt_create_iv(mcrypt_get_iv_size(self::ENCRYPTION_TYPE, self::ENCRYPTION_MODE), MCRYPT_DEV_URANDOM);
     $this->encryptionKey = strrev(Config::Init($this->app)->Get(\Puzzlout\Framework\Enums\AppSettingKeys::EncryptionKey));
     $this->hashSalt = strrev(Config::Init($this->app)->Get(\Puzzlout\Framework\Enums\AppSettingKeys::PasswordSalt));
     return $this;
 }
Example #25
0
 /**
  * Returns a JSON string encoding the encrypted password and the used salt.
  *
  * @param string $password The password to encrypt.
  * @param string $salt Optional. The salt to use.
  * @return string
  * @see encryptPassword()
  * @see verifyPassword()
  */
 public static function getPasswordHash($password, $salt = null)
 {
     if ($salt === null) {
         $salt = bin2hex(mcrypt_create_iv(8, MCRYPT_DEV_URANDOM)) . time();
     }
     return json_encode(array($salt, self::encryptPassword($password, $salt)));
 }
Example #26
0
 /**
  * Generate settings file
  */
 public function generateSettingsFile($database_server, $database_login, $database_password, $database_name, $database_prefix, $database_engine)
 {
     // Check permissions for settings file
     if (file_exists(_PS_ROOT_DIR_ . '/' . self::SETTINGS_FILE) && !is_writable(_PS_ROOT_DIR_ . '/' . self::SETTINGS_FILE)) {
         $this->setError($this->language->l('%s file is not writable (check permissions)', self::SETTINGS_FILE));
         return false;
     } elseif (!file_exists(_PS_ROOT_DIR_ . '/' . self::SETTINGS_FILE) && !is_writable(_PS_ROOT_DIR_ . '/' . dirname(self::SETTINGS_FILE))) {
         $this->setError($this->language->l('%s folder is not writable (check permissions)', dirname(self::SETTINGS_FILE)));
         return false;
     }
     // Generate settings content and write file
     $settings_constants = array('_DB_SERVER_' => $database_server, '_DB_NAME_' => $database_name, '_DB_USER_' => $database_login, '_DB_PASSWD_' => $database_password, '_DB_PREFIX_' => $database_prefix, '_MYSQL_ENGINE_' => $database_engine, '_PS_CACHING_SYSTEM_' => 'CacheMemcache', '_PS_CACHE_ENABLED_' => '0', '_MEDIA_SERVER_1_' => '', '_MEDIA_SERVER_2_' => '', '_MEDIA_SERVER_3_' => '', '_COOKIE_KEY_' => Tools::passwdGen(56), '_COOKIE_IV_' => Tools::passwdGen(8), '_PS_CREATION_DATE_' => date('Y-m-d'), '_PS_VERSION_' => _PS_INSTALL_VERSION_);
     // If mcrypt is activated, add Rijndael 128 configuration
     if (function_exists('mcrypt_encrypt')) {
         $settings_constants['_RIJNDAEL_KEY_'] = Tools::passwdGen(mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
         $settings_constants['_RIJNDAEL_IV_'] = base64_encode(mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND));
     }
     $settings_content = "<?php\n";
     foreach ($settings_constants as $constant => $value) {
         $settings_content .= "define('{$constant}', '" . str_replace('\'', '\\\'', $value) . "');\n";
     }
     if (!file_put_contents(_PS_ROOT_DIR_ . '/' . self::SETTINGS_FILE, $settings_content)) {
         $this->setError($this->language->l('Cannot write settings file'));
         return false;
     }
     return true;
 }
Example #27
0
 /**
  * PRNG generator based on security principles 
  * at http://phpsecurity.readthedocs.org/en/latest/Insufficient-Entropy-For-Random-Values.html 
  * 
  * @param mixed $length 
  * @param mixed $strong 
  * @access public
  * @return void
  */
 public function getBytes($length, $strong = false)
 {
     $bytes = '';
     if (function_exists('openssl_random_pseudo_bytes')
         && (version_compare(PHP_VERSION, '5.3.4') >= 0
         || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
     ) {
         $bytes = openssl_random_pseudo_bytes($length, $usable);
         if (true === $usable) {
             return $bytes;
         }
     }
     if (function_exists('mcrypt_create_iv')
         && (version_compare(PHP_VERSION, '5.3.7') >= 0
         || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
     ) {
         $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
         if ($bytes !== false && strlen($bytes) === $length) {
             return $bytes;
         }
     }
     $checkAlternatives = (file_exists('/dev/urandom') && is_readable('/dev/urandom'))
         || class_exists('\\COM', false);
     if (true === $strong && false === $checkAlternatives) {
         throw new \Exception(
             'Unable to generate sufficiently strong random bytes due to a lack ',
             'of sources with sufficient entropy'
         );
     }
     $generator = $this->getAlternativeGenerator();
     return $generator->generate($length);
 }
Example #28
0
 public static function generateSalt()
 {
     $salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
     $salt = substr(base64_encode($salt), 0, 22);
     $salt = str_replace('+', '.', $salt);
     return $salt;
 }
Example #29
0
 function decrypt($text, $salt)
 {
     if (!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt')) {
         return $text;
     }
     return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
 }
Example #30
0
 /**
  * Encrypt a value
  *
  * @param mixed  $varValue The value to encrypt
  * @param string $strKey   An optional encryption key
  *
  * @return string The encrypted value
  */
 public static function encrypt($varValue, $strKey = null)
 {
     // Recursively encrypt arrays
     if (is_array($varValue)) {
         foreach ($varValue as $k => $v) {
             $varValue[$k] = static::encrypt($v);
         }
         return $varValue;
     } elseif ($varValue == '') {
         return '';
     }
     // Initialize the module
     if (static::$resTd === null) {
         static::initialize();
     }
     if (!$strKey) {
         $strKey = \Config::get('encryptionKey');
     }
     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size(static::$resTd), MCRYPT_RAND);
     mcrypt_generic_init(static::$resTd, md5($strKey), $iv);
     $strEncrypted = mcrypt_generic(static::$resTd, $varValue);
     $strEncrypted = base64_encode($iv . $strEncrypted);
     mcrypt_generic_deinit(static::$resTd);
     return $strEncrypted;
 }