PHP form password with MD5

Status
Not open for further replies.

murdocsvan

Web Programmer
Messages
896
Location
Surrey, UK
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.
 
PHP:
<?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:
<?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.
 
Okay your script is useful, but i would really like to understand it :p. 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.
 
PHP:
<?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.
 
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.
 
You do it the same way, and then just compare.

PHP:
   <?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);

?>
 
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.
 
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:
<?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:
<?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*
 
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);
 
Status
Not open for further replies.
Back
Top Bottom