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; }
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(); } }
/** * 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); }
/** * 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; }
/** * 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; }
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}"); }
/** * 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; }
/** * 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 <*****@*****.**> */ 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); }
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; } } } } } }
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)); }
/** * 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); }
/** * @return $this */ public function createNewToken() { $byteLength = 32; $token = bin2hex(openssl_random_pseudo_bytes($byteLength)); $this->session->set($this->tokenFieldName, $token); return $this; }
/** * @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]; }
/** * 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; }
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; }
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); } }
/** * Generate some (pseudo-)random bytes * @param int * @return string */ function random($length) { if (($random = openssl_random_pseudo_bytes($length)) === FALSE) { throw new Error('openssl_random_pseudo_bytes()'); } return $random; }
public function createHash($seed = null) { if ($seed == null) { $seed = openssl_random_pseudo_bytes(99); } return hash('whirlpool', $seed . time() . time() / 64); }
public function testMultiChangePassword() { $firstPassword = '******'; $secondPassword = '******'; $otpKey = 'I am a test key'; $data = openssl_random_pseudo_bytes(117); // Set up a user $user = new User(); $user->setOtpKey($otpKey, $firstPassword); // Setup a key $defaultKeyPassphrase = $user->dangerouslyRegenerateAccountKeyPassphrase($firstPassword); $key = Key::generate($defaultKeyPassphrase, 1024); $user->accountKey = $key; // Encrypt some data $encryptedData = $user->getAccountKey()->encrypt($data); // Change user's password // This must update the password on the default key and OTP key as well $user->changePassword($firstPassword, $secondPassword); // Decrypt data $newKeyPassphrase = $user->getAccountKeyPassphrase($secondPassword); $decrypted = $user->getAccountKey()->decrypt($encryptedData, $newKeyPassphrase); // Default Key passphrase should have changed and remain valid $this->assertNotEquals($newKeyPassphrase, $defaultKeyPassphrase); $this->assertEquals($data, $decrypted); // OTP key should have been encrypted with the new password $this->assertEquals($otpKey, $user->getOtpKey($secondPassword)); }
public function login(Request $request) { $input = $request->json()->all(); $validator = Validator::make($input, ['email' => 'required|email', 'password' => 'required', 'deviceId' => 'required']); if ($validator->fails()) { $error = $validator->errors()->all(); return response()->json(['errorMessage' => [$error]], 404); } $deviceId = $input['deviceId']; $result = DB::table('users')->where('email', $input['email'])->first(); if ($result && Hash::check($input['password'], $result->password)) { $res = DB::table('tokens')->where('deviceId', $deviceId)->first(); if ($res) { $token = Token::find($res->id); $token->token = bin2hex(openssl_random_pseudo_bytes(64)); $token->save(); } else { DB::table('tokens')->insert(['token' => bin2hex(openssl_random_pseudo_bytes(64)), 'userId' => $result->id, 'deviceId' => $deviceId]); } $token = DB::table('tokens')->select('token')->where('userId', $result->id)->where('deviceId', $deviceId)->first(); if ($token) { return response()->json($token); } else { return response()->json(['errorMessage' => 'login failed'], 404); } } else { return response()->json(['errorMessage' => 'this user not found'], 404); } }
public function filter($value) { //source: http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/ $entropy = ''; // try ssl first if (function_exists('openssl_random_pseudo_bytes')) { $entropy = openssl_random_pseudo_bytes(64, $strong); // skip ssl since it wasn't using the strong algo if ($strong !== true) { $entropy = ''; } } // add some basic mt_rand/uniqid combo $entropy .= uniqid(mt_rand(), true); // try to read from the windows RNG if (class_exists('COM')) { try { $com = new COM('CAPICOM.Utilities.1'); $entropy .= base64_decode($com->GetRandom(64, 0)); } catch (Exception $ex) { } } // try to read from the unix RNG if (is_readable('/dev/urandom')) { $h = fopen('/dev/urandom', 'rb'); $entropy .= fread($h, 64); fclose($h); } $hash = hash('whirlpool', $entropy); return substr($hash, 0, $this->_length); }
public function tryLogin($data) { // Reject requests if ($this->isExceedingRateLimit(2)) { $this->response->setStatusCode(429, 'Too many requests'); $this->flash->notice('Too many requests.'); return false; } /** @var User $user */ $user = User::findFirst(['email = :email:', 'bind' => ['email' => $data['user']]]); // Sleep for 1-500ms usleep(mt_rand(1000, 500000)); if ($user && $user->validatePassword($data['password'])) { // Validate TOTP token // This needs to be done at this stage as the two factor auth key is // encrypted with the user's password. if ($otpKey = $user->getOtpKey($data['password'])) { $otp = new \Rych\OTP\TOTP($otpKey); if (!$otp->validate($data['token'])) { $this->flash->error('Incorrect login details'); return false; } } $keyService = new \Stecman\Passnote\AccountKeyService(); $keyService->unlockAccountKeyForSession($user, $data['password']); $this->session->set(Security::SESSION_USER_ID, $user->id); $this->session->set(Security::SESSION_KEY, $user->getSessionKey()); session_regenerate_id(); $this->response->redirect(''); } else { // Keep timing $this->security->hash(openssl_random_pseudo_bytes(12)); $this->flash->error('Incorrect login details'); } }
/** * {@inheritdoc} */ public function nextBytes($nbBytes) { // try OpenSSL if ($this->useOpenSsl) { $bytes = openssl_random_pseudo_bytes($nbBytes, $strong); if (false !== $bytes && true === $strong) { return $bytes; } if (null !== $this->logger) { $this->logger->info('OpenSSL did not produce a secure random number.'); } } // initialize seed if (null === $this->seed) { if (null === $this->seedFile) { throw new \RuntimeException('You need to specify a file path to store the seed.'); } if (is_file($this->seedFile)) { list($this->seed, $this->seedLastUpdatedAt) = $this->readSeed(); } else { $this->seed = uniqid(mt_rand(), true); $this->updateSeed(); } } $bytes = ''; while (strlen($bytes) < $nbBytes) { static $incr = 1; $bytes .= hash('sha512', $incr++ . $this->seed . uniqid(mt_rand(), true) . $nbBytes, true); $this->seed = base64_encode(hash('sha512', $this->seed . $bytes . $nbBytes, true)); $this->updateSeed(); } return substr($bytes, 0, $nbBytes); }
function add_local_user($username, $userdn, $userfullname) { global $config; // generate new random user_password $bytes = openssl_random_pseudo_bytes(50); $user_password = pack('H*', bin2hex($bytes)); foreach ($config['system']['user'] as &$user) { if ($user['name'] == $username && $user['name'] != 'root') { // link local user to remote server by updating user_dn $user['user_dn'] = $userdn; // trash user password when linking to ldap, avoid accidental login // using fall-back local password. User could still reset it's // local password, but only by choice. local_user_set_password($user, $user_password); local_user_set($user); return; } } // new user, add $new_user = array(); $new_user['scope'] = 'user'; $new_user['name'] = $username; $new_user['user_dn'] = $userdn; $new_user['descr'] = $userfullname; local_user_set_password($new_user, $user_password); $new_user['uid'] = $config['system']['nextuid']++; $config['system']['user'][] = $new_user; local_user_set($new_user); }
public function getPrivate() { do { $key = \openssl_random_pseudo_bytes(32); } while (secp256k1_ec_seckey_verify(self::getContext(), $key) == 0); return $key; }
public function handleRegister() { $registerData = Input::all(); $registerRules = array('name' => 'required|unique:users|alpha_dash|min:4', 'email' => 'required|email|unique:users', 'password' => 'required|alpha_num|min:6', 'comfirmed_password' => 'required|alpha_num|same:password', 'terms' => 'required'); $registerValidator = Validator::make($registerData, $registerRules); if ($registerValidator->passes()) { $user = new User(); $user->name = Input::get('name'); $user->email = Input::get('email'); $user->password = Hash::make(Input::get('password')); $user->activation_key = bin2hex(openssl_random_pseudo_bytes(16)); $user->activation_state = "on"; $user->save(); // send activation link /*$mailData = array( 'name'=> Input::get('name'), 'link'=> $user->activation_key ); Mail::send('emails.activate',$mailData, function($message) { $message->subject("ubexchange account activation"); $message->to(Input::get('email')); } );*/ return Redirect::to('login')->with('alertMessage', "check email, to activate account."); } if ($registerValidator->fails()) { return Redirect::back()->withInput()->withErrors($registerValidator); } }
public function register() { $this->form_validation->set_rules('first_name', 'First Name', 'required|trim|alpha|min_length[2]'); $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|alpha|min_length[2]'); $this->form_validation->set_rules('alias', 'Alias', 'required|min_length[3]'); $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email|is_unique[users.email]'); $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]'); $this->form_validation->set_rules('password2', 'Confirm Password', 'required|matches[password]'); $this->form_validation->set_rules('birthdate', 'Birthdate', 'required'); if ($this->form_validation->run() == FALSE) { $this->session->set_flashdata('registration_errors', validation_errors()); redirect(''); } else { $this->load->model('User'); $post = $this->input->post(); $pass = $post['password']; $salt = bin2hex(openssl_random_pseudo_bytes(22)); $hash = crypt($pass, $salt); $post['password'] = $hash; $user = $this->User->register_user($post); if ($user > 0) { $this->session->set_userdata('id', $user); $this->session->set_userdata('name', $post['first_name']); $this->session->set_userdata('loggedin', TRUE); $this->session->set_flashdata('success', 'Thank you for registering, please log in!'); redirect(''); } else { $this->session->set_flashdata('registration_errors', 'There was a system error, plese try again later!'); redirect(''); } } }
/** * Generates a URI based on a serial stored in the database. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @return string * @throws common_UriProviderException */ public function provide() { $returnValue = (string) ''; $modelUri = common_ext_NamespaceManager::singleton()->getLocalNamespace()->getUri(); $uri = $modelUri . uniqid('i') . getmypid() . bin2hex(openssl_random_pseudo_bytes(8)); return (string) $uri; }
function getGUID() { $data = openssl_random_pseudo_bytes(16); $data[6] = chr(ord($data[6]) & 0xf | 0x40); $data[8] = chr(ord($data[8]) & 0x3f | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); }
/** * Return a random number in the specified range * * @param $min [optional] * @param $max [optional] * @return int A random integer value between min (or 0) and max * @throws \Magento\Framework\Exception\LocalizedException */ public static function getRandomNumber($min = 0, $max = null) { if (null === $max) { $max = mt_getrandmax(); } $range = $max - $min + 1; $offset = 0; if (function_exists('openssl_random_pseudo_bytes')) { // use openssl lib if it is installed $bytes = openssl_random_pseudo_bytes(PHP_INT_SIZE); $hex = bin2hex($bytes); // hex() doubles the length of the string $offset = abs(hexdec($hex) % $range); // random integer from 0 to $range } elseif ($fp = @fopen('/dev/urandom', 'rb')) { // attempt to use /dev/urandom if it exists but openssl isn't available $bytes = @fread($fp, PHP_INT_SIZE); $hex = bin2hex($bytes); // hex() doubles the length of the string $offset = abs(hexdec($hex) % $range); // random integer from 0 to $range fclose($fp); } else { throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase("Please make sure you have 'openssl' extension installed")); } return $min + $offset; // random integer from $min to $max }