stringutils.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * @author Lukas Reschke <lukas@owncloud.com>
  4. * @author Morris Jobke <hey@morrisjobke.de>
  5. *
  6. * @copyright Copyright (c) 2015, ownCloud, Inc.
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OC\Security;
  23. class StringUtils {
  24. /**
  25. * Compares whether two strings are equal. To prevent guessing of the string
  26. * length this is done by comparing two hashes against each other and afterwards
  27. * a comparison of the real string to prevent against the unlikely chance of
  28. * collisions.
  29. *
  30. * Be aware that this function may leak whether the string to compare have a different
  31. * length.
  32. *
  33. * @param string $expected The expected value
  34. * @param string $input The input to compare against
  35. * @return bool True if the two strings are equal, otherwise false.
  36. */
  37. public static function equals($expected, $input) {
  38. if(!is_string($expected) || !is_string($input)) {
  39. return false;
  40. }
  41. if(function_exists('hash_equals')) {
  42. return hash_equals($expected, $input);
  43. }
  44. $randomString = \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(10);
  45. if(hash('sha512', $expected.$randomString) === hash('sha512', $input.$randomString)) {
  46. if($expected === $input) {
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. }