Generator of secure random tokens.

Note that it is best to use an even number for the length.

@param int|null $length (defaults to defaultLength)
@return string Key
3707
public function generateKey($length = null) {
		if (!$length) {
			$length = $this->defaultLength;
		}

		if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
			$function = 'random_bytes';
		} elseif (extension_loaded('openssl')) {
			$function = 'openssl_random_pseudo_bytes';
		} else {
			trigger_error('Not secure', E_USER_DEPRECATED);
			return Random::pwd($length);
		}

		$value = bin2hex($function($length / 2));
		if (strlen($value) !== $length) {
			$value = str_pad($value, $length, '0');
		}
		return $value;
	}
1026204
static public function randomString( $length ) {
      $transactionhars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $size = strlen( $transactionhars );
      $str = '';
      for( $i = 0; $i < $length; $i++ )
        $str .= $transactionhars[ rand( 0, $size - 1 ) ];

      return $str;
  }
466114
protected function generate_key( $length = 64 ) {
		$unique  = md5( microtime() . rand() );
		$prepend = $this->identifier . '_batch_';

		return substr( $prepend . $unique, 0, $length );
	}
999316
public static function random($length = null)
    {
        if ($length === null) {
            $length = Configure::read('Muffin/Tokenize.length', self::DEFAULT_LENGTH);
        }

        return bin2hex(Security::randomBytes($length / 2));
    }
200507
public function createKey($length = 16)
    {
        if (function_exists('random_bytes')) {
            try {
                return random_bytes((int) $length);
            }
            catch (\Exception $e) {
                return FALSE;
            }
        } elseif (defined('MCRYPT_DEV_URANDOM')) {
            return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
        }
        $isSecure = NULL;
        $key      = openssl_random_pseudo_bytes($length, $isSecure);

        return ($isSecure === TRUE) ? $key : FALSE;
    }
416901
public static function generateKey($txt, $length = null)
    {

        date_default_timezone_set('UTC');

        $possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

        $maxlength = (empty($length) || (int)$length > strlen($possible)) ? strlen($possible) : (int)$length;
        $random = "";

        $i = 0;

        while ($i < ($maxlength / 5)) {
            // pick a random character from the possible ones
            $char = substr($possible, mt_rand(0, $maxlength - 1), 1);
            if (!strstr($random, $char)) {
                $random .= $char;
                $i++;
            }
        }

        $salt = time() . $random;
        $rand = mt_rand();
        $key = md5($rand . $txt . $salt);

        return $key;
    }
713586
protected function keygen($length)
	{
		$chars = str_shuffle('3759402687094152031368921');
		$chars = str_shuffle(str_repeat($chars, ceil($length / strlen($chars))));
		
		return strrev(str_shuffle(substr($chars, mt_rand(0, (strlen($chars) - $length - 1)), $length)));
	}
519732
public static function randomString($length)
    {
        $key = '';
        $keys = array_merge(range('a', 'z'));

        for ($i = 0; $i < $length; ++$i) {
            $key .= $keys[array_rand($keys)];
        }

        return $key;
    }
491599
protected function keygen($length)
	{
		$hex = !is_bool($this->hex) ?: $this->hex;
		$bytelength = $hex ? ceil($length / 2) : $length;

		if (function_exists('random_bytes')) {
			$bytes = random_bytes($bytelength);
		}

		elseif (function_exists('openssl_random_pseudo_bytes')) {
			$bytes = openssl_random_pseudo_bytes($bytelength);
		}

		elseif (@file_exists('/dev/urandom') && $bytelength < 100) {
			$bytes = file_get_contents('/dev/urandom', false, null, 0, $bytelength);
		}

		else {
			throw new RuntimeException('Cannot generate binary data.');
		}

		return $hex ? substr(bin2hex($bytes), 0, $length) : $bytes;
	}
674562
protected function keygen($length)
	{
		$key = '';
		$chars = array_merge(range(0, 9), range('a', 'z'), range(0, 9), range('A', 'Z'), range(0, 9));
		shuffle($chars);

		$chars = str_shuffle(str_rot13(join('', $chars)));
		$split = intval(ceil($length / 5));
		$size = strlen($chars);

		$splitSize = ceil($size / $split);
		$chunkSize = 5 + $splitSize + mt_rand(1, 5);
		$chunkArray = array();

		$chars = str_shuffle(str_repeat($chars, 2));
		$size = strlen($chars);

		while ($split != 0) {
			$strip = substr($chars, mt_rand(0, $size - $chunkSize), $chunkSize);
			array_push($chunkArray, strrev($strip));
			$split--;
		}

		foreach ($chunkArray as $set) {
			$modulus = ($length - strlen($key)) % 5;
			$adjusted = ($modulus > 0) ? $modulus : 5;

			$key .= substr($set, mt_rand(0, strlen($set) - $adjusted), $adjusted);
		}

		return str_rot13(str_shuffle($key));
	}
581507
public static function random($length = 16)
    {
        if (PHP_MAJOR_VERSION > 5) {
            return static::_random($length);
        }

        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
    }
375011
public static function randAlphabet($length)
    {
        if ($length < 0) $length = 1;
        if ($length > 64) $length = 64;
        $code = [];
        for ($i = 0; $i < $length; $i++) {
            $code[$i] = self::$alphaCodeSet[mt_rand(0, strlen(self::$alphaCodeSet) - 1)];
        }
        return implode("", $code);
    }
1184451
public static function generateRandomHandle($length = 32)
    {
        do {
            $handle = substr(md5(mt_rand(0, mt_getrandmax())), 0, $length);
        } while (static::getByField(static::$handleField, $handle));

        return $handle;
    }
995354
private function generateToken($length)
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';

        $useChars = array();
        // select some random chars:
        for ($i = 0; $i < $length; $i++) {
            $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
        }
        // Add numbers
        array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
        shuffle($useChars);
        $randomString = trim(implode('', $useChars));
        $randomString = substr($randomString, 0, self::TOKEN_LENGHT);

        return base64_encode($randomString);
    }
995263
public static function random_string($length) {
        $key = '';
        $keys = array_merge(range(0, 9), range('a', 'z'));

        for ($i = 0; $i < $length; $i++) {
            $key .= $keys[array_rand($keys)];
        }

        return $key;
    }
1054996
private function generateToken($length = 6)
    {
        $token = Yii::$app->security->generateRandomString($length);
        $replace = array_rand(range(2, 9));
        return str_replace(['-', '_', 'l', 1], $replace, strtolower($token));
    }
659251
public static function getUniqueToken(int $length = 40): string
    {
        $token        = '';
        $codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz';
        $codeAlphabet .= '0123456789';
        $max          = strlen($codeAlphabet); // edited

        for ($i = 0; $i < $length; $i++) {
            $token .= $codeAlphabet[self::getSecureRandomInt(0, $max - 1)];
        }

        return $token;
    }