3 // Cryptographically secure random number generation
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) {
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;
25 if ($this->use_urandom
) {
26 while (strlen($res) < $num) {
27 $res .= fread($this->urandom_filehandle
, $num - strlen($res));
30 for ($i=0; $i<$num; $i++
) {
31 $res .= chr(mt_rand(0, 255));
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;
48 $random = new LoomRandom();
49 echo $random->random_id() . "\n";
53 /* ***** BEGIN LICENSE BLOCK *****
54 * Version: MPL 1.1/GPL 2.0/LGPL 2.1/Apache 2.0
56 * The contents of this file are subject to the Mozilla Public License Version
57 * 1.1 (the "License"); you may not use this file except in compliance with
58 * the License. You may obtain a copy of the License at
59 * http://www.mozilla.org/MPL/
61 * Software distributed under the License is distributed on an "AS IS" basis,
62 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
63 * for the specific language governing rights and limitations under the
66 * The Original Code is LoomClient PHP library
68 * The Initial Developer of the Original Code is
70 * Portions created by the Initial Developer are Copyright (C) 2008
71 * the Initial Developer. All Rights Reserved.
74 * Bill St. Clair <bill@billstclair.com>
76 * Alternatively, the contents of this file may be used under the
77 * terms of the GNU General Public License Version 2 or later (the
78 * "GPL"), the GNU Lesser General Public License Version 2.1 or later
79 * (the "LGPL"), or The Apache License Version 2.0 (the "AL"), in
80 * which case the provisions of the GPL, LGPL, or AL are applicable
81 * instead of those above. If you wish to allow use of your version of
82 * this file only under the terms of the GPL, the LGPL, or the AL, and
83 * not to allow others to use your version of this file under the
84 * terms of the MPL, indicate your decision by deleting the provisions
85 * above and replace them with the notice and other provisions
86 * required by the GPL or the LGPL. If you do not delete the
87 * provisions above, a recipient may use your version of this file
88 * under the terms of any one of the MPL, the GPL the LGPL, or the AL.
89 ****** END LICENSE BLOCK ***** */