Skip to content

Instantly share code, notes, and snippets.

@mrevjd
Forked from inda5th/generate_random_key.php
Created March 8, 2021 01:47
Show Gist options
  • Select an option

  • Save mrevjd/feda80b06f290fce8385514d7d748d34 to your computer and use it in GitHub Desktop.

Select an option

Save mrevjd/feda80b06f290fce8385514d7d748d34 to your computer and use it in GitHub Desktop.
Generate a random key to be used based on a specified hashing algorithm.
<?php
/**
* Generate a random key
*
* Generate a random key based on the specified hashing algorithm and given length.
* The algorithm defaults to "sha256" and the length defaults to 1024.
* See PHP's hash_algos() function for a list of supported hashing algorithms.
*
* @param string $algo The hashing algorithm to use
* @param int $length Length of desired string of bytes to create the hash
* @return string Random hash
* @access public
*/
function generate_random_key($algo = 'sha256', $length = 1024)
{
$key = '';
// Check if the openssl_random_pseudo_bytes() function exists
if ( function_exists('openssl_random_pseudo_bytes') )
{ // It does exist so let's use it to generate a string of random bytes to hash
$data = openssl_random_pseudo_bytes($length, $cstrong) . mt_rand() . microtime();
$key = hash($algo, $data);
} else
{ // It doesn't exist, but have no fear... We will attempt to read from /dev/urandom instead
// Even if the file_get_contents() function returns FALSE, a hash will still be generated based on
// a random number from mt_rand() and the microtime()
$data = mt_rand() . microtime() . file_get_contents('/dev/urandom', $length) . mt_rand() . microtime();
$key = hash($algo, $data);
}
return $key;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment