0

help me find the meaning and efficiency

I found a strange function for generating a random value $code = $this->secureRandValue(1000, 9999) and decided to look at the implementation protected function secureRandValue($min, $max) { $range = $max - $min; if ($range == 0) return $min; // not so random... $log = log($range, 2); $bytes = (int)($log / 8) + 1; // length in bytes $bits = (int)$log + 1; // length in bits $filter = (int)(1 << $bits) - 1; // set all lower bits to 1 do { $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s))); $rnd = $rnd & $filter; // discard irrelevant bits } while ($rnd >= $range); return $min + $rnd; } smoked for a long time and thought about the essence of the universe....

29th Jul 2024, 1:38 PM
ŠŠ»ŠµŠŗсŠ°Š½Š“р Š˜Š²Š°Š½Š¾Š²
ŠŠ»ŠµŠŗсŠ°Š½Š“р Š˜Š²Š°Š½Š¾Š² - avatar
1 Answer
0
The function is a little deceptive. The parameters (1000, 9999) lead you to believe the return value will be a random number between 1000 and 9999. What it actually returns is a random value between 1000 and (1000+16383) (inclusive) in this case. It re-adjusts the high end of the returned range to the sum of the low value + the next power of 2 that can accommodate the range, minus 1. The random value comes from openssl_random_pseudo_bytes(). The rest of the function code is merely determining how many bytes to retrieve, how many bits can hold the high number, and creating a bitmask to keep the binary magnitude down to the desired number of bits.
29th Jul 2024, 7:04 PM
Brian
Brian - avatar