Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update my security in my login script from MD5 to something more secure? [duplicate]

I have a PHP login script with salt on the database, but in my register script I see:

$qry = "INSERT INTO accounts(username, firstname, lastname, password) " . 
VALUES('$username','$fname','$lname','" . md5($_POST['password']) . "')";

and for the login:

$qry="SELECT * FROM accounts WHERE username='$username' AND password='" .
md5($_POST['password']) . "'";

Is there some code that can replace the MD5? Something more secure?

I've heard of SHA1 or something.

like image 708
DxVerm aka Xeno Avatar asked Oct 05 '22 05:10

DxVerm aka Xeno


2 Answers

Short answer

Use bcrypt not md5 or sha1

Longer answer

Using the crypt() is hard. There is a new PHP password hashing API coming in PHP version 5.5, you can read about it here:

https://gist.github.com/nikic/3707231

It uses bcrypt and makes the whole process very easy. Of course php 5.5 isn't ready yet, so in the meantime there is a library to provide this new API right now:

https://github.com/ircmaxell/password_compat

Edit: See this thread for a much more thorough answer on the topic:

How do you use bcrypt for hashing passwords in PHP?

like image 157
jszobody Avatar answered Oct 13 '22 10:10

jszobody


In consideration of @jszbody post, you should also update your password field to tell you want scheme you're using.

Where you have an MD5 hash now, you might have just "BAC232BC1334DE" or something.

When you go to SHA or whatever, you should change it to: "SHA:YOURSHAHASHHERE".

Because you can't change any of your existing passwords right now. This will make it more backward compatible, since now you can support both schemes.

Since you get the original password during login, you can dynamically upgrade your passwords in place as people login.

You get your user record, check the password. If there is no scheme, use MD5, and compare passwords. If they're correct (i.e. they can log in), you can update their old MD5 password to the new SHA password.

Also, it seems you are not salting your passwords. You must salt your passwords so that when Mary Sue uses "ilovekittens" for her password, and Big Jake Mahoney uses "ilovekittens" as his password, you don't get the same has for identical passwords.

You can store the salt in the password as well: "SHA:RANDOMSALTCHARACTERS:YOURSALTEDHASHHERE".

Salting is highly recommended. Unsalted, it pretty much doesn't matter a whole lot what scheme you use.

like image 33
Will Hartung Avatar answered Oct 13 '22 12:10

Will Hartung