Skip to content
Snippets Groups Projects
Commit 0be44456 authored by Peter Rotich's avatar Peter Rotich
Browse files

Merge pull request #1672 from greezybacon/issue/not-so-random-codes


Fix very predictable random data on some platforms

Reviewed-By: default avatarPeter Rotich <peter@osticket.com>
parents e50b63a0 2a358417
No related branches found
No related tags found
No related merge requests found
...@@ -16,14 +16,31 @@ ...@@ -16,14 +16,31 @@
class Misc { class Misc {
function randCode($count=8, $chars=false) { function randCode($len=8, $chars=false) {
$chars = $chars ? $chars $chars = $chars ?: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_=';
: 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.';
$data = ''; // Determine the number of bits we need
$m = strlen($chars) - 1; $char_count = strlen($chars);
for ($i=0; $i < $count; $i++) $bits_per_char = ceil(log($char_count, 2));
$data .= $chars[mt_rand(0,$m)]; $bytes = ceil(4 * $len / floor(32 / $bits_per_char));
return $data; // Pad to 4 byte boundary
$bytes += (4 - ($bytes % 4)) % 4;
// Fetch some random data blocks
$data = Crypto::random($bytes);
$mask = (1 << $bits_per_char) - 1;
$loops = (int) (32 / $bits_per_char);
$output = '';
$ints = unpack('V*', $data);
array_shift($ints);
foreach ($ints as $int) {
for ($i = $loops; $i > 0; $i--) {
$output .= $chars[($int & $mask) % $char_count];
$int >>= $bits_per_char;
}
}
return substr($output, 0, $len);
} }
function __rand_seed($value=0) { function __rand_seed($value=0) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment