Search code examples
phpcrypt

PHP crypt problems


A quick and dirty experiment.

I put this code into a .php file and loaded it from my web host.

The result was "It works!" but.. why? Should it have failed? I was following Example #1 from here: http://php.net/manual/en/function.crypt.php

<?php
$pass1 = "thetimeshallwhintercows";
$salt = "temperpedic";

$crypt_pass = crypt($pass1, $salt);

if($crypt_pass == crypt("thetimeshallwhintercowz", $crypt_pass))
{
    print("It works!<br/>");
    print( $crypt_pass  );
    print("<br/>");
    print(crypt("thetimeshallwhintercowz", $crypt_pass));
}
else
{
    print("try again....");
}

?>

Solution

  • You should have a look at this answer to a similar question. the crypt() function requires that you have a correctly formatted salt. While temperpedic is a valid salt (sort of) it's not really a correctly formatted salt.

    If you have a look at the PHP documentation for the crypt() function there are a few examples of using crypt() with different hash types. Have a look at these examples.

    Remember, with crypt for modern web applications, you should be using at least SHA-256.

    <?php
    $pass1 = "thetimeshallwhintercows";
    $salt = "temperpedic";
    
    echo 'SHA-256:      ' . crypt($pass1, '$5$rounds=5000$' . $salt . '$') . "\n";
    echo 'SHA-256:      ' . crypt($pass1, '$5$rounds=5000$' . $salt . 'extra$') . "\n";
    echo 'SHA-256:      ' . crypt($pass1, '$5$rounds=5000$' . $salt . 'evenextra$') . "\n";
    
    ?>
    
    tim@roflcopter /tmp $ php lol.php
    SHA-256:      $5$rounds=5000$temperpedic$4g0qFd4Oqr/O.8aZMPiyrO9x5VUaQt14eXPOMr5asK2
    SHA-256:      $5$rounds=5000$temperpedicextra$3BF4dmqrCBuY2UtQpuhxXm4t4KGp1M9OoJPrskM490/
    SHA-256:      $5$rounds=5000$temperpedicevene$jBsGNFGSAbuL8hdcXsZjHRrH6u4qnXb1bAJ.TOR32A2