Skip to content
Advertisement

How can I generate a correct CRAM-MD5 response in PHP?

I wish to generate a CRAM-MD5 response for an SMTP server.

I can see the theoretical details of how to do so here: CRAM-MD5 Implementation, but I’m looking for the specific PHP code in order to implement it.

How can I implement this in PHP?

Advertisement

Answer

The following PHP code will produce a valid response for CRAM-MD5:

$username = "username goes here";
$password = "password goes here";

$challenge = "challenge from server goes here";

$challenge = base64_decode($challenge);
$digest = hash_hmac("md5", $challenge, $password, false);
var_dump(base64_encode($username . ' ' . $digest));

In a telnet session, you can use it like this:

telnet your.smtp.server.com 25
Trying 123.123.123.123...
Connected to your.smtp.server.com.
Escape character is '^]'.
220 your.smtp.server.com
EHLO your.server.com
...
250-AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5
...
AUTH CRAM-MD5
334 <challenge from server>
<output from var_dump goes here>
235 2.7.0 Authentication successful
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement