Jump to content

Recommended Posts

UPDATE users SET password = md5(password);

 

I was given that code, and told that it would encrypt existing passwords. I was wondering if that is true, it's an SQL statement so it would just update my table, right?

 

 

Now how about encrypting passwords in a login script/ registration script? I looked through that link to the tutorial, but there is so much info for me to decipher. Any help?  :)

I don't know about the SQL statement, but seems to be correct so long as they support that function. You can do the same thing with PHP prior to inserting it into the database. Just remember Hashing is different than encrypting. Hash is irreversible. Encryption can be reversed, so make sure you have the right one for your task.

Okay :)

 

Now how would I include that in a registration script so that passwords are automatically hashed or encrypted when they are stored to the database?

 

I can't add that into config.php (where the script connects to the database), can I? Won't that change all the passwords over?

That is hashing, not encrypting. I would avoid using the MySQL MD5 statement, as you are a bit more limited, with PHP you can salt the MD5 hash a bit better to make it more secure. Either way you go, do the same through out the whole script. If a user logins and you are verifying the login, use the MySQL MD5 or PHP MD5, do not mix and match as it will generate difference results.

 

SHA1 is a bit stronger, but yea. I would avoid using the MySQL MD5 function, just because I see it as being a bit more limited in how you control it.

 

Now how about encrypting passwords in a login script/ registration script? I looked through that link to the tutorial, but there is so much info for me to decipher. Any help?  :)

 

Please be a bit more descriptive of what you want to know. When a user signs up you hash the password and store that in a database, when a user logins you hash the password they gave you for the user and check it against your database to verify they match. Pretty simple process.

Okay, so I should look into using sha1()? I saw it, but wasn't sure...MD5 looked simpler.

 

This is want I need to know:

 

a) How to hash existing passwords in my database (is the SQL statement above correct ^^^? )

 

b) What kind of code I need to insert into my login/registration scripts to hash a password. So, if someone registers, what do I need to do to have the password they enter hashed? Same with login so that they will match.

 

 

Thanks :D

Okay, I need to know if it's supposed to look something like this...

 

REGISTRATION SCRIPT

<?php 
ini_set ("display_errors", "1");
error_reporting(E_ALL);
include("config.php"); 

// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());

// check if the username is taken
$check = "select id from $table where username = '".$_POST['username']."';"; 
$qry = mysql_query($check) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 
if ($num_rows != 0) { 
echo "Sorry, there the username {$_POST['username']}  is already taken.<br/>";
echo "<a href=user_login.php>Try again</a>";
exit;
}
if($_POST['password'] != $_POST['confirmnewpassword']){ 
   echo ("The two passwords must match. <br/>"); 
echo ("<a href=user_login.php>Try Again</a>");
}
else {

// insert the data
$insert = mysql_query("insert into $table values ('NULL', '".$_POST['username']."', '".$_POST['password']."', '".$_POST['email']."')")
or die("Could not insert data because ".mysql_error());

// print a success message
echo "Your user account has been created!<br>"; 
echo "Now you can <a href=user_login.php>log in</a>"; 
}

?>

 

THE HASH PART

 

<?php 

$password = $_POST['password'];

$hashed = md5($password); 

if ($hashed == $_POST['password'] { 
exit; 
}
?> 

 

I think it's way off, but I've been staring down md5() and hashing manuals for hours and my brain hurts.

OK, let's break down what you need into actionable steps. As premiso stated I would suggest using a salted hash so if someone was able to get your hashed values they can't use a lookup table to determine the passwords. A salt is just some manner of modifying the value in a consistent manner before hashing. By creating a value that is not 'common' it makes it significantly less likely that someone would have the value in a lookup table. You can salt a value by appending a value (such as the username), reversing the string, or anything that you can consistently replicate.

 

So, here are the steps I would take:

 

1) Create a function to generate a salted hashed password.

2) Create a simple PHP page to run that function on all the current passwords (see caution below)

3) Modify the user creation script to hash the password (using the above function) before doing the SQL Insert

4) Modify the login script to hash to provided password (using the above function) before comparing it against the value in the database.

 

Example hashing function: appends the username to the passoword before hashing to prevent the use of lookup tables if someone got a hold of the value. You could also do something such as reverse the characters of the string or anything that you can consistently reproduce but will result in a value that would not be 'common'.

function hashPW($password, $username)
{
    return sha1($password.$username);
}

 

Sample function to update current records (note this may take a while if you have a LOT of records)

//Be sure to include the hash function!
$query = "SELECT id, username, password FROM users";
$result = mysql_query($query);
$values = array();
while ($record = mysql_fetch_assoc($result))
{
    $query = "UPDATE users
              SET password ='" . hashPW($record['password'], $record['username']) . "'
              WHERE id = {$record['id']}";
    mysql_query($query);
}

You should test this to ensure it works before running. Plus, you might want to backup your database first. It would be bad news if the script fails and you could not return the values to their original values. You could also insert the hashed value into a temporary column.

 

Update the login script to hash entered password before comparing against the db value.

--No code provided

 

Update the Registration script to hash the password

-Change this

// insert the data
$insert = mysql_query("insert into $table values ('NULL', '".$_POST['username']."', '".$_POST['password']."', '".$_POST['email']."')")
or die("Could not insert data because ".mysql_error());

 

-To this

$password = hashPW($_POST['password'], $_POST['username']);
// insert the data
$insert = mysql_query("insert into $table values ('NULL', '{$_POST['username']}', '{$password}', '{$_POST['email']}')")
or die("Could not insert data because ".mysql_error());

 

Lastly, you do not need to worry about protecting the password against sql injection since you are hashing the value - but you definitly want to use mysql_real_escape_string() for the username and email.

PS Here's the login script:

 

<?php

include("config.php"); 

// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());

$match = "select id from $table where username = '".$_POST['username']."'
and password = '".$_POST['password']."';"; 

$qry = mysql_query($match)
or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 

if ($num_rows <= 0) {
echo "Sorry, there is no username, {$_POST['username']}, with the specified password.<br/>";
echo "<a href=log.php>Try again</a>";
exit; 
}
else {
setcookie("loggedin", "TRUE", time()+(3600 * 24));
setcookie("mysite_username", "{$_POST['username']}");
header('Location:http://mythscape.freezoka.com/');
die();
}
?>

 

I don't have a great enough understanding of PHP to be able to modify this. :D

Simply change this

$match = "select id from $table where username = '".$_POST['username']."'
and password = '".$_POST['password']."';";

 

To this

$match = "select id from $table where username = '".$_POST['username']."'
and password = '".hashPW($_POST['password'],$_POST['username'])."';";

 

Again, you REALLY need to be using mysql_real_escape_string() on user submitted values used within a query. I cannot stress this enough. All it would take is one "proplem" input, intentional or accidental, to destroy your database.

This is what I've gotten:

 

The Function

<?php
include "config.php"; 


// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());

function hashPW($password, $username)
{
    return sha1($password.$username);
}
//Be sure to include the hash function!
$query = "SELECT id, username, password FROM users";
$result = mysql_query($query);
$values = array();
while ($record = mysql_fetch_assoc($result))
{
    $query = "UPDATE users
              SET password ='" . hashPW($record['password'], $record['username']) . "'
              WHERE id = {$record['id']}";
    mysql_query($query);
}
?> 

Updated Login Script

<?php

include("config.php"); 

// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());


$match = "select id from $table where username = '".$_POST['username']."'
and password = '".hashPW($_POST['password'],$_POST['username'])."';";

$qry = mysql_query($match)
or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 

if ($num_rows <= 0) {
echo "Sorry, there is no username, {$_POST['username']}, with the specified password.<br/>";
echo "<a href=log.php>Try again</a>";
exit; 
}
else {
setcookie("loggedin", "TRUE", time()+(3600 * 24));
setcookie("mysite_username", "{$_POST['username']}");
header('Location:http://mythscape.freezoka.com/');
die();
}
?>

The Updated Registration Script

<?php 
ini_set ("display_errors", "1");
error_reporting(E_ALL);
include("config.php"); 

// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());

// check if the username is taken
$check = "select id from $table where username = '".$_POST['username']."';"; 
$qry = mysql_query($check) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 
if ($num_rows != 0) { 
echo "Sorry, there the username {$_POST['username']}  is already taken.<br/>";
echo "<a href=user_login.php>Try again</a>";
exit;
}
if($_POST['password'] != $_POST['confirmnewpassword']){ 
   echo ("The two passwords must match. <br/>"); 
echo ("<a href=user_login.php>Try Again</a>");
}
else {

$password = hashPW($_POST['password'], $_POST['username']);
// insert the data
$insert = mysql_query("insert into $table values ('NULL', '{$_POST['username']}', '{$password}', '{$_POST['email']}')")
or die("Could not insert data because ".mysql_error());

// print a success message
echo "Your user account has been created!<br>"; 
echo "Now you can <a href=user_login.php>log in</a>"; 
}

?>

 

I just want to check and make sure it's all good. Thanks in advance to anyone that helps :)

I don't see where you have included the hashing function on the login or registration scripts. That is why I created a function - it will ensure you are slating/hashing the values exactly the same every time. You should put it in an external file and include() it on those pages - never copy and paste a function into multiple pages. You will eventually update one and not the other some day.

These are my final codes, well, the ones I came up with that are probably wrong. :P

function.php

function hashPW($password, $username)
{
    return sha1($password.$username);
}

 

hash.php [for hashing passwords]

<?php
include "config.php"; 


// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());

include "function.php"; 

//Be sure to include the hash function!
$query = "SELECT id, username, password FROM users";
$result = mysql_query($query);
$values = array();
while ($record = mysql_fetch_assoc($result))
{
    $query = "UPDATE users
              SET password ='" . hashPW($record['password'], $record['username']) . "'
              WHERE id = {$record['id']}";
    mysql_query($query);
}
?> 

 

register.php

<?php 
ini_set ("display_errors", "1");
error_reporting(E_ALL);
include("config.php"); 

// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());

// check if the username is taken
$check = "select id from $table where username = '".$_POST['username']."';"; 
$qry = mysql_query($check) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 
if ($num_rows != 0) { 
echo "Sorry, there the username {$_POST['username']}  is already taken.<br/>";
echo "<a href=user_login.php>Try again</a>";
exit;
}
if($_POST['password'] != $_POST['confirmnewpassword']){ 
   echo ("The two passwords must match. <br/>"); 
echo ("<a href=user_login.php>Try Again</a>");
}
else {
include "function.php";
$password = hashPW($_POST['password'], $_POST['username']);
// insert the data
$insert = mysql_query("insert into $table values ('NULL', '{$_POST['username']}', '{$password}', '{$_POST['email']}')")
or die("Could not insert data because ".mysql_error());

// print a success message
echo "Your user account has been created!<br>"; 
echo "Now you can <a href=user_login.php>log in</a>"; 
}

?>

 

login.php

<?php

include("config.php"); 

// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());


$match = "select id from $table where username = '".$_POST['username']."'
and password = '".hashPW($_POST['password'],$_POST['username'])."';";
include "function.php"; 

$qry = mysql_query($match)
or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry); 

if ($num_rows <= 0) {
echo "Sorry, there is no username, {$_POST['username']}, with the specified password.<br/>";
echo "<a href=log.php>Try again</a>";
exit; 
}
else {
setcookie("loggedin", "TRUE", time()+(3600 * 24));
setcookie("mysite_username", "{$_POST['username']}");
header('Location:http://mythscape.freezoka.com/');
die();
}
?>

 

 

I really need to know if these are correctly formatted and stuff so I can re-open my site. Thanks :D

setcookie("loggedin", "TRUE", time()+(3600 * 24));

setcookie("mysite_username", "{$_POST['username']}");

 

 

 

Oh... Errr....

 

 

Never trust cookies.  Having a "loggedin" cookie set to true is a horrible thing security wise.  Cookies can easily be manipulated.  Instead, set a session value or something.

 

 

Also, if you ever want to have a "Remember Me" feature, put the username and some token that a user could not know without actually having done it legitly.

I really need to know if these are correctly formatted and stuff so I can re-open my site. Thanks :D

 

Cetanu,

 

I am more than happy to help provide guidance. But, I am not going to test your code for you. YOU need to test the code against your database to ensure it is working correctly. And, noone can categorically state that your code will work with any certainty. I already stated that I didn't see a problem with what you had. Just follow the steps I posted above. But, as I stated you will want to back up your database first before running the process to update current passwords. Then I would test logging in using an existing account to ensure that update process worked. Then lastly test the process of creating a new account and logging in.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.