Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

encryption issues....

Status
Not open for further replies.

imryn

Programmer
Dec 2, 2002
75
US
Hello Everyone,

Okay, I am wondering what I am doing wrong. I was trying to use the php function crypt to due something like $encpswd = crypt($password). then store $encpswd in mysql database. However, when I try to login in it's not verifying the password. I understand that crypt() is a one-way encrption, but can't I do something to retrieve it?

I tried using md5 and sha1 both worked to encrypt the password, however, I can retrieve it, any idea's?
example of what I am doing...
$query = SELECT COUNT(*) FROM login where username = '$username' AND passw = md5('$pswd')";

Thanks,
imryn
 
for you to use the crypt function in place of a static routine like md5 or sha1 (which, to my mind, are more encodings rather than encryptions) you need to keep the salt constant or at least let the function know what the salt first used was.

so, for an automatic salt you could use this code:

Code:
$pwd = trim($_POST['pwd']);
$uname = trim ($_POST['uname']);
$c_pwd = mysql_result(mysql_query("Select pwd from usertable where username='".mysql_escape_string($uname)."'),0,0);
if (crypt($pwd, $c_pwd) == $c_pwd):
  echo "passwords match";
else:
  echo "passwords do not match";
endif;

for a fixed salt it is much easier and you can use a sql count rather than select (less server strain)

Code:
$salt = "somestring";
$pwd = trim($_POST['pwd']);
$uname = trim ($_POST['uname']);

if (mysql_result(mysql_query("
         Select count(*) 
         from usertable 
         where 
          uname='".mysql_escape_string($uname)."'
          and
          pwd='".mysql_escape_string(crypt($pwd, $salt))."'" == 0:
  // return success
else:
  // return fail
endif;

nb - this is typed straight in to the textarea so may well have parse errors or other faults.
 
Justin,

So your saying that $salt = "somestring" can be anything, and it acts like a "key" so to speak? Cool... I will try this tomorrow when I have a chance, thanks

Ryan
 
so i believe, yes. i don't think it is quite a key but the basis for the internal randomisation of the crypt function.

 
Justin,

I am a little confused about something. When I go to insert my password should I do something like this...
Code:
$pswd = mysql_escape_string($_POST['password'];
$encpswd = crypt($pswd);

INSERT INTO login(username, passw) VALUES("'$usrid','$encpswd')";
then use this to retrieve it
Code:
$salt = "somestring";
$pwd = trim($_POST['pwd']);
$uname = trim ($_POST['uname']);

if (mysql_result(mysql_query("
         Select count(*) 
         from usertable 
         where 
          uname='".mysql_escape_string($uname)."'
          and
          pwd='".mysql_escape_string(crypt($pwd, $salt))."'" == 0:
  // return success
else:
  // return fail
endif;
Thanks,
Ryan
 
Justin,

I am having no luck at the moment. I was search this site and came across this code you did for someone else. I copied it and tried it my self, however, I am have the same issue, once the user is created and I log out, I can't log back in. I think the issue is in the "validlogon" function at line 299. Here are the two pieces of code then I will post the original code you did. I think I just need to change the sql statement to make it work, but I am not sure.... any advise?... thanks
Code:
function login()
{
    if (!isset ($_POST['submit'])):
        logout();
    endif;
    
    switch ($_POST['submit']):
        case "Reset Password":
            $_SESSION = array();
            session_destroy();
            display_reset_password_form();
            break;
[COLOR=red]        case "Login":
            if (!test_fresh_login()):
                logout("You cannot re-login through the back button");
                exit;
            endif;
            
            if (!validlogon()):
                logout("Either username or password is incorrect");
            else:
                $_SESSION['username'] = $_POST['username'];
                $_SESSION['loggedon'] = true;
                $_SESSION['lastaccess'] = strtotime("now");
                unset ($_POST);
                header("Location: ".$_SERVER['PHP_SELF']);
            endif;
        break;   [/color]
        case "Register New User":
            display_new_user_form();
            exit;
        break;
        case "Register":
            process_registration();
        break;
        case "Submit Reset Request":
            resetpassword();
        break;
        default:
            logout();
    endswitch;
}


function validlogon()
{
    if (!isset ($_POST['username']) || !isset ($_POST['pwd'])):
        return false;
    endif;
    dbconnect();
    
    $sql = "
        Select 
            pwdchange
        from 
            usertable 
        where 
            username = '".trim($_POST['username']) ."'
            and
            pwd = '".md5(trim($_POST['pwd']))."'";
            

    $results = mysql_query($sql);
    $row = mysql_fetch_assoc($results);
    if (mysql_num_rows($results) != 0):
        if ($row['pwdchange'] !='1'):
            $_SESSION['flagpwd'] = false;
        else:
            $_SESSION['flagpwd'] = true;
        endif;
        $_SESSION['uniqstamp'] = $_POST['uniqstamp'];
        return true;
    else:
        return false;
    endif;
}

original code....
Code:
<?php 
session_start();
?>
<style>
fieldset {border-color:#0000FF; width:60%;}
table:{width:100%; border-collapse:collapse;}
</style>
<?
/*    DEBUG 
echo "session vars<br/>";
print_r($_SESSION);
echo "<br/>";
echo "post vars<br/>";
print_r($_POST);
*/

//use this script by just including the page at the top of every real page
if (!loggedon()):  
    login();  
else:
    ##this line is included for debug. 
    #normally you would just let the script continue
    echo "You are logged on<br/> click<a href=\"". $_SERVER['PHP_SELF']."?logout=true\"> here </a> to logout";
endif;

function loggedon()
{
//this tests the current status
    if (isset ($_SESSION['loggedon'])):
        if (($_SESSION['lastaccess'] + (60 * 1)) < strtotime("now")):
            logout("Session has timed out");
            exit;
        else:
            $_SESSION['lastaccess'] = strtotime("now");
            
            if ((isset($_POST['submit']) && ($_POST['submit'] === "Change Password"))):
                process_change_password();
                exit;
            elseif (isset($_SESSION['flagpwd']) && ($_SESSION['flagpwd'] === true)):
                changepassword();
                exit;
            elseif (isset($_GET['logout'])):
                logout();
                exit;
            else:
                return true;
            endif;
        endif;
    else:
        return false;
    endif;
}



function render_user_form($msg=NULL)
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Login</legend>
<table>
<input type="hidden" name="uniqstamp" value="<?=strtotime("now")?>" />
<? if (!is_null($msg)):?>
<tr><td colspan="2"><?=$msg?></td></tr>
<? endif; ?>
<tr><td>Username:</td><td><input type="text" name="username"  /></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Login" /></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Reset Password" /><input type="submit" name="submit" value="Register New User" /></td></tr>
</table>
</p>
</fieldset>
</form>
<?
}


function logout($msg=NULL)
{
    $_SESSION = array();
    session_destroy();
    render_user_form ($msg);
    exit;
}
//master script
function display_reset_password_form()
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Reset</legend>
<table>
<tr><td>Email:</td><td><input type="text" name="email"  /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Submit Reset Request" /></td></tr>
</table>
</fieldset>
</form>
<?
}

function login()
{
    if (!isset ($_POST['submit'])):
        logout();
    endif;
    
    switch ($_POST['submit']):
        case "Reset Password":
            $_SESSION = array();
            session_destroy();
            display_reset_password_form();
            break;
        case "Login":
            if (!test_fresh_login()):
                logout("You cannot re-login through the back button");
                exit;
            endif;
            
            if (!validlogon()):
                logout("Either username or password is incorrect");
            else:
                $_SESSION['username'] = $_POST['username'];
                $_SESSION['loggedon'] = true;
                $_SESSION['lastaccess'] = strtotime("now");
                unset ($_POST);
                header("Location: ".$_SERVER['PHP_SELF']);
            endif;
        break;
        case "Register New User":
            display_new_user_form();
            exit;
        break;
        case "Register":
            process_registration();
        break;
        case "Submit Reset Request":
            resetpassword();
        break;
        default:
            logout();
    endswitch;
}
function display_new_user_form($msg=NULL)
{
$username ="";
$email="";
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Login</legend>
<table>
<input type="hidden" name="uniqstamp" value="<?=strtotime("now")?>" />
<? if (!is_null($msg)):?>
<tr><td colspan="2"><?=$msg?></td></tr>
<? 
extract ($_POST);
endif; ?>
<tr><td>Username:</td><td><input type="text" name="username"  value="<?=$username?>"/></td></tr>
<tr><td>Email:</td><td><input type="email" name="email" value="<?=$email?>"/></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="pwd_confirm" /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Register" /></td></tr>
</table>
</fieldset>
</form>
<?
}
function process_registration()
{
    $msg = "";
    if (!isset ($_POST['username']) || empty($_POST['username'])):
        $msg .= "You must supply a username<br/>";    
    endif;
    if (!isset ($_POST['email']) || empty($_POST['email'])):
        $msg .= "You must supply an email address<br/>";    
    endif;
    if (!empty($_POST['pwd'])):
        if ($_POST['pwd'] != $_POST['pwd_confirm']):
        $msg .= "Your password confirmation must match<br/>";    
        endif;
    endif;
    dbconnect();
    $sql = "Select 
                count(*) as cnt 
            from 
                usertable 
            where 
                username='".trim($_POST['username'])."'";
    $result = mysql_query ($sql);
    $row = mysql_fetch_assoc($result);
    if ($row['cnt'] != 0):
        $msg .= "Your chosen username is already in use<br/>";
    endif;
    
    if (!empty($msg)):
        display_new_user_form($msg);
        exit;
    endif;
    
    //all validated now
    
    $sql = "
        insert into
            usertable
        set
            username = '".trim($_POST['username'])."',
            pwd = '".md5(trim($_POST['pwd']))."',
            email = '".trim($_POST['email'])."'";
    
    mysql_query($sql);
    if (mysql_affected_rows() != 1):
        die(mysql_error());
    endif;
    //now log the user on
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['loggedon'] = true;
    $_SESSION['lastaccess'] = strtotime("now");
    unset ($_POST);
    header("Location: ".$_SERVER['PHP_SELF']);

}
function process_change_password()
{
    $msg = "";
    if (!isset ($_POST['username']) && !empty($_POST['username'])):
        loggedout("something wrong here");
        exit;
    endif;
    if (!empty($_POST['pwd'])):
        if ($_POST['pwd'] != $_POST['pwd_confirm']):
        $msg .= "Your password confirmation must match<br/>";    
        endif;
    endif;
    if (!empty($msg)):
        changepassword($msg);
        exit;
    endif;
    $sql = "
        update 
            usertable
        set
            pwd = '".md5(trim($_POST['pwd']))."',
            pwdchange = '0'
        where
            username = '".trim($_POST['username'])."'";
    dbconnect();
    if (!mysql_query($sql)):
        die("something wrong here ".mysql_error() . " affected rows are ".mysql_affected_rows() . " and sql is $sql");
    endif;
    unset ($_POST);
    $_SESSION['flagpwd'] = false;
    echo "Password changed.<br/> click <a href=\"".$_SERVER['PHP_SELF']."\">here</a> to continue";
}
function test_fresh_login()
{
    if (isset($_SESSION['uniqstamp'])):
        if (isset($_POST['uniqstamp'])):
            if ($_SESSION['uniqstamp'] === $_POST['uniqstamp']):
                return false;
            else:
                return true;
            endif;
        else:
            //something wrong here
            logout ("You have arrived here unexpectedly");
            exit;
        endif;
        $_SESSION = array();
        session_destroy();
    else:
        return true;
    endif;
}
function dbconnect()
{
    @mysql_connect("localhost", "root","root") or die ("unable to connect to server");
    @mysql_select_db("test") or die ("unable to connect to database");
    
    /*
    note you need a table called usertable
    CREATE TABLE `usertable` (
    `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `username` VARCHAR( 255 ) NOT NULL ,
    `pwd` VARCHAR( 255 ) NOT NULL ,
    `email` VARCHAR( 255 ) NOT NULL ,
    `pwdchange` int (1) NOT NULL,
    UNIQUE (
    `username` 
    )
    ) TYPE = innodb;
    */
    
}
function validlogon()
{
    if (!isset ($_POST['username']) || !isset ($_POST['pwd'])):
        return false;
    endif;
    dbconnect();
    
    $sql = "
        Select 
            pwdchange
        from 
            usertable 
        where 
            username = '".trim($_POST['username']) ."'
            and
            pwd = '".md5(trim($_POST['pwd']))."'";
            

    $results = mysql_query($sql);
    $row = mysql_fetch_assoc($results);
    if (mysql_num_rows($results) != 0):
        if ($row['pwdchange'] !='1'):
            $_SESSION['flagpwd'] = false;
        else:
            $_SESSION['flagpwd'] = true;
        endif;
        $_SESSION['uniqstamp'] = $_POST['uniqstamp'];
        return true;
    else:
        return false;
    endif;
}    
function changepassword($msg=NULL)
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Change Password</legend>
<table>
<? if (!is_null($msg)):?>
<tr><td colspan="2"><?=$msg?></td></tr>
<? endif; ?>
<input type="hidden" name="username" value="<?=$_SESSION['username']?>" />
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="pwd_confirm" /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Change Password" /></td></tr>
</table>
</fieldset>
</form>
<?
}
function resetpassword()
{
dbconnect();
    
    $password = "pcworld";
    $sql = "
        Update 
            usertable
        set
            pwd = '".md5(trim($password))."',
            pwdchange = '1'
        where
            email ='".trim($_POST['email'])."'";
    
    echo $sql ."<br/>";
    mysql_query($sql); //errors deliberately suppressed
    if (mysql_affected_rows() != 0):
        mail(trim($_POST['email']),"New password", "Your new password is $password");
    endif;
    die ("If you have provided a correct email address that is in our system, an email with your new password will be sent to you shortly. <br/>click<a href=\"". $_SERVER['PHP_SELF']."\"> here </a> to login<br/>DEBUG: password is $password. ");
}
?>
 
ryan - i haven't time this morning to review your longer post.

on the shorter post:

insert password into database either as you have posted or
Code:
$salt = "somestring";
$pwd = crypt($_POST['pwd'], $salt);

to retrieve:
if you have used a defined salt when inserting the password you can just compare what is in the database with
Code:
crypt($_POST['pwd'], $salt);
if you have gone the first route of using a dynamic salt the logic you must use is:

1. retrieve from the database the password that corresponds to the username the user has typed in. this is because crypt stores the salt within the crypted version
2. use the retrieved version of pwd as the salt for a crypt on the incoming user entered password.
3. compare db version with the new crypted version.
this is as per my first post
Code:
$pwd = trim($_POST['pwd']);
$uname = trim ($_POST['uname']);
$c_pwd = mysql_result(
          mysql_query("Select pwd from usertable where username='".mysql_escape_string($uname)."'"),0,0);
//you probably want to do some error checking here.  
if (crypt($pwd, $c_pwd) == $c_pwd):
  echo "passwords match";
else:
  echo "passwords do not match";
endif;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top