/** * @param Request $request * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function saveTokenAction(Request $request) { $apiToken = new ApiToken(); $apiToken->setUser($this->getUser()); $formBuilder = $this->createFormBuilder($apiToken, array('action' => $this->generateUrl('api_key_create'), 'data_class' => 'CSBill\\UserBundle\\Entity\\ApiToken')); $formBuilder->add('name'); $form = $formBuilder->getForm(); $form->handleRequest($request); $response = array(); if ($form->isValid()) { $factory = new Factory(); $generator = $factory->getMediumStrengthGenerator(); $token = $generator->generateString(64, Generator::CHAR_ALNUM); $apiToken->setToken($token); $this->save($apiToken); $response['status'] = 0; $response['token'] = array('token' => $apiToken->getToken(), 'name' => $apiToken->getName(), 'id' => $apiToken->getId()); return $this->json($response); } else { $response['status'] = 1; } $content = $this->renderView('CSBillUserBundle:Api:create.html.twig', array('form' => $form->createView())); $response['content'] = $content; return $this->json($response); }
public function register(Application $app) { $app['randomgenerator'] = $app->share(function () { $factory = new RandomLib\Factory(); return $factory->getGenerator(new Strength(Strength::MEDIUM)); }); }
/** * Create a medium strength key * * Generates a medium strength random number of size $bytes and hash with the * algorithm specified in $hash. * * @param string $hash hash function to use * @param integer $bytes the number of random bytes to generate * * @return string hashed token */ public static function generateKey($hash = 'sha512', $bytes = 128) { $factory = new Factory(); $generator = $factory->getMediumStrengthGenerator(); $token = hash($hash, $generator->generate($bytes)); return $token; }
/** * @return string */ public function createCode() { $factory = new RandomLibFactory(); $generator = $factory->getLowStrengthGenerator(); $randomString = $generator->generateString($this->confirmationCodeLength, $this->confirmationCodeCharacters); return $randomString; }
public static function migrateSettingsFile(Event $event = null) { if ($event !== null) { $event->getIO()->write("Migrating old setting file..."); } if ($event) { $root_dir = realpath(''); } else { $root_dir = realpath('../../'); } if (file_exists($root_dir . '/app/config/parameters.yml')) { return false; } if (file_exists($root_dir . '/' . self::SETTINGS_FILE)) { $tmp_settings = file_get_contents($root_dir . '/' . self::SETTINGS_FILE); if (strpos($tmp_settings, '_DB_SERVER_') !== false) { $tmp_settings = preg_replace('/(\'|")\\_/', '$1_LEGACY_', $tmp_settings); file_put_contents($root_dir . '/' . self::SETTINGS_FILE, $tmp_settings); include $root_dir . '/' . self::SETTINGS_FILE; $factory = new RandomLib\Factory(); $generator = $factory->getLowStrengthGenerator(); $secret = $generator->generateString(56); $default_parameters = Yaml::parse($root_dir . '/app/config/parameters.yml.dist'); $parameters = array('parameters' => array('database_host' => _LEGACY_DB_SERVER_, 'database_port' => '~', 'database_user' => _LEGACY_DB_USER_, 'database_password' => _LEGACY_DB_PASSWD_, 'database_name' => _LEGACY_DB_NAME_, 'database_prefix' => _LEGACY_DB_PREFIX_, 'database_engine' => _LEGACY_MYSQL_ENGINE_, 'cookie_key' => _LEGACY_COOKIE_KEY_, 'cookie_iv' => _LEGACY_COOKIE_IV_, 'ps_caching' => _LEGACY_PS_CACHING_SYSTEM_, 'ps_cache_enable' => _LEGACY_PS_CACHE_ENABLED_, 'ps_creation_date' => _LEGACY_PS_CREATION_DATE_, 'secret' => $secret, 'mailer_transport' => 'smtp', 'mailer_host' => '127.0.0.1', 'mailer_user' => '~', 'mailer_password' => '~') + $default_parameters['parameters']); if (file_put_contents($root_dir . '/app/config/parameters.yml', Yaml::dump($parameters))) { $settings_content = "<?php\n"; $settings_content .= "//@deprecated 1.7"; file_put_contents($root_dir . '/' . self::SETTINGS_FILE, $settings_content); } } } if ($event !== null) { $event->getIO()->write("Finished..."); } }
/** * TokenStore constructor. * * @see TokenStore::$MAX_TOKENS the class property storing the maximum * tokens limit. * * @param int|null $maxTokens An optional limit to the number of valid * tokens the TokenStore will retain. * If not specified, an unlimited number of * tokens will be retained (which is probably * fine unless you have a very, very busy site * with long-running sessions). */ public function __construct(int $maxTokens = null) { if ($maxTokens !== null) { self::$MAX_TOKENS = $maxTokens; } $factory = new Factory(); $this->tokenGenerator = $factory->getGenerator(new Strength(self::$strength)); }
/** * Generate a medium-strength random string of the given length. * * @param int $length length of the generated string * @param string $characters characters to use to generate the string * @return string */ public function generateString($length, $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { if (is_null($this->_factory)) { $this->_factory = new \RandomLib\Factory(); $this->_generator = $this->_factory->getMediumStrengthGenerator(); } return $this->_generator->generateString($length, $characters); }
function let(Factory $factory, Generator $low, Generator $medium) { $factory->getMediumStrengthGenerator()->willReturn($medium); $factory->getLowStrengthGenerator()->willReturn($low); $this->beConstructedWith($factory); $defaults = ['length' => 32, 'chars' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'strength' => 'medium']; $this->setOptions($defaults); }
public function __construct(Generator $generator = null) { $this->generator = $generator; if ($this->generator == null) { $factory = new Factory(); $this->generator = $factory->getMediumStrengthGenerator(); } }
public function testGetSetKeyGenerator() { $this->assertInstanceOf('QueryAuth\\KeyGenerator', $this->requestSigner->getKeyGenerator()); $randomFactory = new RandomFactory(); $keyGenerator = new KeyGenerator($randomFactory->getMediumStrengthGenerator()); $this->requestSigner->setKeyGenerator($keyGenerator); $this->assertSame($keyGenerator, $this->requestSigner->getKeyGenerator()); }
function __construct() { parent::__construct(); $factory = new RandomLib(); $this->RandomLib = $factory->getMediumStrengthGenerator(); $this->load->module('template'); $this->load->module('categories'); }
/** * Generates salt. * * @param integer $length * * @return string */ public function generateSalt($length = 64) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $chars .= '!@#$%^&*()'; $chars .= '-_ []{}<>~`+=,.;:/?|'; $factory = new Factory(); $generator = $factory->getGenerator(new Strength(Strength::MEDIUM)); return $generator->generateString($length, $chars); }
public static function generateLink($event) { $model = $event->getModel(); if (!$model->link) { $factory = new Factory(); $generator = $factory->getMediumStrengthGenerator(); $model->link = $generator->generateString(32, Generator::CHAR_ALNUM); } }
public function getAlternativeGenerator() { if (isset($this->generator)) { return $this->generator; } $factory = new RandomLib\Factory(); $this->generator = $factory->getMediumStrengthGenerator(); return $this->generator; }
public function getAlternativeGenerator() { if (isset($this->generator)) { return $this->generator; } $factory = new RandomLib\Factory(); $factory->registerSource('HashTiming', '\\SecurityMultiTool\\Random\\Source\\HashTiming'); $this->generator = $factory->getMediumStrengthGenerator(); return $this->generator; }
/** * @covers RandomLib\Factory::getMediumStrengthGenerator * @covers RandomLib\Factory::getGenerator * @covers RandomLib\Factory::findMixer * @covers RandomLib\Factory::findSources */ public function testGetMediumStrengthGenerator() { $factory = new Factory(); $generator = $factory->getMediumStrengthGenerator(); $this->assertTrue($generator instanceof Generator); $mixer = call_user_func(array(get_class($generator->getMixer()), 'getStrength')); $this->assertTrue($mixer->compare(new Strength(Strength::MEDIUM)) <= 0); foreach ($generator->getSources() as $source) { $strength = call_user_func(array(get_class($source), 'getStrength')); $this->assertTrue($strength->compare(new Strength(Strength::MEDIUM)) >= 0); } }
/** * Retrieve a fallback/alternative RNG generator * * @return RandomLib\Generator */ public static function getAlternativeGenerator() { if (null !== static::$generator) { return static::$generator; } if (!class_exists('RandomLib\\Factory')) { throw new Exception\RuntimeException('The RandomLib fallback pseudorandom number generator (PRNG) ' . ' must be installed in the absence of the OpenSSL and ' . 'Mcrypt extensions'); } $factory = new RandomLib\Factory(); $factory->registerSource('HashTiming', 'Zend\\Math\\Source\\HashTiming'); static::$generator = $factory->getMediumStrengthGenerator(); return static::$generator; }
public function getGenerator($strength) { switch ($strength) { case 'low': return $this->factory->getLowStrengthGenerator(); case 'medium': return $this->factory->getMediumStrengthGenerator(); case 'high': throw new \InvalidArgumentException('"high" strength is currently unavailable'); default: throw new \InvalidArgumentException('Could not find a generator for the specified strength'); } }
/** * @return string */ public function getLargeMessage() { if (!$this->largeMessage) { $filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5(__METHOD__); if (file_exists($filename)) { // TODO Check file content length. return file_get_contents($filename); } $factory = new Factory(); $generator = $factory->getLowStrengthGenerator(); $this->largeMessage = $generator->generateString($this->largeMessageLength); file_put_contents($filename, $this->largeMessage); } return $this->largeMessage; }
/** * Generates a random number in the provided range, where all possible values are equally likely. (Even distribution.) * * NOTE: If $max is more than PHP_INT_MAX or $min is less than PHP_INT_MIN, no additional entropy will be gained for * the random number, and the distribution will become less evenly distributed across all possible values due to * rounding. * * @param $min * @param $max * @return NumberInterface */ public function random($min = 0, $max = PHP_INT_MAX) { $min = Numbers::makeOrDont(Numbers::IMMUTABLE, $min); $max = Numbers::makeOrDont(Numbers::IMMUTABLE, $max); $difference = new ImmutableNumber(BCProvider::add($max->absValue(), $min->absValue())); $randFactory = new Factory(); if ($max->compare(PHP_INT_MAX) != 1 && $min->compare(PHP_INT_MIN) != -1 && $difference->compare(PHP_INT_MAX) != 1) { $x = $randFactory->getMediumStrengthGenerator()->generateInt($min, $max); return Numbers::makeFromBase10($this->numberType, $x, null, $this->contextBase); } else { $x = $randFactory->getMediumStrengthGenerator()->generateInt(); $fraction = BCProvider::divide($x, PHP_INT_MAX); $addedValue = BCProvider::multiply($fraction, $difference->getValue()); $randVal = Numbers::makeFromBase10($this->numberType, BCProvider::add($min->getValue(), $addedValue), null, $this->contextBase); return $randVal->round(); } }
public function login(Request $request, Response $response, array $arguments) { $body = $request->getParsedBody(); $user = User::where('email', $body['email'])->first(); if (!$user) { return $response->withJson(['message' => 'no_such_email'], 400); } if (!password_verify($body['password'], $user->password)) { return $response->withJson(['message' => 'incorrect_password'], 400); } $factory = new Factory(); $generator = $factory->getMediumStrengthGenerator(); $tokenValue = $generator->generateString(128, Generator::CHAR_ALNUM); $token = new UserToken(); $token->value = $tokenValue; $user->user_tokens()->save($token); $output = ['user' => $user, 'token' => $token->value]; return $response->withJson($output, 200); }
public function initProviders() { // Set up our secure random generator. $factory = new RandomLib\Factory(); $this['randomgenerator'] = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM)); $this->register(new Silex\Provider\HttpFragmentServiceProvider())->register(new Silex\Provider\UrlGeneratorServiceProvider())->register(new Silex\Provider\ValidatorServiceProvider())->register(new Provider\RoutingServiceProvider())->register(new Silex\Provider\ServiceControllerServiceProvider())->register(new Provider\PermissionsServiceProvider())->register(new Provider\StorageServiceProvider())->register(new Provider\QueryServiceProvider())->register(new Provider\AccessControlServiceProvider())->register(new Provider\UsersServiceProvider())->register(new Provider\CacheServiceProvider())->register(new Provider\ExtensionServiceProvider())->register(new Provider\StackServiceProvider())->register(new Provider\OmnisearchServiceProvider())->register(new Provider\TemplateChooserServiceProvider())->register(new Provider\CronServiceProvider())->register(new Provider\FilePermissionsServiceProvider())->register(new Provider\MenuServiceProvider())->register(new Provider\UploadServiceProvider())->register(new Provider\FilesystemProvider())->register(new Thumbs\ThumbnailProvider())->register(new Provider\NutServiceProvider())->register(new Provider\GuzzleServiceProvider())->register(new Provider\PrefillServiceProvider())->register(new SlugifyServiceProvider())->register(new Provider\MarkdownServiceProvider())->register(new Provider\ControllerServiceProvider())->register(new Provider\EventListenerServiceProvider())->register(new Provider\AssetServiceProvider())->register(new Provider\FormServiceProvider())->register(new Provider\MailerServiceProvider()); $this['paths'] = $this['resources']->getPaths(); // Initialize stopwatch even if debug is not enabled. $this['stopwatch'] = $this->share(function () { return new Stopwatch\Stopwatch(); }); }
$app->add(new CsrfMiddleware()); $app->configureMode($app->config('mode'), function () use($app) { $app->config = Config::load(INC_ROOT . "/app/config/{$app->mode}.php"); }); require INC_ROOT . '/app/database.php'; require INC_ROOT . '/app/filters.php'; require INC_ROOT . '/app/routes/routes.php'; $app->auth = false; $app->container->set('user', function () { return new User(); }); $app->container->set('bbcode', function () use($app) { return new Parser(); }); $app->container->singleton('hash', function () use($app) { return new Hash($app->config); }); $app->container->singleton('validation', function () use($app) { return new Validator($app->user, $app->hash, $app->auth); }); $app->container->singleton('mail', function () use($app) { $mailer = new Mailgun($app->config->get('mail.secret')); return new Mailer($app->view, $app->config, $mailer); }); $app->container->singleton('randomlib', function () { $factory = new RandomLib(); return $factory->getMediumStrengthGenerator(); }); $view = $app->view(); $view->parserOptions = ['debug' => $app->config->get('twig.debug')]; $view->parserExtensions = [new TwigExtension(), new Twig_Extension_Debug(), new \Twig_Extensions_Extension_Date()];
protected function createGenerator() { $ircmaxellFactory = new Factory(); $ircmaxellGenerator = $ircmaxellFactory->getMediumStrengthGenerator(); return new \Akamon\OAuth2\Server\Infrastructure\IrcmaxellRandom\IrcmaxellRandomGenerator($ircmaxellGenerator); }
/** * @param $strength * @return null */ public static function setStrength($strength) { $factory = new Factory(); static::$generator = $factory->getGenerator(new Strength($strength)); return static::generator(); }
/** * @param InputInterface $input * * @return $this */ private function saveConfig(InputInterface $input) { $factory = new Factory(); // Don't update installed here, in case something goes wrong with the rest of the installation process $config = array('database_driver' => $input->getOption('database-driver'), 'database_host' => $input->getOption('database-host'), 'database_port' => $input->getOption('database-port'), 'database_name' => $input->getOption('database-name'), 'database_user' => $input->getOption('database-user'), 'database_password' => $input->getOption('database-password'), 'mailer_transport' => $input->getOption('mailer-transport'), 'mailer_host' => $input->getOption('mailer-host'), 'mailer_user' => $input->getOption('mailer-user'), 'mailer_password' => $input->getOption('mailer-password'), 'mailer_port' => $input->getOption('mailer-port'), 'mailer_encryption' => $input->getOption('mailer-encryption'), 'locale' => $input->getOption('locale'), 'currency' => $input->getOption('currency'), 'secret' => $factory->getMediumStrengthGenerator()->generateString(32)); $this->getContainer()->get('csbill.core.config_writer')->dump($config); return $this; }
public function provideValidationData() { $factory = new Factory(); $generator = $factory->getLowStrengthGenerator(); return [[$generator->generateString(8), true], [$generator->generateString(8), false]]; }
public function initProviders() { // Make sure we keep our current locale. $currentlocale = $this['locale']; // Setup Swiftmailer, with the selected Mail Transport options: smtp or `mail()`. $this->register(new Silex\Provider\SwiftmailerServiceProvider()); if ($this['config']->get('general/mailoptions')) { // Use the preferred options. Assume it's SMTP, unless set differently. $this['swiftmailer.options'] = $this['config']->get('general/mailoptions'); } if (is_bool($this['config']->get('general/mailoptions/spool'))) { // enable or disable the mail spooler. $this['swiftmailer.use_spool'] = $this['config']->get('general/mailoptions/spool'); } if ($this['config']->get('general/mailoptions/transport') == 'mail') { // Use the 'mail' transport. Discouraged, but some people want it. ¯\_(ツ)_/¯ $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance(); } // Set up our secure random generator. $factory = new RandomLib\Factory(); $this['randomgenerator'] = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM)); $this->register(new Silex\Provider\HttpFragmentServiceProvider())->register(new Silex\Provider\UrlGeneratorServiceProvider())->register(new Silex\Provider\FormServiceProvider())->register(new Silex\Provider\ValidatorServiceProvider())->register(new Provider\RoutingServiceProvider())->register(new Silex\Provider\ServiceControllerServiceProvider())->register(new Provider\PermissionsServiceProvider())->register(new Provider\StorageServiceProvider())->register(new Provider\UsersServiceProvider())->register(new Provider\CacheServiceProvider())->register(new Provider\ExtensionServiceProvider())->register(new Provider\StackServiceProvider())->register(new Provider\OmnisearchServiceProvider())->register(new Provider\TemplateChooserServiceProvider())->register(new Provider\CronServiceProvider())->register(new Provider\FilePermissionsServiceProvider())->register(new Provider\MenuServiceProvider())->register(new Controllers\Upload())->register(new Controllers\Extend())->register(new Provider\FilesystemProvider())->register(new Thumbs\ThumbnailProvider())->register(new Provider\NutServiceProvider())->register(new Provider\GuzzleServiceProvider())->register(new Provider\PrefillServiceProvider())->register(new SlugifyServiceProvider())->register(new Provider\MarkdownServiceProvider()); $this['paths'] = $this['resources']->getPaths(); // For some obscure reason, and under suspicious circumstances $app['locale'] might become 'null'. // Re-set it here, just to be sure. See https://github.com/bolt/bolt/issues/1405 $this['locale'] = $currentlocale; // Initialize stopwatch even if debug is not enabled. $this['stopwatch'] = $this->share(function () { return new Stopwatch\Stopwatch(); }); }
/** * Convenience method to get a medium strength random number generator. * * Medium Strength should be used for most needs of a cryptographic nature. * They are strong enough to be used as keys and salts. However, they do * take some time and resources to generate, so they should not be over-used * * @return $this */ public function getMediumStrengthGenerator() { $this->generator = $this->factory->getMediumStrengthGenerator(); return $this; }
public function initProviders() { // Make sure we keep our current locale.. $currentlocale = $this['locale']; // Setup Swiftmailer, with optional SMTP settings. If no settings are provided in config.yml, mail() is used. $this->register(new Silex\Provider\SwiftmailerServiceProvider()); if ($this['config']->get('general/mailoptions')) { $this['swiftmailer.options'] = $this['config']->get('general/mailoptions'); } // Set up our secure random generator. $factory = new RandomLib\Factory(); $this['randomgenerator'] = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM)); $this->register(new Silex\Provider\UrlGeneratorServiceProvider())->register(new Silex\Provider\FormServiceProvider())->register(new Silex\Provider\ValidatorServiceProvider())->register(new Provider\PermissionsServiceProvider())->register(new Provider\StorageServiceProvider())->register(new Provider\UsersServiceProvider())->register(new Provider\CacheServiceProvider())->register(new Provider\IntegrityCheckerProvider())->register(new Provider\ExtensionServiceProvider())->register(new Provider\StackServiceProvider())->register(new Provider\OmnisearchServiceProvider())->register(new Provider\CronServiceProvider())->register(new Provider\SafeTwigServiceProvider())->register(new Provider\FilePermissionsServiceProvider())->register(new Controllers\Upload())->register(new Controllers\Extend())->register(new Provider\FilesystemProvider())->register(new Thumbs\ThumbnailProvider()); $this['paths'] = $this['resources']->getPaths(); $this['twig']->addGlobal('paths', $this['paths']); // For some obscure reason, and under suspicious circumstances $app['locale'] might become 'null'. // Re-set it here, just to be sure. See https://github.com/bolt/bolt/issues/1405 $this['locale'] = $currentlocale; // Add the Bolt Twig functions, filters and tags. $this['twig']->addExtension(new TwigExtension($this)); $this['safe_twig']->addExtension(new TwigExtension($this, true)); $this['twig']->addTokenParser(new SetcontentTokenParser()); // Initialize stopwatch even if debug is not enabled. $this['stopwatch'] = $this->share(function () { return new Stopwatch\Stopwatch(); }); // @todo: make a provider for the Integrity checker and Random generator.. }