Generate a secure token which can be used as a crypto key.
Returns the token and suggests PHP configuration to set it.
190084
public function generatesecuretoken()
    {
        $generator = Injector::inst()->create('SilverStripe\\Security\\RandomGenerator');
        $token = $generator->randomToken('sha1');
        $body = <<<TXT
Generated new token. Please add the following code to your YAML configuration:

Security:
  token: $token

TXT;
        $response = new HTTPResponse($body);
        return $response->addHeader('Content-Type', 'text/plain');
    }
1098093
private function createSecureKey($secureKey)
    {
        if (!$secureKey) {
            $secureKey = (microtime(true) . mt_rand(10000, 90000));
        }
        $secureKey = md5($secureKey);

        $this->secureKey = pack('H*', $secureKey);
    }
401214
public static function _init()
	{
		static::$crypter = new Crypt_AES();
		static::$hasher = new Crypt_Hash('sha256');

		// load the config
		\Config::load('crypt', true);
		static::$config = \Config::get('crypt', array ());

		// generate random crypto keys if we don't have them or they are incorrect length
		$update = false;
		foreach(array('crypto_key', 'crypto_iv', 'crypto_hmac') as $key)
		{
			if ( empty(static::$config[$key]) or (strlen(static::$config[$key]) % 4) != 0)
			{
				$crypto = '';
				for ($i = 0; $i < 8; $i++)
				{
					$crypto .= static::safe_b64encode(pack('n', mt_rand(0, 0xFFFF)));
				}
				static::$config[$key] = $crypto;
				$update = true;
			}
		}

		// update the config if needed
		if ($update === true)
		{
			try
			{
				\Config::save('crypt', static::$config);
			}
			catch (\FileAccessException $e)
			{
				// failed to write the config file, inform the user
				echo \View::forge('errors/crypt_keys', array(
					'keys' => static::$config
				));
				die();
			}
		}

		static::$crypter->enableContinuousBuffer();

		static::$hasher->setKey(static::safe_b64decode(static::$config['crypto_hmac']));
	}
1091458
protected function generateCsrfToken()
    {
        $token = $this->app->getSecurity()->generateRandomString();
        if ($this->enableCsrfCookie) {
            $cookie = $this->createCsrfCookie($token);
            $this->app->getResponse()->getCookies()->add($cookie);
        } else {
            $this->app->getSession()->set($this->csrfParam, $token);
        }

        return $token;
    }
1030063
def get_key(soup):
    '''
    
    '''

    crypto_tag = soup.find(_crypto_tag)
    if crypto_tag is None:
        return _default_key

    pat = re.compile('\["(.+)"\]')
    keys = pat.findall(crypto_tag.text)
    if len(keys) > 0:
        unhashed_key = keys[-1].encode().decode('unicode_escape')
        return _generate_sha(unhashed_key)
    else:
        return _default_key
882497
def _generate():
    
    privateKey = rsa.generate_private_key(
        public_exponent=65537,
        key_size=4096,
        backend=default_backend())
    return Key(privateKey).toString('openssh')
372641
function generateAuthToken(bytes, callback) {
		crypto.randomBytes(bytes, function(err, randomBytes) {
			if(err) {
				return callback(err);
			}
			callback(null, randomBytes.toString('hex'));
		});
	}
531052
public static function generateSigningKeypair() : Keypair
    {
        try {
            $keypair = \sodium_crypto_sign_keypair();
            return new Keypair(
                \sodium_crypto_sign_secretkey($keypair),
                \sodium_crypto_sign_publickey($keypair)
            );
        } catch (SodiumException $e) {
            throw new Exception($e->getMessage());
        }
    }
1301783
public static function generateCsrfToken()
  {
    if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
      $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    } elseif(version_compare(PHP_VERSION, '7.0.0', '<')) {
      if (function_exists('mcrypt_create_iv')) {
        $_SESSION['csrf_token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
      } else {
        $_SESSION['csrf_token'] = bin2hex(openssl_random_pseudo_bytes(32));
      }
    }
    return "<input id='csrf_token' type='hidden' name='csrf_token' value='{$_SESSION['csrf_token']}'>";
  }
1072605
private function initToken()
    {
        $tokenName = $this->getConfig()->get('Token', false);
        $rememberMe = $this->getConfig()->get('RememberMe', false);


        if (!$tokenName) {
            // fallback to the default token
            $securityKey = $this->getConfig()->get('TokenKey', false);

            if (!$securityKey) {
                throw new FirewallException('Missing TokenKey for "' . $this->getRealmName() . '" firewall.');
            }
        } else {
            $securityKey = Security::getConfig()->get('Tokens.' . $tokenName . '.SecurityKey', false);

            if (!$securityKey) {
                throw new FirewallException('Missing security key for "' . $tokenName . '" token.');
            }
        }

        $tokenCryptDriver = Security::getConfig()->get('Tokens.' . $tokenName . '.Driver', $this->defaultCryptDriver);
        $tokenCryptParams = Security::getConfig()->get('Tokens.' . $tokenName . '.Params', [], true);
        try {
            $tokenCrypt = $this->factory($tokenCryptDriver, $this->cryptDriverInterface, $tokenCryptParams);
        } catch (\Exception $e) {
            throw new FirewallException($e->getMessage());
        }

        $storageClass = Security::getConfig()->get('Tokens.' . $tokenName . '.StorageDriver');
        $this->token = new Token($this->getTokenName(), $rememberMe, $securityKey, $tokenCrypt, $storageClass);
    }
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
265912
public function generate(): string
    {
        try {
            return DefuseKey::createNewRandomKey()->saveToAsciiSafeString();
        } catch(EnvironmentIsBrokenException $e) {
            throw new CryptoException($e->getMessage(), $e->getCode(), $e);
        }
    }
219103
private function _generateSignatureKey()
    {
        $date_h = hash_hmac('sha256', $this->_date, 'AWS4' . $this->_aws_secret, true);
        $region_h = hash_hmac('sha256', $this->_region, $date_h, true);
        $service_h = hash_hmac('sha256', self::SERVICE, $region_h, true);
        $signing_h = hash_hmac('sha256', 'aws4_request', $service_h, true);

        return $signing_h;
    }
358994
public function generateToken()
    {
        $adminUser = $this->auth->getUser();
        $refreshToken = $adminUser->getRefreshToken();

        if ($refreshToken) {
            $accessToken = $this->client->getAccessToken(
                $this->configFactory->getTokenUrl(),
                $this->buildUrlParams(
                    $this->helper->encryptor->decrypt($refreshToken)
                )
            );

            if (is_string($accessToken)) {
                return $accessToken;
            }
        }

        return false;
    }
883393
protected function getUniqueToken()
    {
        $length = 64;

        if (function_exists('random_bytes')) {
            return base64_encode(random_bytes($length));
        }

        if (function_exists('openssl_random_pseudo_bytes')) {
            return base64_encode(openssl_random_pseudo_bytes($length));
        }

        if (function_exists('password_hash')) {
            // We're using a cost of only 4 since it's not a matter
            // of having a strong hash, but rather a random token
            return base64_encode(password_hash(uniqid(), PASSWORD_DEFAULT, [
                'cost' => 4
            ]));
        }

        // It seems like we don't have any decent librarues installed
        // that can produce a some what secure random string of bytes
        // so let's use some old method (which won't be as secure)

        // This is not a very cryptographically secure token, but without
        // any other extensions, you can't really do that much.

        $token = '';
        for ($i = 0; $i < 4; $i++) {
            $token .= uniqid(rand(0,10000));
        }

        return base64_encode(str_shuffle($token));
    }
697128
private function generateToken()
    {
        return Hash::hash256(self::getHa1()->getHash(), $this->getNonce(), $this->getRounds());
    }
998
protected function generateAuthorizationCode()
    {
        $tokenLen = 40;
        if (function_exists('random_bytes')) {
            $randomData = random_bytes(100);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $randomData = openssl_random_pseudo_bytes(100);
        } elseif (function_exists('mcrypt_create_iv')) {
            $randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM);
        } elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
            $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
        } else {
            $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
        }

        return substr(hash('sha512', $randomData), 0, $tokenLen);
    }