public function perform() { $hash = Request::getString($_REQUEST['x']); if (!strlen($hash) || base64_decode($hash, true) === false) { $this->req->setResult(['success' => false, 'error' => 'Wrong format of extTokenHash']); return; } $this->appInstance->externalAuthTokens->findByExtTokenHash($hash, function ($result) use($hash) { if ($result) { $this->req->setResult(['success' => false, 'error' => 'This token was already used.']); return; } $ip = $this->req->getIp(); $intToken = Crypt::hash(Daemon::uniqid() . "" . $ip . "" . Crypt::randomString()); $this->appInstance->externalAuthTokens->save(['extTokenHash' => $hash, 'intToken' => $intToken, 'ip' => $ip, 'useragent' => Request::getString($_SERVER['HTTP_USER_AGENT']), 'ctime' => microtime(true), 'status' => 'new'], function ($lastError) use($intToken) { if (!isset($lastError['n']) || $lastError['n'] === 0) { $this->req->setResult(['success' => false, 'errors' => ['code' => 'Sorry, internal error.']]); return; } $type = Request::getString($_REQUEST['type']); if ($type === 'email') { // send email.... } elseif ($type === 'redirect') { $this->req->redirectTo(HTTPClient::buildUrl(['/' . $this->req->locale . '/account/extauth', 'i' => $intToken]), false); } $this->req->setResult(['success' => true, 'intToken' => $intToken]); }); }); }
/** * Called when the connection is handshaked (at low-level), and peer is ready to recv. data * @return void */ public function onReady() { $this->setWatermark(2, $this->pool->maxAllowedPacket); Crypt::randomString(16, null, function ($string) { $this->key = base64_encode($string); $this->write('GET /' . $this->path . " HTTP/1.1\r\nHost: " . $this->host . ($this->port != 80 ? ':' . $this->port : '') . "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " . $this->key . "\r\nSec-WebSocket-Version: 13\r\n\r\n"); }); }
/** * @covers Crypt::randomInts */ public function testRandomInts() { $this->prepareAsync(); Crypt::randomInts(5, function ($ints) { self::assertCount(5, $ints, '$ints must contain 5 elements'); $this->completeAsync(); }); $this->runAsync(__METHOD__); }
/** * Constructor * @return void */ public function init() { parent::init(); Crypt::randomInts32(1, function ($ints) { $this->opts['entropy'] = $ints[0]; echo json_encode($this->opts); $this->finish(); }, 9); $this->sleep(5, true); }
/** * @TODO * @param callable $cb * @callback $cb ( ) * @return this */ public function acquire($cb) { Crypt::randomString(16, null, function ($token) use($cb) { $this->token = $token; $this->pool->set($this->key, $this->token, 'NX', 'EX', $this->timeout, function ($redis) use($cb) { $cb($this, $redis->result === 'OK', $redis); }); }); return $this; }
public function perform() { $str = Request::getString($_REQUEST['str']); $size = Request::getInteger($_REQUEST['size']); $rounds = Request::getInteger($_REQUEST['rounds']); if (!$rounds) { $rounds = 24; } $salt = '$512=24'; $hash = Crypt::hash($str, $salt); $hex = trim(str_replace('\\x', ' ', Debug::exportBytes(base64_decode($hash), true))); $this->req->setResult(['stringWithSalt' => $str . $salt, 'base64' => $hash, 'salt' => $salt, 'hex' => $hex, 'rounds' => 24]); }
/** * @param array $find * @param callable $cb */ public function newToken($cb, $add = []) { $this->captcha->insertOne(['_id' => $id = new \MongoId(), 'rnd' => $rnd = \PHPDaemon\Utils\Crypt::randomString(8), 'text' => $text = \WakePHP\Utils\CaptchaDraw::getRandomText(), 'ctime' => time()] + $add, function ($lastError) use($id, $rnd, $cb, $text) { if (!$lastError['ok']) { call_user_func($cb, false); return; } $token = base64_encode($id . "" . $rnd); $this->appInstance->JobManager->enqueue(function ($result) use($token, $text, $cb) { if (!$result) { call_user_func($cb, false); return; } Daemon::log(Debug::dump([[$result]])); call_user_func($cb, $token); }, 'GenerateCaptchaImage', [$token, $text]); }); }
public function init() { try { $this->header('Content-Type: text/plain'); //$this->header('Content-Type: application/x-json'); } catch (\Exception $e) { } if (!$this->importCmdArgs()) { return; } $this->sleep(5, true); // setting timeout 5 seconds */ $this->onSessionStart(function () { $this->wakeup(); if ($this->cmd === 'LOGIN') { if (sizeof($this->args) !== 2) { $this->result = ['$err' => 'You must pass exactly 2 arguments.']; $this->wakeup(); return; } $c1 = \PHPDaemon\Utils\Crypt::compareStrings($this->appInstance->config->username->value, $this->args[0]) ? 0 : 1; $c2 = \PHPDaemon\Utils\Crypt::compareStrings($this->appInstance->config->password->value, $this->args[1]) ? 0 : 1; if ($c1 + $c2 > 0) { $this->result = ['$err' => 'Wrong username and/or password.']; return; } $this->attrs->session['logged'] = $this->appInstance->config->credver; $this->result = ['$ok' => 1]; $this->wakeup(); return; } elseif ($this->cmd === 'LOGOUT') { unset($this->attrs->session['logged']); $this->result = ['$ok' => 1]; $this->wakeup(); return; } if (!isset($this->attrs->session['logged']) || $this->attrs->session['logged'] < $this->appInstance->config->credver) { $this->result = ['$err' => 'You must be authenticated.']; $this->wakeup(); return; } }); }
public function checkCode($code, $cb) { if ($this->cond === null) { $this->extractCondFrom($this->obj); } $this->orm->messages->findAndModify(['query' => $this->cond + ['tries' => ['$gt' => 0], 'ts' => ['$gt' => microtime(true) - 5 * 60], 'success' => null], 'update' => ['$inc' => ['tries' => -11]], 'new' => true], function ($lastError) use($cb, $code) { if (!isset($lastError['value']['code'])) { call_user_func($cb, $this, false, 0); return; } if (!Crypt::compareStrings($lastError['value']['code'], trim($code))) { call_user_func($cb, $this, false, $lastError['value']['tries']); } $this->set('success', true); $this->save(function () use($cb) { if ($this->lastError(true)) { call_user_func($cb, $this, true); } else { call_user_func($cb, $this, false, 0); } }); }); }
/** * @param string $password * @return bool */ public function checkPassword($password) { return !isset($this->obj['password']) ? false : Crypt::compareStrings($this->obj['password'], Crypt::hash($password, $this->obj['salt'] . $this->appInstance->config->cryptsaltextra->value)); }
/** * @param $req * @return array */ public function getAccountBase($req) { return ['email' => '', 'location' => '', 'ukey' => Crypt::randomString(16), 'confirmationcode' => substr(md5($req->attrs->server['REMOTE_ADDR'] . "" . Daemon::uniqid() . "" . $this->appInstance->config->cryptsalt->value . "" . microtime(true) . "" . mt_rand(0, mt_getrandmax())), 0, 6), 'regdate' => time(), 'etime' => time(), 'ttlSession' => 1200, 'ip' => $req->attrs->server['REMOTE_ADDR'], 'subscription' => 'daily', 'aclgroups' => array('Users'), 'acl' => array()]; }
/** * Created by PhpStorm. * User: ovr * Date: 06.12.15 * Time: 22:26 */ use Lavoiesl\PhpBenchmark\Benchmark; use Ovr\Bench\AssignOrNot\ReturnAfterAssignProperty; use Ovr\Bench\AssignOrNot\ReturnWithoutAfterAssignProperty; include_once __DIR__ . '/vendor/autoload.php'; $benchmark = new Benchmark(); $benchmark->add('rand', function () { rand(0, getrandmax()); }); $benchmark->add('mt_rand', function () { mt_rand(0, getrandmax()); }); $benchmark->add('random_int', function () { random_int(0, getrandmax()); }); $benchmark->add('phpd-utils-crypt', function () { $gen = false; \PHPDaemon\Utils\Crypt::randomInts(1, function ($result) use(&$gen) { $gen = true; }); while (!$gen) { } }); $benchmark->setCount(100000); $benchmark->run();
/** * Function run task and wait result in callback * * @param $params * @param callable $cb = null * @param boolean $unique */ public function submitJob($params, $cb = null) { $closure = function () use(&$params, $cb) { $this->sendCommand('SUBMIT_JOB' . (isset($params['pri']) ? '_ ' . strtoupper($params['pri']) : '') . (isset($params['bg']) && $params['bg'] ? '_BG' : ''), [$params['function'], $params['unique'], $params['payload']], $cb); }; if (isset($params['unique'])) { $closure(); } else { Crypt::randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', function ($random) use($closure) { $params['unique'] = $random; $closure(); }); } }
/** * @return array */ public function startSession($add = [], $cb = null) { $session = ['id' => Crypt::randomString(), 'ctime' => microtime(true)] + $add; $this->sessions->upsertOne(['id' => (string) $session['id']], $session, $cb); return $session; }
public static function getRandomText() { return \PHPDaemon\Utils\Crypt::randomString(4, '23456789abcdefghkmnpqrstuvwxyz23456789'); //return \PHPDaemon\Utils\Crypt::randomString(4, 'ABCDEFGHKLMNPQRSTUVWXYZ23456789abcdefghkmnpqrstuvwxyz23456789'); }