TYPO3 API  SVNRelease
CramMd5Authenticator.php
Go to the documentation of this file.
00001 <?php
00002 
00003 /*
00004  * This file is part of SwiftMailer.
00005  * (c) 2004-2009 Chris Corbyn
00006  *
00007  * For the full copyright and license information, please view the LICENSE
00008  * file that was distributed with this source code.
00009  */
00010 
00011 //@require 'Swift/Transport/Esmtp/Authenticator.php';
00012 //@require 'Swift/Transport/SmtpAgent.php';
00013 //@require 'Swift/TransportException.php';
00014 
00015 /**
00016  * Handles CRAM-MD5 authentication.
00017  * @package Swift
00018  * @subpackage Transport
00019  * @author Chris Corbyn
00020  */
00021 class Swift_Transport_Esmtp_Auth_CramMd5Authenticator
00022   implements Swift_Transport_Esmtp_Authenticator
00023 {
00024 
00025   /**
00026    * Get the name of the AUTH mechanism this Authenticator handles.
00027    * @return string
00028    */
00029   public function getAuthKeyword()
00030   {
00031     return 'CRAM-MD5';
00032   }
00033 
00034   /**
00035    * Try to authenticate the user with $username and $password.
00036    * @param Swift_Transport_SmtpAgent $agent
00037    * @param string $username
00038    * @param string $password
00039    * @return boolean
00040    */
00041   public function authenticate(Swift_Transport_SmtpAgent $agent,
00042     $username, $password)
00043   {
00044     try
00045     {
00046       $challenge = $agent->executeCommand("AUTH CRAM-MD5\r\n", array(334));
00047       $challenge = base64_decode(substr($challenge, 4));
00048       $message = base64_encode(
00049         $username . ' ' . $this->_getResponse($password, $challenge)
00050         );
00051       $agent->executeCommand(sprintf("%s\r\n", $message), array(235));
00052       return true;
00053     }
00054     catch (Swift_TransportException $e)
00055     {
00056       $agent->executeCommand("RSET\r\n", array(250));
00057       return false;
00058     }
00059   }
00060 
00061   /**
00062    * Generate a CRAM-MD5 response from a server challenge.
00063    * @param string $secret
00064    * @param string $challenge
00065    * @return string
00066    */
00067   private function _getResponse($secret, $challenge)
00068   {
00069     if (strlen($secret) > 64)
00070     {
00071       $secret = pack('H32', md5($secret));
00072     }
00073 
00074     if (strlen($secret) < 64)
00075     {
00076       $secret = str_pad($secret, 64, chr(0));
00077     }
00078 
00079     $k_ipad = substr($secret, 0, 64) ^ str_repeat(chr(0x36), 64);
00080     $k_opad = substr($secret, 0, 64) ^ str_repeat(chr(0x5C), 64);
00081 
00082     $inner  = pack('H32', md5($k_ipad . $challenge));
00083     $digest = md5($k_opad . $inner);
00084 
00085     return $digest;
00086   }
00087 
00088 }