Fix a comment
[loomclient.git] / LoomRandom.php
blobb904e6d6ec3e600ae310ee48b79931de11c7506d
1 <?php
3 // Cryptographically secure random number generation
5 class LoomRandom {
7 var $urandom_filehandle; // /dev/urandom file handle
9 function LoomRandom() {
10 $this->urandom_filehandle = false;
13 // Return $num random bytes from /dev/urandom
14 function urandom_bytes($num) {
15 if ($num < 0)
16 err("NUM must be nonnegative in urandom_bytes");
17 if (!$this->urandom_filehandle) {
18 $file = fopen("/dev/urandom", "r");
19 if (!$file) err("Unable to open /dev/urandom");
20 $this->urandom_filehandle = $file;
22 $res = '';
23 while (strlen($res) < $num)
24 $res .= fread($this->urandom_filehandle, $num - strlen($res));
25 return $res;
28 // Return a random 128-bit location, as hex
29 function random_id() {
30 return bin2hex($this->urandom_bytes(16));
35 /* testing code
37 $random = new LoomRandom();
38 echo $random->random_id() . "\n";
42 // Copyright 2008 Bill St. Clair
44 // Licensed under the Apache License, Version 2.0 (the "License");
45 // you may not use this file except in compliance with the License.
46 // You may obtain a copy of the License at
48 // http://www.apache.org/licenses/LICENSE-2.0
50 // Unless required by applicable law or agreed to in writing, software
51 // distributed under the License is distributed on an "AS IS" BASIS,
52 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
53 // See the License for the specific language governing permissions
54 // and limitations under the License.