1
0

SecureRandom.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Security;
  9. use OCP\Security\ISecureRandom;
  10. /**
  11. * Class SecureRandom provides a wrapper around the random_int function to generate
  12. * secure random strings. For PHP 7 the native CSPRNG is used, older versions do
  13. * use a fallback.
  14. *
  15. * Usage:
  16. * \OC::$server->get(ISecureRandom::class)->generate(10);
  17. * @package OC\Security
  18. */
  19. class SecureRandom implements ISecureRandom {
  20. /**
  21. * Generate a secure random string of specified length.
  22. * @param int $length The length of the generated string
  23. * @param string $characters An optional list of characters to use if no character list is
  24. * specified all valid base64 characters are used.
  25. * @throws \LengthException if an invalid length is requested
  26. */
  27. public function generate(
  28. int $length,
  29. string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
  30. ): string {
  31. if ($length <= 0) {
  32. throw new \LengthException('Invalid length specified: ' . $length . ' must be bigger than 0');
  33. }
  34. $maxCharIndex = \strlen($characters) - 1;
  35. $randomString = '';
  36. while ($length > 0) {
  37. $randomNumber = \random_int(0, $maxCharIndex);
  38. $randomString .= $characters[$randomNumber];
  39. $length--;
  40. }
  41. return $randomString;
  42. }
  43. }