Using the PHP Crypt Function

The PHP crypt function is a one-way encryption function that lets you confirm that an entered password matches a stored encrypted one — without having to decrypt anything. Chris Root explains how it works.

Protecting user names and passwords, not to mention financial or other personal information, can be a difficult job for any webmaster. Unfortunately there are an awful lot of people out there with nothing better to do than break into your system and steal information, or just wreak havok. One of the tools of the trade for information protection is encryption. There is a built-in function of the PHP language called crypt() which is easy to use and can help you secure information you want to protect.

Crypt is a one-way encryption function. You may wonder then, “What good is it if I can’t decrypt what I have encrypted?” The answer is simple. In PHP, crypt can be used to confirm that, for example, an entered password matches a stored encrypted one.

Here is how it works: crypt accepts two arguments and returns an encrypted string. The first argument is the string you wish to encrypt. Use the trim function to ensure that whitespace on either side of the string is stripped away, just to make everything cleaner. The second argument is the encryption “salt,” which is a string that is used on which to base the encryption. This is an optional parameter that, if not supplied, will be randomly generated by the function. Here is an example:

$crypted_pass = crypt($password);

The variable Crypted_pass can now be stored in a database or flat file. If you use the encrypted password for the salt argument and use it to encrypt the correct password, entered from a login form for instance, the two encrypted versions will match as below.

//$pass_entered_from_login is the user entered password
//$crypted_pass is the encrypted password from the
//database or file
if(crypt($pass_entered_from_login,$crypted_pass)) == $crypted_pass)
   echo(“Welcome to my web site.”)

You are encrypting it in the same way that you did when it was entered and stored in the database. The difference is that this time you are using the stored encrypted version as the salt. If the correct password was entered then the two encrypted versions will match; the user is welcomed and can proceed.

This allows you to confirm the password without decrypting it, since all you really need to know is if it matches the user’s input. You can use this for any information that is short (8 charaters on some systems) and needs to be confirmed but not decrypted. User information like passwords are the most common target for this function.

Crypt uses standard MD5 encryption but can also use DES or other encryption as available. Information on the types of encryption that is available on your system can be viewed through constants set in PHP. Check for which encryption is supported by using the following code.

echo(“DES is ” . CRYPT_STD_DES.”<br>Extended DES is “.
“<br>BlowFish is “.CRYPT_BLOWFISH”);

The result will look something like this:

DES is 1
Extended DES is 1
MD5 is 1
BlowFish is 0

If any of these is “0″ then it is not supported. Each of these algorithms use a different salt. MD5 uses 12 characters, DES uses 2. Also beware that some operating systems truncate a string that is larger than 8 characters before encrypting it. You should test this in your comparison script on the system that you intend to use it just in case. You can also check CRYPT_SALT_LENGTH to determine the default salt length. It may be 2 or 12 depending on the encryption that is used.

It is not recommended that you use an automatically generated salt if you will be calling crypt repeatedly, such as in a loop. The same salt will be used, which will compromise security.

{mospagebreak title=A Practical Example}

First let’s set up a form for entering a username and password to add a new user into the system. Let’s use an example of a form for an admin interface to administer a Company X product database for Web display.

<title>Company X Products Admin Application Add New User </title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
<h1>Administration Interface login: Add new User</h1>
<form name=”form1″ method=”post” action=”admin_login_newuserbe.php”>
<input name=”uname” type=”text” id=”uname” size=”8″ maxlength=”8″>
   <strong>Enter User Name</strong>
<input name=”pword” type=”password” id=”pword” size=”8″ maxlength=”8″>
   <strong>Enter Password</strong>
   <br><input type=”submit” name=”Submit” value=”Add”>

When the form is submitted to “admin_login_newuserbe.php” the crypt function is used to encrypt the new username. We first confirm that both fields have entries:

if(empty($_POST[pword]) || empty($_POST[uname]))
   echo “<html><head></head>
   <body><h1>You must enter both a username and password.
   <a href = “admin_login_newuser.html”>Try Again?

Additional validation could be added to this either on the client side (using Javascript) or on the server side as needed. Next we will use crypt to encrypt our password and neatly trim leading and trailing white space from our username. They can then be stored in a database or flat file.

   $pwrd = crypt(trim(“$_POST[pword]“));
   $user = trim(“$_POST[uname]“);
//Code for accessing you database or flat file goes here.

{mospagebreak title=Login}

Login would use a similar form, but now we are comparing a stored encrypted password with one entered by the user. The usual validating code can be used on the form input. Once this is done we make our database or file connections and retrieve the needed information. We then make our comparisons, and when we receive a successful match, start a new session for our logged in user and redirect them to the admin interface page. If there is no match we simply prompt the user to try again.

You could also set up a way to track the number of times a user attempted to log in within a certain period of time if you wished. Options to reset passwords and have passwords emailed to the user are also good add-ons. Of course keep in mind that wherever you store an unencrypted password, it had better be secure. If the information you are protecting is something like credit card information, it’s even more important.

//the array $row is from the database that holds our information.
if(crypt($pwrd,$row[pword]) == $row[pword])
session_start();//start the new session
$sesid = session_id();//get the session id
$_SESSION[logged] = TRUE;//set a session id to check if this user is logged in
header(“location: chooser.php?id=$sesid”);//redirect the user to the admin interface page
else//whoops no match but be nice and let them try again.
echo “<html><head></head>
<body><h1>Sorry No Passord matches.
</h1><a href = “admin_login.html”>Try Again?</a></body></html>”;

{mospagebreak title=A Few Words About Storage and Security}

If you use a flat file for your password storage, make sure to put it outside your Web root. Proper permissions can be set on this file to allow your scripts to access it. As a default on UNIX systems PHP and the Web server run under the user “nobody.” Using a flat file is fine for a small number of passwords, but if you have a lot of them a database is a better choice. You could also split your password storage: website usernames and passwords in a database and database access passwords in a flat file.

You also have the option of using the htaccess and htpasswd file if you are using the Apache Web server. Make sure to consult any documentation for your server for more information. Another good general net security resource is available at Always keep up with the latest security updates and bulletins for any software you use on your site and apply the available patches promptly.

There are other encryption functions or add ons for PHP as well. Such as md5() or a two way PHP extension called Mcrypt. A good source for information about these or other PHP functions and features is in the PHP manual. You can access the PHP manual on line at or through the PHP Freaks web site


Using crypt we have made password validation secure and easy. There was no need to ever expose the real password and the logged in user is now on their way to doing some work. Always consider all security measures available when you have important information to protect.

Google+ Comments

Google+ Comments