You don’t have to be hiding NSA secret documents to feel like you should secure your website from unwanted intruders. PHP built-in encryption/encoding functions let you achieve a very decent level of security to protect your data. The purpose of this post is to explain what kind of data you should secure and how to do so (in a beginner’s programming level).

What kind of data do I need to Secure?

Fortunately you don’t have to encrypt every single data you exchange with your server. The most common secure transmission involves passwords. When a user registers or logs into your site you want to work with data he submitted in an encoded form so that no one (even you!) can read the raw values.

The best way to deal with passwords is:
  • The user inputs a password.
  • You receive it and encrypt it (with any of the below PHP functions).
  • Store it in an encrypted form in your database (probably MySQL).
  • When the user wants to login, compare the encrypted form of the submitted password with the encrypted form in the database.
  • If they match, then the password is correct. Otherwise, it is incorrect.

This way even if someone hacks into your database he will only see encrypted versions of the passwords (and any other information you have in encoded form).

MD5

MD5 (Message-Digest Algorithm 5) is an encoding algorithm producing a 128-bit output (usually expressed in a 32-bit hexadecimal number) of any input string.

To calculate the MD5 hash equivalent of a string variable you can use the PHP function md5().

php code
<?
// password from the database (equivalent to “hello world”)
$password = “5eb63bbbe01eeed093cb22bb8f5acdc3”;

// encrypt inputted password (from a form here)
$user_input = md5($_POST[“password”]);

// check if correct (match?)
if ($user_input == $password) {
echo “Correct password!”;
}
else {
echo “Incorrect password!”;
}
?>

CRYPT

The PHP crypt function returns an encoded form of a string using different encryption algorithms: DES, Blowfish, MD5, SHA-256, SHA-512. It also uses a salt which is an optional parameter to make the encoding more secure. If the salt is not specified, PHP will generate a random one.

php code
<?
// crypt using STANDARD DES
// password from the database (equivalent to “hello world”)
$password = “$1$r35.Y52.$iyiFuvM.zFGsscpU0aZ4e.”;

// encrypt inputted password (from a form here)
// you should use $password as the salt to make sure
// it is using the same encryption algorithm
$user_input = crypt($_POST[“password”], $password);

// check if correct (match?)
if ($user_input == $password) {
echo “Correct password!”;
}
else {
echo “Incorrect password!”;
}
?>

With these two PHP encryption functions you should be able to securely manage passwords and other confidential data as explained above.