PageRenderTime 38ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/swift/Swift/Authenticator/CRAMMD5.php

https://bitbucket.org/enurkov/prestashop
PHP | 73 lines | 35 code | 7 blank | 31 comment | 2 complexity | fe5ff3f695359b2bda22ebd792f370d1 MD5 | raw file
  1. <?php
  2. /**
  3. * Swift Mailer CRAM-MD5 Authenticator Mechanism
  4. * Please read the LICENSE file
  5. * @author Chris Corbyn <chris@w3style.co.uk>
  6. * @package Swift_Authenticator
  7. * @license GNU Lesser General Public License
  8. */
  9. require_once dirname(__FILE__) . "/../ClassLoader.php";
  10. Swift_ClassLoader::load("Swift_Authenticator");
  11. /**
  12. * Swift CRAM-MD5 Authenticator
  13. * This form of authentication is a secure challenge-response method
  14. * @package Swift_Authenticator
  15. * @author Chris Corbyn <chris@w3style.co.uk>
  16. */
  17. class Swift_Authenticator_CRAMMD5 implements Swift_Authenticator
  18. {
  19. /**
  20. * Try to authenticate using the username and password
  21. * Returns false on failure
  22. * @param string The username
  23. * @param string The password
  24. * @param Swift The instance of Swift this authenticator is used in
  25. * @return boolean
  26. */
  27. public function isAuthenticated($user, $pass, Swift $swift)
  28. {
  29. try {
  30. $encoded_challenge = substr($swift->command("AUTH CRAM-MD5", 334)->getString(), 4);
  31. $challenge = base64_decode($encoded_challenge);
  32. $response = base64_encode($user . " " . self::generateCRAMMD5Hash($pass, $challenge));
  33. $swift->command($response, 235);
  34. } catch (Swift_ConnectionException $e) {
  35. $swift->reset();
  36. return false;
  37. }
  38. return true;
  39. }
  40. /**
  41. * Return the name of the AUTH extension this is for
  42. * @return string
  43. */
  44. public function getAuthExtensionName()
  45. {
  46. return "CRAM-MD5";
  47. }
  48. /**
  49. * Generate a CRAM-MD5 hash from a challenge
  50. * @param string The string to get a hash from
  51. * @param string The challenge to use to make the hash
  52. * @return string
  53. */
  54. public static function generateCRAMMD5Hash($password, $challenge)
  55. {
  56. if (strlen($password) > 64)
  57. $password = pack('H32', md5($password));
  58. if (strlen($password) < 64)
  59. $password = str_pad($password, 64, chr(0));
  60. $k_ipad = substr($password, 0, 64) ^ str_repeat(chr(0x36), 64);
  61. $k_opad = substr($password, 0, 64) ^ str_repeat(chr(0x5C), 64);
  62. $inner = pack('H32', md5($k_ipad.$challenge));
  63. $digest = md5($k_opad.$inner);
  64. return $digest;
  65. }
  66. }