im creating a website that requires user authorisation to access some features. im currently working on how a user creates an account and how to utilise sessions to authorise their login. user information is stored in a MySQL table named user which likely includes a reference of username and passwords.
ive been reading up on password hashing/salt for security and wanted the input of some PHP masters, considering im still a rookie to the language.
ive written the following scripts :
define('SALT_LENGTH', 6);
function generateHash($plaintext, $salt==null){
if($salt == null){
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else{
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($salt . $plaintext);
}
?>
this is a function included to generate a hash with a salt.
$username = $_POST['username'];
$password = generateHash($_POST['password']);
try{
$stmt = $pdo->prepare(INSERT INTO user VALUES (:username, :password, :location, :email, :name);
}catch(PDOException $e){
echo $e->getMessage();
}
$stmt->execute(array(':username'=>$username,
':password'=>$password,
':location'=>$location,
':email'=>$email,
':name'=>$name);
this is the important parts of the script to create an account
if(isset($_POST)){
//if form was submitted
$username = $_POST['username'];
$password = generateHash($_POST['password']);
session_start();
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay;', $user, $pass);
try{
$stmt = $pdo->prepare('SELECT username FROM user WHERE username = :username AND password = :password');
$stmt->execute(array(':username'=>$username,
':password'=>$password);
if($stmt->fetch(PDO::FETCH_ASSOC)){
echo 'match';
}
else{
echo 'nomatch';
}
this is the login session script to lookup users in the database
my main question is does this hashing/salt look like it will work? im confused as to how a hash used to create an encryption in one instance (create acct) will be able to work with a hash created in a different instance. further, is the complexity of what im trying to create appropriate for a relatively simple software project that will likely never be properly deployed?
any other suggestions of where my scripts are wrong will be appreciated also (i need the criticism).