Php55.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Polyfill\Php55;
  11. /**
  12. * @internal
  13. */
  14. final class Php55
  15. {
  16. public static function boolval($val)
  17. {
  18. return (bool) $val;
  19. }
  20. public static function json_last_error_msg()
  21. {
  22. switch (json_last_error()) {
  23. case JSON_ERROR_NONE: return 'No error';
  24. case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded';
  25. case JSON_ERROR_STATE_MISMATCH: return 'State mismatch (invalid or malformed JSON)';
  26. case JSON_ERROR_CTRL_CHAR: return 'Control character error, possibly incorrectly encoded';
  27. case JSON_ERROR_SYNTAX: return 'Syntax error';
  28. case JSON_ERROR_UTF8: return 'Malformed UTF-8 characters, possibly incorrectly encoded';
  29. default: return 'Unknown error';
  30. }
  31. }
  32. /**
  33. * @author Sebastiaan Stok <s.stok@rollerscapes.net>
  34. * @author Scott <scott@paragonie.com>
  35. */
  36. public static function hash_pbkdf2($algorithm, $password, $salt, $iterations, $length = 0, $rawOutput = false)
  37. {
  38. // Pre-hash for optimization if password length > hash length
  39. $hashLength = \strlen(hash($algorithm, '', true));
  40. switch ($algorithm) {
  41. case 'sha224':
  42. case 'sha256':
  43. $blockSize = 64;
  44. break;
  45. case 'sha384':
  46. case 'sha512':
  47. $blockSize = 128;
  48. break;
  49. default:
  50. $blockSize = $hashLength;
  51. break;
  52. }
  53. if ($length < 1) {
  54. $length = $hashLength;
  55. if (!$rawOutput) {
  56. $length <<= 1;
  57. }
  58. }
  59. // Number of blocks needed to create the derived key
  60. $blocks = ceil($length / $hashLength);
  61. $digest = '';
  62. if (\strlen($password) > $blockSize) {
  63. $password = hash($algorithm, $password, true);
  64. }
  65. for ($i = 1; $i <= $blocks; ++$i) {
  66. $ib = $block = hash_hmac($algorithm, $salt.pack('N', $i), $password, true);
  67. // Iterations
  68. for ($j = 1; $j < $iterations; ++$j) {
  69. $ib ^= ($block = hash_hmac($algorithm, $block, $password, true));
  70. }
  71. $digest .= $ib;
  72. }
  73. if (!$rawOutput) {
  74. $digest = bin2hex($digest);
  75. }
  76. return substr($digest, 0, $length);
  77. }
  78. }