Generate a new key

@param string $hash
@param int $length
@param string $key
@return string
1201
private function newKey($hash, $length, $key = '')
  {
    $generated = $this->hasReq(Hash::secure($length));

    if ($hash == 'base64') {
      $key = 'base64:' . base64_encode($generated);
    } else {
      $key = $hash . ':' . $generated;
    }

    return $key;
  }
1309619
public static String createAlphanumericHash(final String str, final int length) {
		try {
			final MessageDigest md = MessageDigest.getInstance("SHA-256");
			final byte[] digest = md.digest(str.getBytes(CHARSET_UTF8));
			// To human
			final StringBuilder sb = new StringBuilder();
			for (final byte b : digest) {
				if (b < 16) sb.append("0");
				sb.append(Integer.toHexString(b & 0xff));
			}
			// repeat if to small
			while (sb.length() < length) {
				sb.append(sb.toString());
			}
			// truncation and return
			return sb.delete(length, sb.length()).toString();
		} catch (NoSuchAlgorithmException | UnsupportedCharsetException e) {
			// Hashalgo. and charset is mandatory for all kinds of JDK, so this should happend. But even when, we generate a random string.
			return createRandomAlphanumeric(length);
		}
	}
1030677
public static function generateSafeHash($length=16)
    {
        $factory = new CryptLib\Random\Factory;
        return preg_replace('/[^A-Za-z0-9\-]/', '', $factory->getLowStrengthGenerator()->generateString($length));
    }
923980
public static function isHash($hash, int $length = 32): bool
    {
        return (is_string($hash) || is_int($hash)) && preg_match('#^[0-9a-f]{'.$length.'}$#i', $hash);
    }
65935
public function generateHmac($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentForHashGenerationException('A hash can only be generated for a string, but "' . gettype($string) . '" was given.', 1255069587);
        }

        return hash_hmac('sha1', $string, $this->getEncryptionKey());
    }
1021750
protected function createToken($length = 32)
    {
        static $chars = '0123456789abcdef';
        $max = strlen($chars) - 1;
        $token = '';
        $name = $this->getName();

        for ($i = 0; $i < $length; ++$i) {
            $token .= $chars[(mt_rand(0, $max))];
        }

        return md5($token . $name);
    }
157186
public function generateHardReadableString($length)
    {
        try {
            return $this->driverInstance->generateHardReadableString($length);
        } catch (\Exception $e) {
            throw new CryptException($e->getMessage());
        }
    }
1349772
public static function getHashedToken($length = 25)
    {
        $token = "";
        $max   = strlen(static::getPool());
        for ($i = 0; $i < $length; $i++) {
            $token .= static::getPool()[static::secureCrypt(0, $max)];
        }

        return $token;
    }
1020966
public function getRange($key, $length) {
        $badKeys = [];

        for ($i = 0; $i < $key; $i++) {
            array_push($badKeys, $i);
        }

        for ($i = $key + $length; $i < count($this->_datas); $i++) {
            array_push($badKeys, $i);
        }

        return array_diff_key($this->_datas, array_flip($badKeys));
    }
1138097
public static function generateSalt($length)
    {
        mt_srand(intval(microtime(true)*100000 + memory_get_usage(true)));
        return substr(sha1(uniqid(mt_rand(), true)), 0, $length);
    }
449257
private function _returnHash(string $hash, int $length)
    {
        try {
            return substr($hash, 0, $length);
        } catch (\Exception $e) { }

        return false;
    }
989180
public static function make(?string $salt, ?int $length, ?string $alphabet)
    {
        $salt     = is_null($salt) ? config('hashids.salt') : config('hashids.salt') . $salt;
        $length   = $length   ?? config('hashids.length');
        $alphabet = $alphabet ?? config('hashids.alphabet');
        $salt     = \Illuminate\Support\Facades\Hash::make($salt);

        return new self($salt, $length, $alphabet);
    }
1103759
private function expand(RawBytes $pseudoRandomKey, string $info, int $length) : BinaryString
    {
        $T = new BinaryString('');
        $outputKeyingMaterial = new BinaryString('');

        for ($blockIndex = 1; $blockIndex <= (int) ceil($length / 32); $blockIndex++) {
            $T = new BinaryString(hash_hmac(
                'sha256',
                $T->getRawBytes() . $info . chr($blockIndex),
                $pseudoRandomKey->getRawBytes(),
                true
            ));
            $outputKeyingMaterial = $outputKeyingMaterial->concat($T);
        }

        return $outputKeyingMaterial->slice($length);
    }
24114
public static function generate($length = 8, $type = self::ALPHANUMERIC_STRING)
    {
        if ($type !== self::ALPHAHASH_STRING) {
            switch ($type) {
                default:
                case self::ALPHANUMERIC_STRING:
                    $codeAlphabet = implode(range('A', 'Z')); // Uppercase Alphabet
                    $codeAlphabet .= implode(range('a', 'z')); // Lowercase Alphabet
                    $codeAlphabet .= implode(range(0, 9)); // Numeric Alphabet
                    break;
                case self::ALPHAUPPERCASE_STRING:
                    $codeAlphabet = implode(range('A', 'Z')); // Uppercase Alphabet
                    break;
                case self::ALPHALOWERCASE_STRING:
                    $codeAlphabet = implode(range('a', 'z')); // Lowercase Alphabet
                    break;
                case self::NUMERIC_STRING:
                    $codeAlphabet = implode(range(0, 9)); // Numeric Alphabet
                    break;
            }

            $token = '';
            $max = strlen($codeAlphabet);

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

            return $token;
        }

        /**
         * ALPHABIN2HEX_STRING
         */
        if (function_exists('random_bytes')) {
            $randomData = random_bytes(20);
            if ($randomData !== false && strlen($randomData) === 20) {
                return bin2hex($randomData);
            }
        }
        if (function_exists('openssl_random_pseudo_bytes')) {
            $randomData = openssl_random_pseudo_bytes(20);
            if ($randomData !== false && strlen($randomData) === 20) {
                return bin2hex($randomData);
            }
        }
        if (function_exists('mcrypt_create_iv')) {
            $randomData = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM);
            if ($randomData !== false && strlen($randomData) === 20) {
                return bin2hex($randomData);
            }
        }
        if (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
            $randomData = file_get_contents('/dev/urandom', false, null, 0, 20);
            if ($randomData !== false && strlen($randomData) === 20) {
                return bin2hex($randomData);
            }
        }
        // Last resort which you probably should just get rid of:
        $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);

        return substr(hash('sha512', $randomData), 0, $length);
    }
831714
private static int hash(char []key, int length)
  {
    int hash = 17;

    for (int i = length - 1; i >= 0; i--) {
      char a = key[i];

      if ('A' <= a && a <= 'Z')
        a += 'a' - 'A';
      
      hash = 65537 * hash + a;
    }

    return hash;
  }
78523
public function generateBase32RandomKey($length = 16, $prefix = '')
    {
        $secret = $prefix ? $this->toBase32($prefix) : '';

        $secret = $this->strPadBase32($secret, $length);

        $this->validateSecret($secret);

        return $secret;
    }
1057248
public static function genRandomPassword($length = 8)
	{
		$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$base = strlen($salt);
		$makepass = '';

		// Start with a cryptographic strength random string, then convert it to
		// a string with the numeric base of the salt.
		// Shift the base conversion on each character so the character
		// distribution is even, and randomize the start shift so it's not
		// predictable.
		$random = \Hubzero\Encryption\Encrypter::genRandomBytes($length + 1);
		$shift = ord($random[0]);
		for ($i = 1; $i <= $length; ++$i)
		{
			$makepass .= $salt[($shift + ord($random[$i])) % $base];
			$shift += ord($random[$i]);
		}

		return $makepass;
	}