当前位置: 首页>>代码示例>>PHP>>正文


PHP random_bytes函数代码示例

本文整理汇总了PHP中random_bytes函数的典型用法代码示例。如果您正苦于以下问题:PHP random_bytes函数的具体用法?PHP random_bytes怎么用?PHP random_bytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了random_bytes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: process

 public function process(ServerRequestInterface $request, DelegateInterface $delegate) : ResponseInterface
 {
     /* @var \PSR7Session\Session\SessionInterface $session */
     $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
     // Generate csrf token
     if (!$session->get('csrf')) {
         $session->set('csrf', md5(random_bytes(32)));
     }
     // Generate form and inject csrf token
     $form = new FormFactory($this->template->render('app::contact-form', ['token' => $session->get('csrf')]), $this->inputFilterFactory);
     // Validate form
     $validationResult = $form->validateRequest($request);
     if ($validationResult->isValid()) {
         // Get filter submitted values
         $data = $validationResult->getValues();
         $this->logger->notice('Sending contact mail to {from} <{email}> with subject "{subject}": {body}', $data);
         // Create the message
         $message = new Message();
         $message->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']);
         $this->mailTransport->send($message);
         // Display thank you page
         return new HtmlResponse($this->template->render('app::contact-thank-you'), 200);
     }
     // Display form and inject error messages and submitted values
     return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200);
 }
开发者ID:xtreamwayz,项目名称:xtreamwayz.com,代码行数:26,代码来源:ContactAction.php

示例2: randBytes

 /**
  * Generate secure random bytes
  * @param  int $length
  * @return string
  */
 static function randBytes($length = 256)
 {
     if (function_exists('random_bytes')) {
         // PHP 7
         return random_bytes($length);
     }
     if (function_exists('openssl_random_pseudo_bytes')) {
         // OpenSSL
         $result = openssl_random_pseudo_bytes($length, $strong);
         if (!$strong) {
             throw new Exception('OpenSSL failed to generate secure randomness.');
         }
         return $result;
     }
     if (file_exists('/dev/urandom') && is_readable('/dev/urandom')) {
         // Unix
         $fh = fopen('/dev/urandom', 'rb');
         if ($fh !== false) {
             $result = fread($fh, $length);
             fclose($fh);
             return $result;
         }
     }
     throw new Exception('No secure random source available.');
 }
开发者ID:svlt,项目名称:back,代码行数:30,代码来源:security.php

示例3: getName

 /**
  * Get file name.
  *
  * @return string
  */
 public function getName() : string
 {
     if (empty($this->name)) {
         $this->name = 'prun.' . microtime(true) . '_' . bin2hex(random_bytes(16)) . '.json';
     }
     return $this->name;
 }
开发者ID:arabcoders,项目名称:profiler,代码行数:12,代码来源:FileHandler.php

示例4: createOrUpdate

 /**
  * @param  int                                       $titleId          customer title id (from customer_title table)
  * @param  string                                    $firstname        customer first name
  * @param  string                                    $lastname         customer last name
  * @param  string                                    $address1         customer address
  * @param  string                                    $address2         customer adress complement 1
  * @param  string                                    $address3         customer adress complement 2
  * @param  string                                    $phone            customer phone number
  * @param  string                                    $cellphone        customer cellphone number
  * @param  string                                    $zipcode          customer zipcode
  * @param  string                                    $city
  * @param  int                                       $countryId        customer country id (from Country table)
  * @param  string                                    $email            customer email, must be unique
  * @param  string                                    $plainPassword    customer plain password, hash is made calling setPassword method. Not mandatory parameter but an exception is thrown if customer is new without password
  * @param  string                                    $lang
  * @param  int                                       $reseller
  * @param  null                                      $sponsor
  * @param  int                                       $discount
  * @param  null                                      $company
  * @param  null                                      $ref
  * @param  bool                                      $forceEmailUpdate true if the email address could be updated.
  * @param  int                                       $stateId          customer state id (from State table)
  * @throws \Exception
  * @throws \Propel\Runtime\Exception\PropelException
  */
 public function createOrUpdate($titleId, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $countryId, $email = null, $plainPassword = null, $lang = null, $reseller = 0, $sponsor = null, $discount = 0, $company = null, $ref = null, $forceEmailUpdate = false, $stateId = null)
 {
     $this->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setEmail($email, $forceEmailUpdate)->setPassword($plainPassword)->setReseller($reseller)->setSponsor($sponsor)->setDiscount($discount)->setRef($ref);
     if (!is_null($lang)) {
         $this->setLangId($lang);
     }
     $con = Propel::getWriteConnection(CustomerTableMap::DATABASE_NAME);
     $con->beginTransaction();
     try {
         if ($this->isNew()) {
             $address = new Address();
             $address->setLabel(Translator::getInstance()->trans("Main address"))->setCompany($company)->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setAddress1($address1)->setAddress2($address2)->setAddress3($address3)->setPhone($phone)->setCellphone($cellphone)->setZipcode($zipcode)->setCity($city)->setCountryId($countryId)->setStateId($stateId)->setIsDefault(1);
             $this->addAddress($address);
             if (ConfigQuery::isCustomerEmailConfirmationEnable()) {
                 $this->setConfirmationToken(bin2hex(random_bytes(32)));
             }
         } else {
             $address = $this->getDefaultAddress();
             $address->setCompany($company)->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setAddress1($address1)->setAddress2($address2)->setAddress3($address3)->setPhone($phone)->setCellphone($cellphone)->setZipcode($zipcode)->setCity($city)->setCountryId($countryId)->setStateId($stateId)->save($con);
         }
         $this->save($con);
         $con->commit();
     } catch (PropelException $e) {
         $con->rollBack();
         throw $e;
     }
 }
开发者ID:vigourouxjulien,项目名称:thelia,代码行数:52,代码来源:Customer.php

示例5: random

 /**
  * Generate a "random" alpha-numeric string.
  *
  * From Laravel
  * @param  int $length
  * @return string
  */
 public static function random($length = 16)
 {
     $length = (int) $length;
     if ($length <= 0) {
         throw new \InvalidArgumentException(__t('random_length_must_be_greater_then_zero'));
     }
     if (function_exists('random_bytes')) {
         try {
             $random = random_bytes($length);
         } catch (\Exception $e) {
             $random = static::randomString($length);
         }
     } else {
         if (function_exists('openssl_random_pseudo_bytes')) {
             $string = '';
             while (($len = strlen($string)) < $length) {
                 $size = $length - $len;
                 $bytes = openssl_random_pseudo_bytes($size);
                 $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
             }
             $random = $string;
         } else {
             $random = static::randomString($length);
         }
     }
     return $random;
 }
开发者ID:YounessTayer,项目名称:directus,代码行数:34,代码来源:StringUtils.php

示例6: testShortQueries

 public function testShortQueries()
 {
     try {
         $db = Database::factory($this->getConfig());
     } catch (DBException $ex) {
         $this->markTestSkipped('Database not configured');
         return;
     }
     $this->assertTrue($db instanceof Database);
     $db->beginTransaction();
     $db->insert('test_values', ['name' => 'abc', 'foo' => true]);
     $db->insert('test_values', ['name' => 'def', 'foo' => false]);
     $db->insert('test_values', ['name' => 'ghijklmnopqrstuvwxyz', 'foo' => true]);
     $row = $db->row('SELECT * FROM test_values WHERE NOT foo');
     $this->assertTrue(\is_array($row));
     $name = $row['name'];
     $db->rollBack();
     $db->beginTransaction();
     $db->insert('test_values', ['name' => 'abcdef', 'foo' => true]);
     $db->insert('test_values', ['name' => 'GHI', 'foo' => false]);
     $db->insert('test_values', ['name' => 'jklmnopqrstuvwxyz', 'foo' => true]);
     $rows = $db->run('SELECT * FROM test_values WHERE NOT foo');
     $this->assertTrue(\count($rows) === 1);
     $count = $db->cell('SELECT count(*) FROM test_values WHERE name = ?', 'GHI');
     $this->assertEquals(\count($rows), $count);
     $count = $db->cell('SELECT count(*) FROM test_values WHERE name = ?', 'def');
     $this->assertNotEquals(\count($rows), $count);
     $value = Base64UrlSafe::encode(\random_bytes(33));
     $stored = $db->insertGet('test_values', ['name' => $value, 'foo' => true], 'name');
     $this->assertSame($value, $stored);
     $db->commit();
 }
开发者ID:paragonie,项目名称:airship,代码行数:32,代码来源:PostgresqlTest.php

示例7: random

 /**
  * Get a random string
  *
  * @param int $length The length of the resulting string
  * @return string
  */
 public static function random(int $length) : string
 {
     $byteLength = $length < 10 ? 10 : $length;
     $chars = base64_encode(random_bytes($byteLength));
     $chars = str_replace(["+", "/", "="], "", $chars);
     return substr($chars, 0, $length);
 }
开发者ID:sndsgd,项目名称:util,代码行数:13,代码来源:Str.php

示例8: testOutput

 public function testOutput()
 {
     $bytes = array(random_bytes(12), random_bytes(64), random_bytes(64));
     $this->assertTrue(strlen(bin2hex($bytes[0])) === 24);
     // This should never generate identical byte strings
     $this->assertFalse($bytes[1] === $bytes[2]);
 }
开发者ID:niyomja,项目名称:laravel_redis,代码行数:7,代码来源:RandomBytesTest.php

示例9: generateToken

 /**
  * Generate random identifier for CSRF token
  *
  * @return string
  */
 public static function generateToken()
 {
     if (function_exists('random_bytes')) {
         return bin2hex(random_bytes(32));
     }
     return bin2hex(openssl_random_pseudo_bytes(32));
 }
开发者ID:skipperbent,项目名称:simple-php-router,代码行数:12,代码来源:CsrfToken.php

示例10: getSalt

 private function getSalt()
 {
     $salt = sprintf('$2a$%02d$', $this->rounds);
     $bytes = random_bytes(16);
     $salt .= $this->encodeBytes($bytes);
     return $salt;
 }
开发者ID:ferchang,项目名称:downloader,代码行数:7,代码来源:class_bcrypt.php

示例11: issueToken

 /**
  * Generates a random API token for the user and persists it.
  *
  * @param User $user
  */
 public function issueToken(User $user)
 {
     $token = bin2hex(random_bytes(32));
     $user->setApiToken($token);
     $this->em->persist($user);
     $this->em->flush($user);
 }
开发者ID:Briareos,项目名称:Undine,代码行数:12,代码来源:ApiTokenManager.php

示例12: testRandomString

 public function testRandomString()
 {
     $str = Base64UrlSafe::encode(\random_bytes(32));
     $sets = [[true, true], [true, false], [false, true], [false, false]];
     foreach ($sets as $set) {
         $hidden = new HiddenString($str, $set[0], $set[1]);
         ob_start();
         var_dump($hidden);
         $dump = ob_get_clean();
         $this->assertFalse(\strpos($dump, $str));
         $print = \print_r($hidden, true);
         $this->assertFalse(\strpos($print, $str));
         $cast = (string) $hidden;
         if ($set[0]) {
             $this->assertFalse(\strpos($cast, $str));
         } else {
             $this->assertNotFalse(\strpos($cast, $str));
         }
         $serial = \serialize($hidden);
         if ($set[1]) {
             $this->assertFalse(\strpos($serial, $str));
         } else {
             $this->assertNotFalse(\strpos($serial, $str));
         }
     }
 }
开发者ID:paragonie,项目名称:halite,代码行数:26,代码来源:HiddenStringTest.php

示例13: randBytes

 /**
  * Return a random strings of $length bytes
  *
  * @param  integer $length
  * @param  boolean $strong
  * @return string
  */
 public static function randBytes($length, $strong = false)
 {
     $length = (int) $length;
     if ($length <= 0) {
         return false;
     }
     if (function_exists('random_bytes')) {
         // available in PHP 7
         return random_bytes($length);
     }
     if (function_exists('mcrypt_create_iv')) {
         $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
         if ($bytes !== false && strlen($bytes) === $length) {
             return $bytes;
         }
     }
     if (file_exists('/dev/urandom') && is_readable('/dev/urandom')) {
         $frandom = fopen('/dev/urandom', 'r');
         if ($frandom !== false) {
             return fread($frandom, $length);
         }
     }
     if (true === $strong) {
         throw new Zend_Crypt_Exception('This PHP environment doesn\'t support secure random number generation. ' . 'Please consider installing the OpenSSL and/or Mcrypt extensions');
     }
     $rand = '';
     for ($i = 0; $i < $length; $i++) {
         $rand .= chr(mt_rand(0, 255));
     }
     return $rand;
 }
开发者ID:0svald,项目名称:icingaweb2,代码行数:38,代码来源:Math.php

示例14: fire

 /**
  * Execute the start command, which will start a new hangar session.
  *
  * @param array $args
  * @return bool
  */
 public function fire(array $args = []) : bool
 {
     if (\is_readable(AIRSHIP_LOCAL_CONFIG . '/hangar.session.json')) {
         if (\count($args) > 0) {
             if ($args[0] !== '--force') {
                 echo 'There is already an active session!';
                 return false;
             }
             $size = \filesize(AIRSHIP_LOCAL_CONFIG . '/hangar.session.json');
             \file_put_contents(AIRSHIP_LOCAL_CONFIG . '/hangar.session.json', \random_bytes($size));
             \unlink(AIRSHIP_LOCAL_CONFIG . '/hangar.session.json');
             \file_put_contents(AIRSHIP_LOCAL_CONFIG . '/hangar.session.json', \json_encode(['dir' => \getcwd()], JSON_PRETTY_PRINT));
             \clearstatcache();
             return true;
         } else {
             echo 'There is already an active session!', "\n";
             echo 'To nuke the active session, run "hangar start --force"', "\n";
             \clearstatcache();
             return false;
         }
     }
     \file_put_contents(AIRSHIP_LOCAL_CONFIG . '/hangar.session.json', \json_encode(['dir' => \getcwd()], JSON_PRETTY_PRINT));
     echo '[', $this->c['green'], 'OK', $this->c[''], '] ', 'Session started: ', \getcwd(), "\n";
     \clearstatcache();
     return true;
 }
开发者ID:paragonie,项目名称:airship,代码行数:32,代码来源:Start.php

示例15: ldSetCredentials

function ldSetCredentials($login, $ARUserDir = "/system/users/")
{
    global $ARCurrent, $AR, $LD_NO_SESSION_SUPPORT;
    if ($LD_NO_SESSION_SUPPORT) {
        debug("ldSetCredentials({$login}): no session support");
        return;
    }
    if (!$ARUserDir || $ARUserDir == "") {
        $ARUserDir = "/system/users/";
    }
    // Make sure the login is lower case. Because of the
    // numerous checks on "admin".
    $login = strtolower($login);
    debug("ldSetCredentials({$login})", "object");
    if (!$ARCurrent->session) {
        ldStartSession();
    } else {
        /* use the same sessionid if the user didn't login before */
        ldStartSession($ARCurrent->session->id);
    }
    $ARCurrent->session->put("ARLogin", $login);
    $ARCurrent->session->put("ARUserDir", $ARUserDir, true);
    /* create the session key */
    $session_key = bin2hex(random_bytes(16));
    $ARCurrent->session->put("ARSessionKey", $session_key, true);
    $ARCurrent->session->put("ARSessionTimedout", 0, 1);
    /* now save our session */
    $ARCurrent->session->save();
    $cookies = (array) $_COOKIE["ARSessionCookie"];
    foreach ($cookies as $sessionid => $cookie) {
        if (!$AR->hideSessionIDfromURL) {
            if (!$ARCurrent->session->sessionstore->exists("/{$sessionid}/")) {
                $data = ldDecodeCookie($cookie);
                if (is_array($data)) {
                    // don't just kill it, it may be from another ariadne installation
                    if ($data['timestamp'] < time() - 86400) {
                        // but do kill it if it's older than one day
                        unset($cookie[$sessionid]);
                        setcookie("ARSessionCookie[" . $sessionid . "]", null);
                    }
                }
            }
        } else {
            // only 1 cookie allowed, unset all cookies
            if ($sessionid != $ARCurrent->session->id) {
                setcookie("ARSessionCookie[" . $sessionid . "]", null);
            }
        }
    }
    $data = array();
    $data['login'] = $login;
    $data['timestamp'] = time();
    $data['check'] = ldGenerateSessionKeyCheck();
    $cookie = ldEncodeCookie($data);
    $cookiename = "ARSessionCookie[" . $ARCurrent->session->id . "]";
    debug("setting cookie ()({$cookie})");
    header('P3P: CP="NOI CUR OUR"');
    $https = $_SERVER['HTTPS'] == 'on';
    setcookie($cookiename, $cookie, 0, '/', false, $https, true);
}
开发者ID:poef,项目名称:ariadne,代码行数:60,代码来源:loader.webdav.auth.php


注:本文中的random_bytes函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。