I am using the following code in my application. It takes 128 bytes of random data (converts to a hexadecimal string) and takes two characters at a time, converting them to decimal numbers and checking that they are in the valid range (alphanumeric, with characters, no spaces or characters that won't play well with your editor or configuration file - aka no ')
32 characters is 128 bits, so it works well with block ciphers.
function random_key_string() { $source = bin2hex(openssl_random_pseudo_bytes(128)); $string = ''; $c = 0; while(strlen($string) < 32) { $dec = gmp_strval(gmp_init(substr($source, $c*2, 2), 16),10); if($dec > 33 && $dec < 127 && $dec !== 39) $string.=chr($dec); $c++; } return $string; }
karimkorun
source share