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);
 }
示例#2
1
文件: security.php 项目: svlt/back
 /**
  * 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.');
 }
示例#3
0
 /**
  * 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;
 }
示例#4
0
 /**
  * @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;
     }
 }
示例#5
0
 /**
  * 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;
 }
示例#6
0
 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();
 }
示例#7
0
文件: Str.php 项目: sndsgd/util
 /**
  * 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);
 }
示例#8
0
 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]);
 }
 /**
  * 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));
 }
示例#10
0
 private function getSalt()
 {
     $salt = sprintf('$2a$%02d$', $this->rounds);
     $bytes = random_bytes(16);
     $salt .= $this->encodeBytes($bytes);
     return $salt;
 }
示例#11
0
 /**
  * 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);
 }
示例#12
0
 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));
         }
     }
 }
示例#13
0
 /**
  * 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;
 }
示例#14
0
 /**
  * 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;
 }
示例#15
0
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);
}
示例#16
0
 /**
  * POST | This handles the registration with validation.
  *
  * @return mixed
  */
 public function storeRegistrationForm()
 {
     $inputs = request()->get();
     $validator = new RegistrationValidator();
     $validation = $validator->validate($inputs);
     if (count($validation)) {
         session()->set('input', $inputs);
         return redirect()->to(url()->previous())->withError(RegistrationValidator::toHtml($validation));
     }
     $token = bin2hex(random_bytes(100));
     $connection = db()->connection();
     try {
         $connection->begin();
         $user = new User();
         $success = $user->create(['email' => $inputs['email'], 'password' => security()->hash($inputs['password']), 'token' => $token]);
         if ($success === false) {
             throw new Exception('It seems we can\'t create an account, ' . 'please check your access credentials!');
         }
         queue(\Components\Queue\Email::class, ['function' => 'registeredSender', 'template' => 'emails.registered-inlined', 'to' => $inputs['email'], 'url' => route('activateUser', ['token' => $token]), 'subject' => 'You are now registered, activation is required.']);
         $connection->commit();
     } catch (TransactionFailed $e) {
         $connection->rollback();
         throw $e;
     } catch (Exception $e) {
         $connection->rollback();
         throw $e;
     }
     return redirect()->to(route('showLoginForm'))->withSuccess(lang()->get('responses/register.creation_success'));
 }
示例#17
0
 /**
  * @param Session $session
  * @param RequestEnvelope $env
  * @param Request[] $reqs
  * @throws Exception
  */
 public static function sign(Session $session, RequestEnvelope $env, $reqs)
 {
     if (!$session->hasAuthTicket()) {
         return;
     }
     $location = $session->getLocation();
     $rawTicket = $session->getAuthTicket()->toBinary();
     $microTime = MicroTime::get();
     $protoSignature = new ProtoSignature();
     $protoSignature->setTimestampSinceStart($microTime - $session->getStartMicroTime());
     // TODO: LocationFix
     // TODO: AndroidGpsInfo
     // TODO: SensorInfo
     // TODO: DeviceInfo
     // TODO: ActivityStatus
     $protoSignature->setLocationHash1(self::generateLocation1($rawTicket, $location));
     $protoSignature->setLocationHash2(self::generateLocation2($location));
     $protoSignature->setSessionHash($session->getSessionHash());
     $protoSignature->setTimestamp($microTime);
     foreach ($reqs as $req) {
         $protoSignature->addRequestHash(self::generateRequestHash($rawTicket, $req->toProto()->toStream()->getContents()));
     }
     $protoSignature->setUnknown25(9.909701338899655E+18);
     $uk6 = new Unknown6();
     $uk6->setRequestType(6);
     $uk2 = new Unknown2();
     $enc = Encrypt::encrypt($protoSignature->toStream()->getContents(), random_bytes(32));
     $uk2->setEncryptedSignature($enc);
     $uk6->setUnknown2($uk2);
     $env->setUnknown6($uk6);
     $session->getLogger()->debug("Signed request: " . strlen($enc) . " bytes");
 }
 /**
  * Generate a new recovery access.
  * Can receives a own expected password or will generate a random 12 characters password.
  *
  * @param string|null $password Password to use.
  *
  * @return self
  */
 public static function generate($password = null)
 {
     if ($password === null) {
         $password = random_bytes(12);
     }
     return new self($password);
 }
示例#19
0
 public function __construct(int $length = 7)
 {
     if (!is_int($length) || $length > 32 || $length < 1) {
         throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
     }
     $this->uid = substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length);
 }
示例#20
0
 static function getString($length = 40)
 {
     if (function_exists('random_bytes')) {
         return bin2hex(random_bytes($length));
     }
     return self::hex2setstring(bin2hex((new RandomLibFactory())->getMediumStrengthGenerator()->generate($length)));
 }
示例#21
0
 /**
  * @depends testGeneratePublicPrivateKeys
  */
 public function testEncryptDecrypt(array $keys)
 {
     $plaintext = random_bytes(64);
     $ciphertext = $this->crypt->encrypt($plaintext, $keys['public']);
     $result = $this->crypt->decrypt($ciphertext, $keys['private']);
     $this->assertEquals($plaintext, $result);
 }
示例#22
0
 private function generateAuthorizationHeader(Request $request)
 {
     $oauth = ['oauth_consumer_key' => $this->appCredentials->consumerKey(), 'oauth_nonce' => md5(random_bytes(32)), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => (string) time(), 'oauth_version' => '1.0A', 'oauth_token' => $this->oauthCredentials->accessToken()];
     $encodedParams = [];
     foreach (array_merge($oauth, $this->getParameters($request)) as $k => $v) {
         $encodedParams[$this->encodeRfc3986($k)] = $this->encodeRfc3986($v);
     }
     ksort($encodedParams);
     $queryParams = [];
     foreach ($encodedParams as $k => $v) {
         $queryParams[] = "{$k}={$v}";
     }
     $encodedMethod = $this->encodeRfc3986(strtoupper($request->getMethod() ?? 'GET'));
     $encodedUrl = $this->encodeRfc3986($this->getNormalizedUrl($request));
     $encodedParameters = $this->encodeRfc3986(implode('&', $queryParams));
     $signatureBase = "{$encodedMethod}&{$encodedUrl}&{$encodedParameters}";
     $key = $this->encodeRfc3986($this->appCredentials->consumerSecret()) . '&' . $this->encodeRfc3986($this->oauthCredentials->accessSecret());
     $signature = base64_encode(hash_hmac('sha1', $signatureBase, $key, true));
     $oauth['oauth_signature'] = $this->encodeRfc3986($signature);
     $output = 'OAuth realm="",';
     foreach ($oauth as $k => $v) {
         $output .= "{$k}=\"{$v}\",";
     }
     $output = trim($output, ',');
     return $output;
 }
示例#23
0
 function random_int($min = PHP_INT_MIN, $max = PHP_INT_MAX)
 {
     if ($min >= $max) {
         trigger_error('Minimum value must be less than the maximum value', E_USER_WARNING);
         return false;
     }
     $umax = $max - $min;
     $result = random_bytes(PHP_INT_SIZE);
     if ($result === false) {
         return false;
     }
     $ULONG_MAX = PHP_INT_MAX - PHP_INT_MIN;
     $result = hexdec(bin2hex($result));
     if ($umax === $ULONG_MAX) {
         return intval($result);
     }
     $umax++;
     if (($umax & $umax - 1) != 0) {
         $limit = $ULONG_MAX - fmod($ULONG_MAX, $umax) - 1;
         while ($result > $limit) {
             $result = random_bytes(PHP_INT_SIZE);
             if ($result === false) {
                 return false;
             }
             $result = hexdec(bin2hex($result));
         }
     }
     return intval(fmod($result, $umax) + $min);
 }
 /**
  * {@inheritdoc}
  */
 protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token)
 {
     $series = base64_encode(random_bytes(64));
     $tokenValue = base64_encode(random_bytes(64));
     $this->tokenProvider->createNewToken(new PersistentToken(get_class($user = $token->getUser()), $user->getUsername(), $series, $tokenValue, new \DateTime()));
     $response->headers->setCookie(new Cookie($this->options['name'], $this->encodeCookie(array($series, $tokenValue)), time() + $this->options['lifetime'], $this->options['path'], $this->options['domain'], $this->options['secure'], $this->options['httponly']));
 }
 /**
  * Hash a password with PBKDF2
  * 
  * @param string $password
  * @return string
  */
 public static function create_hash($password)
 {
     // format: algorithm:iterations:outputSize:salt:pbkdf2output
     if (!\is_string($password)) {
         throw new InvalidArgumentException("create_hash(): Expected a string");
     }
     if (\function_exists('random_bytes')) {
         try {
             $salt_raw = \random_bytes(self::PBKDF2_SALT_BYTES);
         } catch (Error $e) {
             $salt_raw = false;
         } catch (Exception $e) {
             $salt_raw = false;
         } catch (TypeError $e) {
             $salt_raw = false;
         }
     } else {
         $salt_raw = \mcrypt_create_iv(self::PBKDF2_SALT_BYTES, MCRYPT_DEV_URANDOM);
     }
     if ($salt_raw === false) {
         throw new CannotPerformOperationException("Random number generator failed. Not safe to proceed.");
     }
     $PBKDF2_Output = self::pbkdf2(self::PBKDF2_HASH_ALGORITHM, $password, $salt_raw, self::PBKDF2_ITERATIONS, self::PBKDF2_OUTPUT_BYTES, true);
     return self::PBKDF2_HASH_ALGORITHM . ":" . self::PBKDF2_ITERATIONS . ":" . self::PBKDF2_OUTPUT_BYTES . ":" . \base64_encode($salt_raw) . ":" . \base64_encode($PBKDF2_Output);
 }
示例#26
0
文件: Random.php 项目: jivoo/core
 /**
  *
  * @param int $n
  * @return string
  * @codeCoverageIgnore
  */
 private static function php7Bytes($n)
 {
     if (!function_exists('random_bytes')) {
         return null;
     }
     return random_bytes($n);
 }
示例#27
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Unknown cipher method
  */
 public function testInvalidCipher()
 {
     $privateKey = CurveFactory::getGeneratorByName('nistp256')->getPrivateKeyFrom(gmp_init(100));
     $iv = random_bytes(16);
     $method = 'not-a-known-cipher';
     new EncryptedPrivateKey($privateKey, $method, $iv);
 }
示例#28
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;
                    }
                }
            }
        }
    }
}
示例#29
0
 /**
  * Creates and returns an input with a long, random, name in hex to be
  * designated the "any" / "wildcard" state, or, if such an input has
  * already been created, returns it.
  *
  * @return Input
  */
 public static function any() : Input
 {
     if (!isset(self::$wildcard)) {
         self::$wildcard = new self(bin2hex(random_bytes(20)));
     }
     return self::$wildcard;
 }
示例#30
-1
 public function testOutput()
 {
     $bytes = array(random_bytes(12), random_bytes(64), random_bytes(64), random_bytes(1.5));
     $this->assertTrue(strlen(bin2hex($bytes[0])) === 24);
     $this->assertTrue(strlen(bin2hex($bytes[3])) === 2);
     // This should never generate identical byte strings
     $this->assertFalse($bytes[1] === $bytes[2]);
     try {
         $x = random_bytes(~PHP_INT_MAX - 1000000000);
         $this->assertTrue(false);
     } catch (TypeError $ex) {
         $this->assertTrue(true);
     } catch (Error $ex) {
         $this->assertTrue(true);
     } catch (Exception $ex) {
         $this->assertTrue(true);
     }
     try {
         $x = random_bytes(PHP_INT_MAX + 1000000000);
         $this->assertTrue(false);
     } catch (TypeError $ex) {
         $this->assertTrue(true);
     } catch (Error $ex) {
         $this->assertTrue(true);
     } catch (Exception $ex) {
         $this->assertTrue(true);
     }
 }