Encrypting passwords using PHP
Monday, July 7th, 2008 at 3:43pm, in User Handling, written by Stefan Ashwell
When creating a membership based site security is paramount - especially if you're dealing with personal information. When it comes to passwords you'll want to encrypt them wherever they are stored so they can't be stolen. Here are a few things you can do to make your passwords as safe as possible.
It doesn't matter where you're storing your passwords, typically it will be in a database table however it could be somewhere else. The theory about encrypting the passwords themselves remains the same. Let's imagine you have a registration form on your website that a user has filled out. One of the fields is a password field called 'passw'
Tip: As another level of security I like to call any password related fields in forms and my databases anything other that 'password' so its more difficult to guess them - its not much but it helps!
sha1 encryption
PHP's sha1 function creates a hash from the value you give to it. This is a one way encryption method that turns the entered password into a seemingly random series of characters. Let's use it to start encrypting our password:
$encrypted = sha1($_POST['passw']);
Now the '$encrypted' variable contains our hash based on the password that's been entered. We can now store this value in our database table.
Handling log-ins
Now you have encrypted passwords stored in your database you need a way of checking the passwords when a user logs into your site. To do this you simply need to perform the same encryption on a password entered into the log in form and compare the resulting hash to the one stored in the database for that user.
$encrypted = sha1($_POST['passw']);
if ( $database_row['pass'] == $encrypted ) {
$login_success = 1;
}
If they match perform any login actions you need to, as you would normally.
Forgotten passwords
It is common to include a forgotten password feature accompanying your login form. By encrypting your passwords in this way you are unable to remind users of their password - a sacrifice made in the name of a more secure website. All is not lost however, rather than reminding them of their password an alternative is to generate a new one for them, have a look at my random password generation article for ideas on how to do this.
I hope you've found this article interesting, if you have any comments or views on encrypting passwords or indeed website security, don't hesitate to post a comment.
Share and Enjoy:
Subscribe to Total PHP: RSS | Email
Related Posts:

















Comments on this article
By Ovidiu Curcan, Thursday, July 10th, 2008 at 4:31am
1. Hashing is not really encryption (encryption is the process of encoding a message so that only the intended recipient of the message can read it)
2. You should really salt the passwords. Otherwise they're vulnerable to rainbow table attacks.
Please log in to post a comment about this article.