Last active
March 8, 2021 01:47
-
-
Save inda5th/4552792 to your computer and use it in GitHub Desktop.
Generate a random key to be used based on a specified hashing algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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