Computer Forums

Member Login

Remember Me? Sign Up! | Forgot Password
 
Slogan
 
Computer Forums > Programmers Lounge > Programming Discussions » PHP form password with MD5
Closed Thread
Old 03-12-2009, 10:37 AM   #1 (permalink)
murdocsvan's Avatar
 
Ultra Techie

Join Date: Jun 2007

Location: Surrey, UK

Posts: 849

murdocsvan is on a distinguished road

Default PHP form password with MD5

I'm making a basic form which i can use to input passwords into a MySQL database. Before it's entered into the database however, i need it turned into an MD5 key, so that the MD5 is put onto the database, not the actual password.

I'm sure it's a simple of comma is the wrong place or something, but can someone help me out please?

Code:
<?php

$con = mysql_connect("localhost","user","password1234");

if(!$con)
	{
	die('Could not connect: ' . mysql_error());
	}

$password = md5($_POST["password"]);
	
mysql_select_db("database", $con);

$sql = "INSERT INTO members (id,username, password)
VALUES ('$_POST["username"]',$password)";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);

?>
EDIT: It returns a parse error on line 15.
__________________


Last edited by murdocsvan; 03-12-2009 at 10:39 AM.
murdocsvan is offline  
Old 03-12-2009, 04:20 PM   #2 (permalink)
CrazeD's Avatar
 
Wizard Techie

Join Date: Feb 2006

Location: Maine

Posts: 3,683

CrazeD will become famous soon enough

Send a message via AIM to CrazeD Send a message via MSN to CrazeD
Default Re: PHP form password with MD5

PHP Code:
<?php

$con 
mysql_connect("localhost","user","password1234");

if(!
$con)
    {
    die(
'Could not connect: ' mysql_error());
    }

$password md5($_POST["password"]);
    
mysql_select_db("database"$con);

$sql "INSERT INTO members (id,username, password)
VALUES ('"
.$_POST["username"]."','".$password."')";

if (!
mysql_query($sql,$con))
  {
  die(
'Error: ' mysql_error());
  }
echo 
"1 record added";

mysql_close($con);

?>
This should work. However, this is very insecure as you didn't even protect against SQL injection. Also, MD5 is old and has been cracked, it's no longer a good choice for encryption. At the very least, encrypt with the SHA1 function. If you really want security, use a salt too. A salt is a randomly generated string that is encrypted into the password. So, even if a hacker got the password hash, they would have to figure out your salt and your algorithm. And even that wouldn't help them, because it'd be nearly impossible to crack.

So, what you need to do is add a salt column to your MySQL table, and then use this script that I have revised for you:

PHP Code:
<?php

function createSalt($length='')
{
    
$salt substr(sha1(md5(uniqid(rand(), true))), 0$length);

    return 
$salt;
}

function 
getPassHash($password='',$salt='')
{
    
$passhash sha1 (md5(sha1($password) . md5($salt)));

    return 
$passhash;
}


$con mysql_connect("localhost","user","password1234");

if(!
$con)
    {
    die(
'Could not connect: ' mysql_error());
    }

$username mysql_escape_string ($_POST['username']);
$password mysql_escape_string ($_POST['password']);

$salt createSalt();
$passhash getPassHash($password,$salt);
    
mysql_select_db("database"$con);

$sql "INSERT INTO members (id,username, password, password_salt)
VALUES ('"
.$username."','".$passhash."', '".$salt."')";

if (!
mysql_query($sql,$con))
  {
  die(
'Error: ' mysql_error());
  }
echo 
"1 record added";

mysql_close($con);

?>
This script will protect against SQL injection, as well as make a very secure password with a salt. When you want to authenticate a login, just repeat the algorithm like I did and match the passhash.

Hope that helps.
__________________

Need website help? PM me!
CrazeD is offline  
Old 03-13-2009, 12:34 PM   #3 (permalink)
murdocsvan's Avatar
 
Ultra Techie

Join Date: Jun 2007

Location: Surrey, UK

Posts: 849

murdocsvan is on a distinguished road

Default Re: PHP form password with MD5

Thanks, CrazeD!
__________________

murdocsvan is offline  
Old 03-17-2009, 10:37 AM   #4 (permalink)
murdocsvan's Avatar
 
Ultra Techie

Join Date: Jun 2007

Location: Surrey, UK

Posts: 849

murdocsvan is on a distinguished road

Default Re: PHP form password with MD5

Okay your script is useful, but i would really like to understand it . I've looked on the internet for some tutorials, but nothing really explains it. It would be simple to just copy & paste it in, but this is part of a school project, and i'd need to explain in good detail how i did it.

I'd really appreciate it if you broke it down and commented the code so i could understand fully.
Thanks.
__________________

murdocsvan is offline  
Old 03-17-2009, 03:57 PM   #5 (permalink)
CrazeD's Avatar
 
Wizard Techie

Join Date: Feb 2006

Location: Maine

Posts: 3,683

CrazeD will become famous soon enough

Send a message via AIM to CrazeD Send a message via MSN to CrazeD
Default Re: PHP form password with MD5

PHP Code:
<?php

/*
make the createSalt function which will make a randomly generated string for the password salt

a password salt is a short randomly generated string that will make a password harder to crack, increasing security
*/

function createSalt($length='')
{
    
// make the randomly generated string, with a few standard functions
    
$salt substr(sha1(md5(uniqid(rand(), true))), 0$length);

    return 
$salt;
}

/*
make the getPassHash function which will use a custom algorithm to encrypt the password and salt
*/

function getPassHash($password='',$salt='')
{
    
// make the hash string using sha1 and md5, and add the salt in
    
$passhash sha1 (md5(sha1($password) . md5($salt)));

    return 
$passhash;
}

$con mysql_connect("localhost","user","password1234");

if(!
$con)
    {
    die(
'Could not connect: ' mysql_error());
    }

// get POST data and use mysql_escape_string to escape illegal characters
// this is to prevent SQL injection, which is a huge but easy-to-fix security risk
$username mysql_escape_string ($_POST['username']);
$password mysql_escape_string ($_POST['password']);

// make our salt with the createSalt() function
$salt createSalt();

// encrypt the password with the getPassHash() function
$passhash getPassHash($password,$salt);
    
mysql_select_db("database"$con);

// insert the data into the database
$sql "INSERT INTO members (id,username, password, password_salt)
VALUES ('"
.$username."','".$passhash."', '".$salt."')";

if (!
mysql_query($sql,$con))
  {
  die(
'Error: ' mysql_error());
  }
echo 
"1 record added";

mysql_close($con);

?>
Does this help?

I'm not really good at commenting, I never do it.
__________________

Need website help? PM me!
CrazeD is offline  
Old 03-18-2009, 07:30 AM   #6 (permalink)
murdocsvan's Avatar
 
Ultra Techie

Join Date: Jun 2007

Location: Surrey, UK

Posts: 849

murdocsvan is on a distinguished road

Default Re: PHP form password with MD5

Okay, thanks for that. That explains it a lot more. Could you explain though how i can get the password back, such as with a login script? Thanks again.
__________________

murdocsvan is offline  
Old 03-18-2009, 05:22 PM   #7 (permalink)
CrazeD's Avatar
 
Wizard Techie

Join Date: Feb 2006

Location: Maine

Posts: 3,683

CrazeD will become famous soon enough

Send a message via AIM to CrazeD Send a message via MSN to CrazeD
Default Re: PHP form password with MD5

You do it the same way, and then just compare.

PHP Code:
   <?php

/*
make the createSalt function which will make a randomly generated string for the password salt

a password salt is a short randomly generated string that will make a password harder to crack, increasing security
*/

function createSalt($length='')
{
    
// make the randomly generated string, with a few standard functions
    
$salt substr(sha1(md5(uniqid(rand(), true))), 0$length);

    return 
$salt;
}

/*
make the getPassHash function which will use a custom algorithm to encrypt the password and salt
*/

function getPassHash($password='',$salt='')
{
    
// make the hash string using sha1 and md5, and add the salt in
    
$passhash sha1 (md5(sha1($password) . md5($salt)));

    return 
$passhash;
}

$con mysql_connect("localhost","user","password1234");

if(!
$con)
    {
    die(
'Could not connect: ' mysql_error());
    }

// get POST data and use mysql_escape_string to escape illegal characters
// this is to prevent SQL injection, which is a huge but easy-to-fix security risk
$username mysql_escape_string ($_POST['username']);
$password mysql_escape_string ($_POST['password']);

// check if username or password is empty
if (!empty ($username) && !empty ($password)) {        
    
mysql_select_db("database"$con);

    
// do a query to find the member with the username from the form
    
$sql mysql_query ("SELECT * FROM members WHERE username='".$username."' LIMIT 1");

    
// check if rows were found (indicating the user exists)
    
if (mysql_num_rows ($sql) > 0) {
        
// assign $row to the database rows
        
$row mysql_fetch_array ($sql);

        
// get the salt from the database
        
$salt $row['password_salt'];

        
// make the password hash with the form password and the salt returned from the database
        
$passhash getPassHash($password,$salt);

        if (
$passhash == $row['password']) {
            
// member is logged in
            // set some sessions, or whatever else you want to do
            
echo 'You are now logged in!';
        } else {
            
// invalid password
            
echo 'Your password is incorrect!';
        }
    } else {
        
// username wasnt found
        
echo 'This user is not in the database!';
    }
} else {
    
// username or password not entered
    
echo 'You must enter a username and a password!';
}

mysql_close($con);

?>

__________________

Need website help? PM me!
CrazeD is offline  
Old 03-25-2009, 08:51 AM   #8 (permalink)
murdocsvan's Avatar
 
Ultra Techie

Join Date: Jun 2007

Location: Surrey, UK

Posts: 849

murdocsvan is on a distinguished road

Default Re: PHP form password with MD5

Thanks for the code, been really helpful.

However, once the password has been stored in the database, the idea is that people who have access to the database wont be able to read it. It will only be me, but still...

Wouldn't it be easier just to use the sha1 function on its own? And then to store the key as the password in the table. The whole salt thing is quite complicated, and i'm still only getting to grips with the basics.
__________________

murdocsvan is offline  
Old 03-25-2009, 10:18 AM   #9 (permalink)
murdocsvan's Avatar
 
Ultra Techie

Join Date: Jun 2007

Location: Surrey, UK

Posts: 849

murdocsvan is on a distinguished road

Default Re: PHP form password with MD5

EPIC WIN!!!

I got it to work!! =D=D=D

I used some of the code you gave me, and some stuff i found laying around the internet. I chose to use just sha1 instead of the salt method.

This is the login form:

Code:
<html>
<body>
<head>
<meta name="robots" content="noindex, nofollow" />
<meta name="robots" content="noarchive" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin Login</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>

<table class="login">
	<tr>
		<td class="login">
			<form name="login" action="checklogin.php" method="post">
				Username: <input type="text" name="username" /><br />
				Password: <input type="password" name="password" /><br />
				<input type="submit" value="Submit" />
				<input type="reset" value="Reset" />
			</form>
		</td>
	</tr>
</table>


</body>
</html>
This is the login check page:

PHP Code:
<?php

$host
="localhost"// Host name 
$sql_username="*****"// Mysql username 
$sql_password="*****"// Mysql password 
$db_name="*****"// Database name 
$tbl_name="******"// Table name 

//mysql Connect variable
$con mysql_connect("$host","$sql_username","$sql_password");

//if the mysql connect variable can't connect, die
if(!$con)
    {
    die(
'Could not connect: ' mysql_error());
    }

//Database select
mysql_select_db($db_name$con);

//Fetch username and password from previous form
$username=$_POST['username']; 
$password=$_POST['password']; 

//Protect against mysql Inject
$username stripslashes($username);
$password stripslashes($massword);
$username mysql_escape_string ($_POST['username']);
$password mysql_escape_string ($_POST['password']);

$password=sha1($password);

//Check that fields aren't left blank
if (!empty ($username) && !empty ($password))
    {        
    
mysql_select_db("vmrgjdq_primary"$con);
    
    
//select the data from the table and set it to a variable
    
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
    
$result=mysql_query($sql,$con);
    
    
//count number of rows in table
    
$count=mysql_num_rows($result);

    if(
$count==1)
        {
        
// Register $myusername, $mypassword and redirect to file "login_success.php"
        
session_register("username");
        
session_register("password"); 
        
header("location:login_success.php");
        }
    else 
        {
        echo 
"Error: Wrong Username or Password";
        }
    }
else
    echo 
"Error: No username or password";
    
?>
and last but not least, the login_succesful page:

PHP Code:
<?php

session_start
();

if(!
session_is_registered(username))
    {
    
header("location:main_login.php");
    }
    
?>
    
<html>
<head>
<title>Login Successful!/title>
<meta http-equiv="REFRESH" content="0;url=http://www.the-domain-you-want-to-redirect-to.com">
</head>

<body>
Login Successful!
<br /><br />
Redirecting to Admin page...
</body>
</html>
*weeps tear of joy*
__________________


Last edited by murdocsvan; 03-25-2009 at 11:28 AM.
murdocsvan is offline  
Old 03-25-2009, 08:32 PM   #10 (permalink)
CrazeD's Avatar
 
Wizard Techie

Join Date: Feb 2006

Location: Maine

Posts: 3,683

CrazeD will become famous soon enough

Send a message via AIM to CrazeD Send a message via MSN to CrazeD
Default Re: PHP form password with MD5

Nice, but I see an error.

Code:
//Protect against mysql Inject
$username = stripslashes($username);
$password = stripslashes($massword);
$username = mysql_escape_string ($_POST['username']);
$password = mysql_escape_string ($_POST['password']);
You use the stripslashes function on $username and on $password (by the way, you misspelled $password for the second stripslashes function) but then you bypass this by using mysql_escape_string on the $_POST data. Your code should read like this:

Code:
//Protect against mysql Inject
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_escape_string ($username);
$password = mysql_escape_string ($password);

__________________

Need website help? PM me!
CrazeD is offline  
 
Closed Thread

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
PHP form murdocsvan Programming Discussions 7 03-11-2009 11:00 PM
DBD::mysql Perl module install CrazeD Linux, BSD, other *nixes & Open Source Software 4 02-28-2009 05:37 PM
PHP - what it does and what it doesn’t Osiris Programming Discussions 1 02-16-2009 04:09 PM
Looking for php form input and display script linux1880 Programming Discussions 3 06-03-2008 10:23 PM
Need PHP and JavaScript Form Validation Scripts aetherh4cker Programming Discussions 2 01-06-2008 04:16 PM