ILIAS  release_4-3 Revision
 All Data Structures Namespaces Files Functions Variables Groups Pages
CryptUtil.php
Go to the documentation of this file.
1 <?php
2 
18 if (!defined('Auth_OpenID_RAND_SOURCE')) {
23  define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
24 }
25 
40  static function getBytes($num_bytes)
41  {
42  static $f = null;
43  $bytes = '';
44  if ($f === null) {
45  if (Auth_OpenID_RAND_SOURCE === null) {
46  $f = false;
47  } else {
48  $f = @fopen(Auth_OpenID_RAND_SOURCE, "r");
49  if ($f === false) {
50  $msg = 'Define Auth_OpenID_RAND_SOURCE as null to ' .
51  ' continue with an insecure random number generator.';
52  trigger_error($msg, E_USER_ERROR);
53  }
54  }
55  }
56  if ($f === false) {
57  // pseudorandom used
58  $bytes = '';
59  for ($i = 0; $i < $num_bytes; $i += 4) {
60  $bytes .= pack('L', mt_rand());
61  }
62  $bytes = substr($bytes, 0, $num_bytes);
63  } else {
64  $bytes = fread($f, $num_bytes);
65  }
66  return $bytes;
67  }
68 
80  static function randomString($length, $population = null)
81  {
82  if ($population === null) {
83  return Auth_OpenID_CryptUtil::getBytes($length);
84  }
85 
86  $popsize = strlen($population);
87 
88  if ($popsize > 256) {
89  $msg = 'More than 256 characters supplied to ' . __FUNCTION__;
90  trigger_error($msg, E_USER_ERROR);
91  }
92 
93  $duplicate = 256 % $popsize;
94 
95  $str = "";
96  for ($i = 0; $i < $length; $i++) {
97  do {
99  } while ($n < $duplicate);
100 
101  $n %= $popsize;
102  $str .= $population[$n];
103  }
104 
105  return $str;
106  }
107 }
108