Fixed issue with Math\Rand::getInteger() on ranges close to PHP_INT_MAX #5614

Merged
merged 3 commits into from Mar 5, 2014

Projects

None yet

5 participants

@denixport

When min - max range is close or equal to PHP_INT_MAX log() produces number of bits
equal to machine size integer. So $filter = (int) ((1 << $bits) - 1); evaluates to zero.
In this case getInteger(0, PHP_INT_MAX) returns only zeros.

PR includes correct bit calculation and test

@samsonasik samsonasik commented on an outdated diff Dec 15, 2013
library/Zend/Math/Rand.php
do {
- $rnd = hexdec(bin2hex(self::getBytes($bytes, $strong)));
- $rnd = $rnd & $filter;
+ $rnd = hexdec(bin2hex(self::getBytes($bytes, $strong)));
@samsonasik
samsonasik Dec 15, 2013

use static::getBytes instead of self::getBytes

@ezimuel

If you want to be sure (high probability) that Rand::getInteger does not give only zero values you should increase the number of cycles, for instance from 5 to 100.

@ezimuel

Why are you using the XOR operator here? The sum (+=) is not a better choice here?

Actually the purpose of the test was also to ensure that getInteger() does not return same value (not just zero) on every call. There is a chance that total sum of values would be 0 so += could produce false positives, but you're right ^= doesn't work either. I will come up with better test.

@weierophinney weierophinney added this to the 2.2.6 milestone Mar 3, 2014
@ezimuel ezimuel merged commit cc11994 into zendframework:master Mar 5, 2014

1 check passed

Details default The Travis CI build passed
@Maks3w
Member
Maks3w commented May 1, 2015

Is it normal $values to be negative?

I've changed the test for assert $values to be greater than 0

1) ZendTest\Math\RandTest::testIntegerRangeOverflow
Failed asserting that -5.1650883406387E+20 is greater than 0.

https://travis-ci.org/zendframework/zf2/jobs/60848303#L1081

@Maks3w
Member
Maks3w commented May 1, 2015

Ok, I see what is happenning. $values probably has a value which produce a int overflow as result of operate with big numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment