本文整理汇总了PHP中openssl_random_pseudo_bytes函数的典型用法代码示例。如果您正苦于以下问题:PHP openssl_random_pseudo_bytes函数的具体用法?PHP openssl_random_pseudo_bytes怎么用?PHP openssl_random_pseudo_bytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了openssl_random_pseudo_bytes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getRandomBytes
private function getRandomBytes($count)
{
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
// OpenSSL slow on Win
$bytes = openssl_random_pseudo_bytes($count);
}
if ($bytes === '' && @is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if (strlen($bytes) < $count) {
$bytes = '';
if ($this->randomState === null) {
$this->randomState = microtime();
if (function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for ($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
示例2: create_user
public function create_user($post)
{
// echo 'in the model create user';
// var_dump ($post);
// die();
$this->load->library('form_validation');
// $this->form_validation->set_eroor_delimiters('<p class="error">', '</p>');
$this->form_validation->set_rules('first_name', 'First Name', 'required|min_length[2]|alpha');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|min_length[2]|alpha');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|matches[pw_confirmation]');
$this->form_validation->set_rules('pw_confirmation', 'Password Confirmation', 'required');
//if validations pass create user
// otherwise display error messages
if ($this->form_validation->run() != false) {
// $salt = bin2hex(openssl_random_pseudo_bytes(22));
$first_name = $post['first_name'];
// echo $first_name;
// die();
$last_name = $post['last_name'];
$email = $post['email'];
$password = $post['password'];
$salt = bin2hex(openssl_random_pseudo_bytes(22));
$encrypted_password = md5($password . '' . $salt);
$query = "INSERT INTO users (first_name, last_name, email, encrypted_pw, salt, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
$this->db->query($query, array($first_name, $last_name, $email, $encrypted_password, $salt));
$this->db->insert_id();
// return 1;
} else {
$errors = validation_errors();
return $errors;
// var_dump($errors);
// die();
}
}
示例3: getBytes
/**
* 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);
}
示例4: twofactor_genkey
/**
* Generate Secret Key
* @return string
*/
function twofactor_genkey()
{
global $base32_enc;
// RFC 4226 recommends 160bits Secret Keys, that's 20 Bytes for the lazy ones.
$crypto = false;
$raw = "";
$x = -1;
while ($crypto == false || ++$x < 10) {
$raw = openssl_random_pseudo_bytes(20, $crypto);
}
// RFC 4648 Base32 Encoding without padding
$len = strlen($raw);
$bin = "";
$x = -1;
while (++$x < $len) {
$bin .= str_pad(base_convert(ord($raw[$x]), 10, 2), 8, '0', STR_PAD_LEFT);
}
$bin = str_split($bin, 5);
$ret = "";
$x = -1;
while (++$x < sizeof($bin)) {
$ret .= $base32_enc[base_convert(str_pad($bin[$x], 5, '0'), 2, 10)];
}
return $ret;
}
示例5: _check_csrf_token
function _check_csrf_token($user)
{
global $secret;
if (isset($_SERVER['HTTP_X_CSRF_TOKEN']) && $_SERVER['HTTP_X_CSRF_TOKEN']) {
$found_token = $_SERVER['HTTP_X_CSRF_TOKEN'];
} elseif (isset($_POST['csrf-token']) && $_POST['csrf-token']) {
$found_token = $_POST['csrf-token'];
} else {
$found_token = '';
}
if (isset($secret) && $secret) {
# if we have a secret keep csrf-token valid across logins
$csrf_hmac_secret = hash_pbkdf2('sha256', 'csrf_hmac', $secret, 100, 0, true);
$userinfo = base64_encode($user['emailaddress']) . ':' . base64_encode($user['password']);
$csrf_token = base64_encode(hash_hmac('sha256', $userinfo, $csrf_hmac_secret, true));
} else {
# without secret create new token for each session
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
}
if ($found_token === $csrf_token) {
global $current_user;
$current_user['has_csrf_token'] = true;
}
define('CSRF_TOKEN', $csrf_token);
header("X-CSRF-Token: {$csrf_token}");
}
示例6: hash
/**
* 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;
}
示例7: generateRandomString
/**
* Generate a random string by using openssl, dev/urandom or random
* @param int $length optional length of the string
* @return string random string
* @author Benjamin BALET <benjamin.balet@gmail.com>
*/
private function generateRandomString($length = 10)
{
if (function_exists('openssl_random_pseudo_bytes')) {
$rnd = openssl_random_pseudo_bytes($length, $strong);
if ($strong === TRUE) {
return base64_encode($rnd);
}
}
$sha = '';
$rnd = '';
if (file_exists('/dev/urandom')) {
$fp = fopen('/dev/urandom', 'rb');
if ($fp) {
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($fp, 0);
}
$sha = fread($fp, $length);
fclose($fp);
}
}
for ($i = 0; $i < $length; $i++) {
$sha = hash('sha256', $sha . mt_rand());
$char = mt_rand(0, 62);
$rnd .= chr(hexdec($sha[$char] . $sha[$char + 1]));
}
return base64_encode($rnd);
}
示例8: gen_bytes
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;
}
}
}
}
}
}
示例9: createNewAccountEntry
protected function createNewAccountEntry(User $user)
{
$newAccount = new NewAccount();
$newAccount->user_id = $user->id;
$newAccount->create_on = new \DateTime();
$newAccount->token = bin2hex(openssl_random_pseudo_bytes($bits));
}
示例10: encrypt
/**
* Encrypt a value using AES-256.
*
* *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
* Any trailing null bytes will be removed on decryption due to how PHP pads messages
* with nulls prior to encryption.
*
* @param string $plain The value to encrypt.
* @param string $key The 256 bit/32 byte key to use as a cipher key.
* @param string|null $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
* @return string Encrypted data.
* @throws \InvalidArgumentException On invalid data or key.
*/
public static function encrypt($plain, $key, $hmacSalt = null)
{
$method = 'AES-256-CBC';
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
return $iv . openssl_encrypt($plain, $method, $key, OPENSSL_RAW_DATA, $iv);
}
示例11: createNewToken
/**
* @return $this
*/
public function createNewToken()
{
$byteLength = 32;
$token = bin2hex(openssl_random_pseudo_bytes($byteLength));
$this->session->set($this->tokenFieldName, $token);
return $this;
}
示例12: getToken
/**
* @static
*
* @return string текущий токен пользователя
*/
function getToken()
{
if (!isset($_SESSION[SESSION_KEY_TOKEN])) {
$_SESSION[SESSION_KEY_TOKEN] = base64_encode(openssl_random_pseudo_bytes(32));
}
return $_SESSION[SESSION_KEY_TOKEN];
}
示例13: getCsrfToken
/**
* Token utilizado para proteção contra CSRF.
*
* Deve ser adicionado à Session do Cliente e comparado na avaliação
* do Retorno da autenticação
*
* @return string Token de 12 caracteres
*/
public function getCsrfToken()
{
if (empty($this->token)) {
$this->token = substr(sha1(openssl_random_pseudo_bytes(32)), 0, 9);
}
return $this->token;
}
示例14: get_random_bytes
function get_random_bytes($count)
{
$output = '';
if (@is_readable('/dev/urandom') && ($fh = @fopen('/dev/urandom', 'rb'))) {
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($fh, 0);
}
$output = fread($fh, $count);
fclose($fh);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$output = openssl_random_pseudo_bytes($count, $orpb_secure);
if ($orpb_secure != true) {
$output = '';
}
} elseif (defined('MCRYPT_DEV_URANDOM')) {
$output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
}
if (strlen($output) < $count) {
$output = '';
for ($i = 0; $i < $count; $i += 16) {
$this->random_state = md5(microtime() . $this->random_state);
$output .= pack('H*', md5($this->random_state));
}
$output = substr($output, 0, $count);
}
return $output;
}
示例15: generate
public static function generate()
{
$token = bin2hex(openssl_random_pseudo_bytes(32));
if (Session::put(Config::get('session_for_csrf_form_token/timestamp_name'), time())) {
return Session::put(Config::get('session_for_csrf_form_token/name'), $token);
}
}