SecureRandom.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Security;
  27. use OCP\Security\ISecureRandom;
  28. /**
  29. * Class SecureRandom provides a wrapper around the random_int function to generate
  30. * secure random strings. For PHP 7 the native CSPRNG is used, older versions do
  31. * use a fallback.
  32. *
  33. * Usage:
  34. * \OC::$server->getSecureRandom()->generate(10);
  35. * @package OC\Security
  36. */
  37. class SecureRandom implements ISecureRandom {
  38. /**
  39. * Generate a secure random string of specified length.
  40. * @param int $length The length of the generated string
  41. * @param string $characters An optional list of characters to use if no character list is
  42. * specified all valid base64 characters are used.
  43. * @return string
  44. * @throws \LengthException if an invalid length is requested
  45. */
  46. public function generate(int $length,
  47. string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'): string {
  48. if ($length <= 0) {
  49. throw new \LengthException('Invalid length specified: ' . $length . ' must be bigger than 0');
  50. }
  51. $maxCharIndex = \strlen($characters) - 1;
  52. $randomString = '';
  53. while ($length > 0) {
  54. $randomNumber = \random_int(0, $maxCharIndex);
  55. $randomString .= $characters[$randomNumber];
  56. $length--;
  57. }
  58. return $randomString;
  59. }
  60. }