Such noise

This commit is contained in:
Shoghi Cervantes
2014-02-12 09:45:38 +01:00
parent 26772082da
commit 1bc54dbc44
10 changed files with 430 additions and 262 deletions

View File

@@ -22,25 +22,15 @@
//Unsecure, not used for "Real Randomness"
class Random{
private $x, $y, $z, $w;
private $z, $w;
public function __construct($seed = false){
$this->setSeed($seed);
}
public function setSeed($seed = false){
$seed = $seed !== false ? Utils::writeInt((int) $seed):Utils::getRandomBytes(4, false);
$state = array();
for($i = 0; $i < 256; ++$i){
$state[] = $i;
}
for($i = $j = 0; $i < 256; ++$i){
$j = ($j + ord($seed{$i & 0x03}) + $state[$i]) & 0xFF;
$state[$i] ^= $state[$j];
$state[$j] ^= $state[$i];
$state[$i] ^= $state[$j];
}
$this->state = $state;
$this->i = $this->j = 0;
$seed = $seed !== false ? (int) $seed:Utils::readInt(Utils::getRandomBytes(4, false));
$this->z = $seed ^ 0xdeadbeef;
$this->w = $seed ^ 0xc0de1337;
}
public function nextInt(){
@@ -61,19 +51,16 @@ class Random{
public function nextBytes($byteCount){
$bytes = "";
for($i = 0; $i < $byteCount; ++$i){
$this->i = ($this->i + 1) & 0xFF;
$this->j = ($this->j + $this->state[$this->i]) & 0xFF;
$this->state[$this->i] ^= $this->state[$this->j];
$this->state[$this->j] ^= $this->state[$this->i];
$this->state[$this->i] ^= $this->state[$this->j];
$bytes .= chr($this->state[($this->state[$this->i] + $this->state[$this->j]) & 0xFF]);
while(strlen($bytes) < $byteCount){
$this->z = 36969 * ($this->z & 65535) + ($this->z >> 16);
$this->w = 18000 * ($this->w & 65535) + ($this->w >> 16);
$bytes .= pack("N", ($this->z << 16) + $this->w);
}
return $bytes;
return substr($bytes, 0, $byteCount);
}
public function nextBoolean(){
return ($this->nextBytes(1) & 0x01) == 0;
return ($this->nextSignedInt() & 0x01) === 0;
}
public function nextRange($start = 0, $end = PHP_INT_MAX){