我现在真的是一个选择 . 但是,我发现PHP 7 's new CS functions so I' ve的polyfill实现了该解决方案(https://github.com/paragonie/random_compat) .
我认为srand()可以用来播种random_int(),但现在我不确定是不是这样 . CSPRNG甚至可以播种吗?如果它可以播种,输出是否是确定性的(相同的随机结果,给定相同的种子)?
这是我的代码:
require_once($_SERVER['DOCUMENT_ROOT']."/lib/assets/random_compat/lib/random.php");
$seed_a = 8138707157292429635;
$seed_b = 'JuxJ1XLnBKk7gPASR80hJfq5Ey8QWEIc8Bt';
class CSPRNG{
private static $RNGseed = 0;
public function generate_seed_a(){
return random_int(0, PHP_INT_MAX);
}
public function generate_seed_b($length = 35){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for($i = 0; $i < $length; $i++){
$randomString .= $characters[random_int(0, strlen($characters) - 1)];
}
return $randomString;
}
public function seed($s = 0) {
if($s == 0){
$this->RNGseed = $this->generate_seed_a();
}else{
$this->RNGseed = $s;
}
srand($this->RNGseed);
}
public function generate_random_integer($min=0, $max=PHP_INT_MAX, $pad_zeros = true){
if($this->RNGseed == 0){
$this->seed();
}
$rnd_num = random_int($min, $max);
if($pad_zeros == true){
$num_digits = strlen((string)$max);
$format_str = "%0".$num_digits."d";
return sprintf($format_str, $rnd_num);
}else{
return $rnd_num;
}
}
public function drawing_numbers($seed_a, $num_of_balls = 6){
$this->seed($seed_a);
$draw_numbers = array();
for($i = 0; $i < $num_of_balls; $i++) {
$number = ($this->generate_random_integer(1, 49));
if(in_array($number, $draw_numbers)){
$i = $i-1;
}else{
array_push($draw_numbers, $number);
}
}
sort($draw_numbers);
return $draw_numbers;
}
}
$CSPRNG= new CSPRNG();
echo '
Seed A: '.$seed_a.'
';echo '
Seed B: '.$seed_b.'
';$hash = hash('sha1', $seed_a.$seed_b);
echo '
Hash: '.$hash.'
';$drawNumbers = $CSPRNG->drawing_numbers($seed_a);
$draw_str = implode("-", $drawNumbers);
echo "
Drawing: $draw_str
";
运行此代码时,Drawing($ draw_str)在每次运行时都应该相同,但事实并非如此 .
为了证明绘图是公平的,在挑选和显示中奖号码之前选择种子(种子A) . 还生成另一个随机数(种子B) . 将种子B用作盐并与种子A组合,并将结果进行哈希处理 . 在绘图之前向用户显示该哈希 . 他们还将获得源代码,以便在挑选获胜号码时,揭示两个种子 . 他们可以验证哈希匹配并且一切都公平地完成 .