PageRenderTime 15ms CodeModel.GetById 11ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/app/protected/extensions/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php

https://bitbucket.org/ddonthula/zurmouser
PHP | 85 lines | 44 code | 11 blank | 30 comment | 2 complexity | 3a6949b3a8bd5a944bbbe4f66d8fe62f MD5 | raw file
 1<?php
 2
 3/*
 4 * This file is part of SwiftMailer.
 5 * (c) 2004-2009 Chris Corbyn
 6 *
 7 * For the full copyright and license information, please view the LICENSE
 8 * file that was distributed with this source code.
 9 */
10
11
12/**
13 * Handles CRAM-MD5 authentication.
14 * @package Swift
15 * @subpackage Transport
16 * @author Chris Corbyn
17 */
18class Swift_Transport_Esmtp_Auth_CramMd5Authenticator
19  implements Swift_Transport_Esmtp_Authenticator
20{
21  
22  /**
23   * Get the name of the AUTH mechanism this Authenticator handles.
24   * @return string
25   */
26  public function getAuthKeyword()
27  {
28    return 'CRAM-MD5';
29  }
30  
31  /**
32   * Try to authenticate the user with $username and $password.
33   * @param Swift_Transport_SmtpAgent $agent
34   * @param string $username
35   * @param string $password
36   * @return boolean
37   */
38  public function authenticate(Swift_Transport_SmtpAgent $agent,
39    $username, $password)
40  {
41    try
42    {
43      $challenge = $agent->executeCommand("AUTH CRAM-MD5\r\n", array(334));
44      $challenge = base64_decode(substr($challenge, 4));
45      $message = base64_encode(
46        $username . ' ' . $this->_getResponse($password, $challenge)
47        );
48      $agent->executeCommand(sprintf("%s\r\n", $message), array(235));
49      return true;
50    }
51    catch (Swift_TransportException $e)
52    {
53      $agent->executeCommand("RSET\r\n", array(250));
54      return false;
55    }
56  }
57  
58  /**
59   * Generate a CRAM-MD5 response from a server challenge.
60   * @param string $secret
61   * @param string $challenge
62   * @return string
63   */
64  private function _getResponse($secret, $challenge)
65  {
66    if (strlen($secret) > 64)
67    {
68      $secret = pack('H32', md5($secret));
69    }
70    
71    if (strlen($secret) < 64)
72    {
73      $secret = str_pad($secret, 64, chr(0));
74    }
75    
76    $k_ipad = substr($secret, 0, 64) ^ str_repeat(chr(0x36), 64);
77    $k_opad = substr($secret, 0, 64) ^ str_repeat(chr(0x5C), 64);
78
79    $inner  = pack('H32', md5($k_ipad . $challenge));
80    $digest = md5($k_opad . $inner);
81
82    return $digest;
83  }
84  
85}