HS256Encrypter.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of qbhy/simple-jwt.
  5. *
  6. * @link https://github.com/qbhy/simple-jwt
  7. * @document https://github.com/qbhy/simple-jwt/blob/master/README.md
  8. * @contact qbhy0715@qq.com
  9. * @license https://github.com/qbhy/simple-jwt/blob/master/LICENSE
  10. */
  11. namespace Qbhy\SimpleJwt\EncryptAdapters;
  12. use Qbhy\SimpleJwt\AbstractEncrypter;
  13. class HS256Encrypter extends AbstractEncrypter
  14. {
  15. public function signature(string $signatureString): string
  16. {
  17. return \hash_hmac('SHA256', $signatureString, $this->getSecret(), true);
  18. }
  19. public function check(string $signatureString, string $signature): bool
  20. {
  21. $hash = \hash_hmac('SHA256', $signatureString, $this->getSecret(), true);
  22. if (\function_exists('hash_equals')) {
  23. return \hash_equals($signature, $hash);
  24. }
  25. $len = \min(static::safeStrlen($signature), static::safeStrlen($hash));
  26. $status = 0;
  27. for ($i = 0; $i < $len; ++$i) {
  28. $status |= (\ord($signature[$i]) ^ \ord($hash[$i]));
  29. }
  30. $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
  31. return $status === 0;
  32. }
  33. public static function alg(): string
  34. {
  35. return 'HS256';
  36. }
  37. }