CramMd5Authenticator.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\Component\Mailer\Transport\Smtp\Auth;
  11. use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
  12. /**
  13. * Handles CRAM-MD5 authentication.
  14. *
  15. * @author Chris Corbyn
  16. */
  17. class CramMd5Authenticator implements AuthenticatorInterface
  18. {
  19. public function getAuthKeyword(): string
  20. {
  21. return 'CRAM-MD5';
  22. }
  23. /**
  24. * {@inheritdoc}
  25. *
  26. * @see https://www.ietf.org/rfc/rfc4954.txt
  27. */
  28. public function authenticate(EsmtpTransport $client): void
  29. {
  30. $challenge = $client->executeCommand("AUTH CRAM-MD5\r\n", [334]);
  31. $challenge = base64_decode(substr($challenge, 4));
  32. $message = base64_encode($client->getUsername().' '.$this->getResponse($client->getPassword(), $challenge));
  33. $client->executeCommand(sprintf("%s\r\n", $message), [235]);
  34. }
  35. /**
  36. * Generates a CRAM-MD5 response from a server challenge.
  37. */
  38. private function getResponse(string $secret, string $challenge): string
  39. {
  40. if (\strlen($secret) > 64) {
  41. $secret = pack('H32', md5($secret));
  42. }
  43. if (\strlen($secret) < 64) {
  44. $secret = str_pad($secret, 64, \chr(0));
  45. }
  46. $kipad = substr($secret, 0, 64) ^ str_repeat(\chr(0x36), 64);
  47. $kopad = substr($secret, 0, 64) ^ str_repeat(\chr(0x5C), 64);
  48. $inner = pack('H32', md5($kipad.$challenge));
  49. $digest = md5($kopad.$inner);
  50. return $digest;
  51. }
  52. }