Changeset 28615


Ignore:
Timestamp:
Jun 3, 2014, 10:07:32 AM (10 years ago)
Author:
plg
Message:

bug 3082: increase generate_key randomness with openssl_random_pseudo_bytes (with fallback on mt_rand for Windows+PHP<5.3.4)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/include/functions_session.inc.php

    r28591 r28615  
    5959 *
    6060 * @param int $size
    61  * @param string $alphabet chars to use in the key,
    62  *    default is all digits and all letters uppercase and lowercase
    6361 * @return string
    6462 */
    65 function generate_key($size, $alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    66 {
    67   $l = strlen($alphabet)-1;
    68   $key = '';
    69   for ($i=0; $i<$size; $i++)
    70   {
    71     $key.= $alphabet[mt_rand(0, $l)];
    72   }
    73   return $key;
     63function generate_key($size)
     64{
     65  if (
     66    is_callable('openssl_random_pseudo_bytes')
     67    and !(version_compare(PHP_VERSION, '5.3.4') < 0 and defined('PHP_WINDOWS_VERSION_MAJOR'))
     68    )
     69  {
     70    return substr(
     71      str_replace(
     72        array('+', '/'),
     73        '',
     74        base64_encode(openssl_random_pseudo_bytes($size))
     75        ),
     76      0,
     77      $size
     78      );
     79  }
     80  else
     81  {
     82    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
     83    $l = strlen($alphabet)-1;
     84    $key = '';
     85    for ($i=0; $i<$size; $i++)
     86    {
     87      $key.= $alphabet[mt_rand(0, $l)];
     88    }
     89    return $key;
     90  }
    7491}
    7592
Note: See TracChangeset for help on using the changeset viewer.