Generate random prime
barryvdh opened this issue · 1 comments
barryvdh commented
Instead of letting the user pick a prime, why not find a random one with php? Or is that more insecure?
Something like this in the Spark command for example, when the prime is empty (Although random_int
would be safer in PHP7)
protected function findRandomPrime()
{
$min = 1e6;
$max = 2147483647;
for ($i=rand($min, $max); $i < $max; $i++) {
if ($this->isPrime($i)) {
return $i;
}
}
}
/**
* From http://stackoverflow.com/a/16763365/444215
* @param $num
* @return bool
*/
protected function isPrime($num){
/**
* if the number is divisible by two, then it's not prime and it's no longer
* needed to check other even numbers
*/
if($num % 2 == 0) {
return false;
}
/**
* Checks the odd numbers. If any of them is a factor, then it returns false.
* The sqrt can be an aproximation, hence just for the sake of
* security, one rounds it to the next highest integer value.
*/
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}