diff --git a/h5p.classes.php b/h5p.classes.php index f08eeb0..7c0e546 100644 --- a/h5p.classes.php +++ b/h5p.classes.php @@ -2790,16 +2790,8 @@ class H5PCore { * @return string token */ public static function createToken($action) { - if (!isset($_SESSION['h5p_token'])) { - // Create an unique key which is used to create action tokens for this session. - $_SESSION['h5p_token'] = uniqid(); - } - - // Timefactor - $time_factor = self::getTimeFactor(); - // Create and return token - return substr(hash('md5', $action . $time_factor . $_SESSION['h5p_token']), -16, 13); + return self::hashToken($action, self::getTimeFactor()); } /** @@ -2810,6 +2802,31 @@ class H5PCore { return ceil(time() / (86400 / 2)); } + /** + * Generate a unique hash string based on action, time and token + * + * @param string $action + * @param int $time_factor + * @return string + */ + private static function hashToken($action, $time_factor) { + if (!isset($_SESSION['h5p_token'])) { + // Create an unique key which is used to create action tokens for this session. + if (function_exists('random_bytes')) { + $_SESSION['h5p_token'] = base64_encode(random_bytes(15)); + } + else if (function_exists('openssl_random_pseudo_bytes')) { + $_SESSION['h5p_token'] = base64_encode(openssl_random_pseudo_bytes(15)); + } + else { + $_SESSION['h5p_token'] = uniqid('', TRUE); + } + } + + // Create hash and return + return substr(hash('md5', $action . $time_factor . $_SESSION['h5p_token']), -16, 13); + } + /** * Verify if the given token is valid for the given action. * @@ -2818,9 +2835,12 @@ class H5PCore { * @return boolean valid token */ public static function validToken($action, $token) { + // Get the timefactor $time_factor = self::getTimeFactor(); - return $token === substr(hash('md5', $action . $time_factor . $_SESSION['h5p_token']), -16, 13) || // Under 12 hours - $token === substr(hash('md5', $action . ($time_factor - 1) . $_SESSION['h5p_token']), -16, 13); // Between 12-24 hours + + // Check token to see if it's valid + return $token === self::hashToken($action, $time_factor) || // Under 12 hours + $token === self::hashToken($action, $time_factor - 1); // Between 12-24 hours } /**