securerandom.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace OC\Security;
  9. use RandomLib;
  10. use Sabre\DAV\Exception;
  11. use OCP\Security\ISecureRandom;
  12. /**
  13. * Class SecureRandom provides a layer around RandomLib to generate
  14. * secure random strings.
  15. *
  16. * Usage:
  17. * \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(10);
  18. *
  19. * @package OC\Security
  20. */
  21. class SecureRandom implements ISecureRandom {
  22. /** @var \RandomLib\Factory */
  23. var $factory;
  24. /** @var \RandomLib\Generator */
  25. var $generator;
  26. function __construct() {
  27. $this->factory = new RandomLib\Factory;
  28. }
  29. /**
  30. * Convenience method to get a low strength random number generator.
  31. *
  32. * Low Strength should be used anywhere that random strings are needed
  33. * in a non-cryptographical setting. They are not strong enough to be
  34. * used as keys or salts. They are however useful for one-time use tokens.
  35. *
  36. * @return $this
  37. */
  38. public function getLowStrengthGenerator() {
  39. $this->generator = $this->factory->getLowStrengthGenerator();
  40. return $this;
  41. }
  42. /**
  43. * Convenience method to get a medium strength random number generator.
  44. *
  45. * Medium Strength should be used for most needs of a cryptographic nature.
  46. * They are strong enough to be used as keys and salts. However, they do
  47. * take some time and resources to generate, so they should not be over-used
  48. *
  49. * @return $this
  50. */
  51. public function getMediumStrengthGenerator() {
  52. $this->generator = $this->factory->getMediumStrengthGenerator();
  53. return $this;
  54. }
  55. /**
  56. * Generate a random string of specified length.
  57. * @param string $length The length of the generated string
  58. * @param string $characters An optional list of characters to use if no characterlist is
  59. * specified all valid base64 characters are used.
  60. * @return string
  61. * @throws \Exception If the generator is not initialized.
  62. */
  63. public function generate($length, $characters = '') {
  64. if(is_null($this->generator)) {
  65. throw new \Exception('Generator is not initialized.');
  66. }
  67. return $this->generator->generateString($length, $characters);
  68. }
  69. }