Encrypting Password & Other Sensitive Information

Published: January 13th, 2009 by:

Encrypting sensitive data is extremely important. You, as the webmaster or database administrator, needs to make sure that the data is safe, even if it falls in the wrong hands. In this article, I will show you how to use MD5 and SHA1 encryption in PHP.


Salting your Passwords

Examples in this article will be with salted passwords. Salting the password lessons the risk of dictionary attacks. For example, if I were to use a password of ‘password’. That hash is common and very susceptible to a dictionary attack. However, if the application salted all passwords with a random string like ‘as87f56safg8’, then the resulting stored password would be the encrypted version of ‘as87f56safg8password’, which is not susceptible to a dictionary attack, regardless of how weak of a password provided by the end-user.

MD5 Encryption

Using PHP’s md5() function allows you to easily create a password hash.

Here is the recommended way to encrypt a password:

<?php
	$salt = "7dA+U^@'aF7FLvJ";
	$password = 'secret';
	
	$hash = md5($salt . $password);
	echo $hash;
	
	/* returns: ade1373f24d328d9229d57f284871cd0 */
?>

Since this is a one-way hash, you can’t decode it to compare to verify with a user-supplied password. Instead, take the user-supplied password, encrypt it with the same md5() function & salt, and compare it to the hash stored in your database. If the hashes match, then the supplied password is correct.

SHA1 Encryption

This is very similar to md5(), except using another algorithm.

<?php
	$salt = "7dA+U^@'aF7FLvJ";
	$password = 'secret';
	
	$hash = sha1($salt . $password);
	echo $hash;
	
	/* returns: be58ee5f202d6a9bfcd13ad4ac3552b1367e30db */
?>

There is an alternative PHP function, crypt(), but I find these other two functions easier to use.


Leave a Reply





Wordpress doesn't like it when you post PHP code. Go save your code at pastebin, and post the link here.

About the Author

Andrew has been coding PHP applications since 2006, and has plenty of experience with PHP, MySQL, and Apache. He prefers Ubuntu Linux on his desktop and has plenty of experience at managing CentOS web servers. He is the owner of Wells IT Solutions LLC, and develops PHP applications full time for anyone that needs it as well as does desktop computer support locally in the local area. He spends most of his free time exploring new programming concepts and posting on The Webmaster Forums.