0

Possible Duplicate:
Secure hash and salt for PHP passwords

I am working on a PHP script for my site, the site it's self is up and running. The problem I have is that the registration on the website is for plain text passwords. Obviously this is very weak security. I am hoping someone can help me convert it so I can use a hash password. I have included part of the registration code that I think counts. I did not include all code on the page as I did not think it relevant but will supply if someone thinks it will help.

require 'include.inc';
if ($signup) {

if ($signup[repassword] != $signup[password]) {
    $err_msg = "Your passwords do not match.";
error($err_msg);
}

if(!preg_match("^[_\.0-9a-z-]+$/i^", $str)) {
$msg = 'Invalid Username! Usernames can consist of letters and numbers only';
}
if(!preg_match("^[_\.0-9a-z-]+$^",$signup[password])) {
   $err_msg = "Invalid Password!  Passwords can consist of letters and numbers   only.";
}
  if(!$signup[password] || !$signup[username] || !$signup[email] || !$signup[username])
        $err_msg = "Oops! You forgot some important fields!";


  if (!$err_msg) {
$usercheck = @mysql_query("INSERT INTO user values(
    'NULL','$signup[fname]','$signup[lname]',
    '$signup[username]','$signup[password]','$signup[email]', 1, ".$pointInc.",     '$signup[referral]', NOW(), 'n', 'y')");

      // done, you are entered correctly, Now Enter the points and URL info


        $sql = "Select id from user where username='$signup[username]'";

    $result = mysql_query( $sql );
        if ( $result != false )
            {
        while ( $data = mysql_fetch_assoc( $result ) )
        {
            $point_set = $data['id'];

            }
        } else {
            echo mysql_error();
        }   
    // add rerral points

if ($signup[referral])  {
  $referralSql="UPDATE points SET points=points+ ".$refPoints . " WHERE     userid=".$signup[referral];
  $result = mysql_query( $referralSql );
                if ( $result != false )
                    {
                } else {
                    echo mysql_error();
                    }
    }                           


// add URL  

$sql="INSERT INTO url_table ( userid, website, active, datechanged) VALUES ($point_set,'".$signup[site_url]."','n', '".date("Ymd")."')";

  $result = mysql_query( $sql );
                if ( $result != false )
                    {
                } else {
                    echo mysql_error();
                }
// add points
    $sql="INSERT INTO points (userid, username, points) VALUES ($point_set,'     ',$signPoints)";
  $result = mysql_query( $sql );
                if ( $result != false )
                    {
                } else {
                    echo mysql_error();
                    }
    }
     echo mysql_errno().": ".mysql_error()."<br>";





            if (!$usercheck) {
       $err_msg = "Database error:<br>There was an error entering your account.<br>It is possible that username or Email already exists, please try another one.<br>";
         }   else {
            include ("reg.php"); 
            exit;
            }
     }
     if (!$err_msg) {
        // done, you are entered correctly



     }
   pageHeader($title, $bgColor, $styleSheet);
?>
Community
  • 1
  • 1
user1906671
  • 21
  • 1
  • 4
  • You have a SQL injection vulnerability. – SLaks Jan 23 '13 at 13:29
  • `Passwords can consist of letters and numbers only` .. That is _extremely_ wrong. – SLaks Jan 23 '13 at 13:30
  • 4
    Don't restrict the characters that I can have in my password.... it restricts me, adds to the complexity of your code, reduces security, and is completely unnecessary – Mark Baker Jan 23 '13 at 13:30
  • Creating a hash for a string is easy and asked many times, just [search around on SO](http://stackoverflow.com/search?q=php+hash+password)! – Veger Jan 23 '13 at 13:31
  • try this link http://php.net/manual/en/faq.passwords.php or http://phpmaster.com/password-hashing-in-php/ – Rakesh Sharma Jan 23 '13 at 13:33

5 Answers5

2

The basic principle is quite easy:

1 . When a user registers, don't store the plaintext password, but hash(password).

$query = $pdoObject->prepare('INSERT INTO users (UserName, Password) VALUES (:u, :p)');
$query->bindParam(':u', $_POST['username']);
$query->bindParam(':p', hash($_POST['password']));
// Note that we don't store the password, we store the hash of the password. Once this script is done executing, no one involved in the website (except for the original user) will know that the password is
$query->execute();

2 . When a user attempts to log in, calculate the hash of the entered password with the hash stored in your user database. If both hashes match, the password is correct.

$query = $pdoObject->prepare('SELECT * FROM users WHERE UserName = :u AND Password = :p');
$query->bindParam(':u', $_POST['username']);
$query->bindParam(':p', hash($_POST['password']));
// We locate the original user by searching for the hash of the password that they typed in

So much for theory. Some practical issues you should consider:

  1. Many tutorials suggest using MD5 of SHA1 as hash functions. However, these are not secure. Check the PHP hash library (especially the hash() function) for available hashing algorithms.
  2. You should also consider using salted passwords. For each registered user, create a random string (the salt), concatenate this string with the user's password and then hash both password and salt (the salt needs to be saved too, because you need it again when authenticating the user).
  3. You can use PDO to make your SQL more secure. This will protect you against something called SQL Injection. If you don't do this, then users will be able to mess up your website by entering characters such as apostrophes (').
Chris
  • 3,328
  • 1
  • 32
  • 40
helmbert
  • 35,797
  • 13
  • 82
  • 95
  • as long as you don't protect your login form from external requests it will be open for brute force tryouts with plain passwords and it does not matter how you hash or crypt the password in the db. – stocker4all Jan 23 '13 at 16:42
  • 1
    True, but on-line brute force attacks are extremely ineffective, because you can only try out passwords at a very limited rate (due to bandwidth, latency, server capacities, ...). So usually, a brute force attempt on a login form will not be successfull within a reasonable amount of time. Strong hash algorithms are usually strong enough to withstand even offline brute force attacks (which require that an attacker gets his hands on the password hashes) in which an attacker can try out millions of different hashes per second... – helmbert Jan 23 '13 at 16:50
0

You can use md5 function to create a hash for your passwords, example:

$password = '12345';
$password = md5($password);

You save this hash at the database and when you will check user and password for login you do this

$post['password'] = md5($post['password']);

and check if is equal of the hash saved in the database. I know that md5 is not the best hash but is simple and has a good level of security

  • 2
    Using plain MD5 as hashing algorithm is **extremely insecure**. MD5 hashes can be computed extremely fast (making brute force easy) and the algorithm is prone to collisions. – helmbert Jan 23 '13 at 13:37
0

Use crypt for hashing passwords.

troelskn
  • 115,121
  • 27
  • 131
  • 155
-1

Use md5 for that http://php.net/manual/en/function.md5.php

Also look up uniqid http://php.net/manual/en/function.uniqid.php

It's always a bad practice to store the password in plain text in your database. Check this other question: What are the best practices to encrypt passwords stored in MySql using PhP?

Community
  • 1
  • 1
Andrei Cristian Prodan
  • 1,114
  • 4
  • 17
  • 34
-1

some opinions don't think md5 or SHA-1 breakable, try to salt them.. search that.

blackmath
  • 242
  • 1
  • 10