New article: Trubanc Server Working
[loomclient.git] / LoomRandom.php
blob1b1a13b1d2eae31ed8d3c61c128b5971b9534bbe
1 <?php
3 // Cryptographically secure random number generation
5 class LoomRandom {
7 var $urandom_filehandle; // /dev/urandom file handle
8 var $use_urandom; // false if we can't open /dev/urandom
10 function LoomRandom() {
11 $this->urandom_filehandle = false;
12 $this->use_urandom = true;
15 // Return $num random bytes from /dev/urandom
16 function urandom_bytes($num) {
17 if ($num < 0)
18 err("NUM must be nonnegative in urandom_bytes");
19 if ($this->use_urandom && !$this->urandom_filehandle) {
20 $file = @fopen("/dev/urandom", "r");
21 if (!$file) $this->use_urandom = false;
22 else $this->urandom_filehandle = $file;
24 $res = '';
25 if ($this->use_urandom) {
26 while (strlen($res) < $num) {
27 $res .= fread($this->urandom_filehandle, $num - strlen($res));
29 } else {
30 for ($i=0; $i<$num; $i++) {
31 $res .= chr(mt_rand(0, 255));
34 return $res;
37 // Return a random 128-bit location, as hex
38 function random_id() {
39 $res = bin2hex($this->urandom_bytes(16));
40 if (strlen($res) < 32) $res = str_repeat("0", 32 - strlen($res)) . $res;
41 return $res;
46 /* testing code
48 $random = new LoomRandom();
49 echo $random->random_id() . "\n";
53 // Copyright 2008 Bill St. Clair
55 // Licensed under the Apache License, Version 2.0 (the "License");
56 // you may not use this file except in compliance with the License.
57 // You may obtain a copy of the License at
59 // http://www.apache.org/licenses/LICENSE-2.0
61 // Unless required by applicable law or agreed to in writing, software
62 // distributed under the License is distributed on an "AS IS" BASIS,
63 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64 // See the License for the specific language governing permissions
65 // and limitations under the License.