stringutils.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. class StringUtils {
  10. /**
  11. * Compares whether two strings are equal. To prevent guessing of the string
  12. * length this is done by comparing two hashes against each other and afterwards
  13. * a comparison of the real string to prevent against the unlikely chance of
  14. * collisions.
  15. *
  16. * Be aware that this function may leak whether the string to compare have a different
  17. * length.
  18. *
  19. * @param string $expected The expected value
  20. * @param string $input The input to compare against
  21. * @return bool True if the two strings are equal, otherwise false.
  22. */
  23. public static function equals($expected, $input) {
  24. if(!is_string($expected) || !is_string($input)) {
  25. return false;
  26. }
  27. if(function_exists('hash_equals')) {
  28. return hash_equals($expected, $input);
  29. }
  30. $randomString = \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(10);
  31. if(hash('sha512', $expected.$randomString) === hash('sha512', $input.$randomString)) {
  32. if($expected === $input) {
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38. }