I was looking for the best way to store the users' passwords, but I'm not really into security, so I've found a lot of information about encryption and things like that, using Google.
I don't like using snippets that I can get in blogs or sites on the Internet, I'd rather create my own solution, so I ended up developing two functions: One to create a hash and another one to check the "hashed" password.
I don't know if I'm doing right, or if I'm just increasing my problems, so take a look at the functions below.
// Creates a simple password's hash
function hashPassword( $password = false )
{
// Checks if the password has more than 6 characters
if( strlen( $password ) < 6 )
{
// Kills the script
exit('Password is too short.');
}
// Split the 4 first characters of the password
$salt = substr( $password, 0, 4 );
// Calculate the md5 hash of the salt
$salt = md5( $salt );
// Get the rest of the password
$password = substr( $password, 3, strlen( $password ) );
// Calculate the md5 hash of the password
$password = sha1( $salt . $password );
// Crypt the password
$password = crypt( $password );
return $password;
}
That's the password that I'm going to store. Now, check out the way I'm gonna check if the password's correct.
// Checks if a hashed password match a user input password
function checkHashedPassword( $password = false, $hashedPassword = false )
{
// Checks if the password has more than 6 characters
if( strlen( $password ) < 6 )
{
// Kills the script
exit('Password is too short.');
}
// Split the 4 first characters of the password
$salt = substr( $password, 0, 4 );
// Calculate the md5 hash of the salt
$salt = md5( $salt );
// Get the rest of the password
$password = substr( $password, 3, strlen( $password ) );
// Calculate the md5 hash of the password
$password = sha1( $salt . $password );
// Checks the password and hash
if( crypt( $password, $hashedPassword ) == $hashedPassword )
{
// Returns true
return true;
}
// Returns false by default
return false;
}
As you can notice, I'm going to create a variable storing the password, and the I can check if it's ok, like the code below:
$pass = hashPassword( $_POST['password'] );
if( !checkHashedPassword( $_POST['password'], $pass ) )
{
exit('Password incorrect!');
}
So, will it work securely?