md5 encryption and decrypt Not working well on remote host

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

md5 encryption and decrypt Not working well on remote host

Post by MikeSpider »

Hi guys,
I tried the md5 encryption and decryption for passwords, and it works fine on my local server.
On remote server for some reason it only encrypts on database , but is not decrypting when the user logs in.
my code follows:

Code: Select all


//registration page
.......

if($_pwd == $_pwd2){

                 $hash_val = md5($_pwd);
                 $register = new Registration();
                 $register->insert($_user, $hash_val,$_email, $_name, $_surname, $_country, $_FILES, $_previledges);

Code: Select all


//login page

....

if( "" != $_user && "" != $_pwd )
        {
           
            $hash_val = md5($_pwd);

            //compare field values with database values for admin login
            $auth = new Authentication();
            $auth->Login($_user, $hash_val);

//compare field values with database values for user login
            $auth2 = new Registration();
            $auth2->Login($_user, $hash_val);
.....

As I said, the above code works fine in Localhost but not on live host
Any help will be very much appreciated!
thanks,
Mike Spider
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: md5 encryption and decrypt Not working well on remote ho

Post by twinedev »

what function are you trying to use to decrypt md5? (Don't answer, that was a programmer joke, prepare for others to point out that md5 is one way hashing, not encryption that can be decrypted, and that md5 is weak to begin with)

Seriously though, for any help, you'd need to give more code. we have no idea what the classes you are using and/or the code behind them.

Have you done any debugging in the code to see what it is doing in Login ? how is it comparing data, what it retrieving from the database, etc...

How is your table defined? Many questions, the more info you give, the more we can possibly help you.

-Greg
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

Thanks for your quick reply.
I dint put all the functions involved, because the only place i use the hash is in the above code.
all my main functions are inside classes. The insert function just grabs whtever parameters i pass along, cleans them up,
compares to see if a user or email already exists in DB, if not, insert them into DB, else returns false.

The login function just grabs the user values( username + password) and compares with values on DB to see if it exists.


This is strange because it works on my localhost.
Why should't it work on remote host? What's the point then of having a localhost, when things will behave diferently in remote host?

I just read about the hashing recently, and tried it out and it worked. When users register, their password is hashed in the database. but when they try to access
their account in the login form, the password wont work, because it is now hashed. So, my idea (good or bad, but at least I had results localy) was to hash back, whatever input the user writes in the login field. , My guess was: if hashing is just a case of giving a crypt code equivalent to some word, then this crypt code would always be equivalent to the same word. It worked! and it also prooves it not so safe. but at least is better than not having anything at all.
It worked only on local server, hashing back to real values never happened on live server.

If you have any other sugestions for real encryption,
i'd be greatful,
Mike Spider
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: md5 encryption and decrypt Not working well on remote ho

Post by twinedev »

Well, without actually seeing the code that actually checks things, and the way you describe it, yet it should be working.

Make sure the code for the Login Function does the exact same thing in the two classes you are using.

Beyond, that, start dumping data to see what it retrieving from the database to see exactly what it is comparing.

If you do a search on here for "md5 hash password salt" you will probably find one of the many threads where there are suggestions on proper ways to handle this.

-Greg
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: md5 encryption and decrypt Not working well on remote ho

Post by Apollo »

Well, here goes: md5 is one way hashing, not encryption that can be decrypted, and md5 is weak to begin with! :)
MikeSpider wrote:My guess was: if hashing is just a case of giving a crypt code equivalent to some word, then this crypt code would always be equivalent to the same word. It worked! and it also prooves it not so safe. but at least is better than not having anything at all.
What's not so safe? Remember: not safe is to store the actual password, either in plaintext (very unsafe) or encrypted in some way (still not safe).

Think of hashing like taking a fingerprint. A checksum. You put a password (or any piece of data) in, you get some number in return. It's these hash numbers that you store in your database, and compare to authenticate a user.
It worked only on local server, hashing back to real values never happened on live server.
I can assure you it didn't happen on local server either. Perhaps you forgot to register your account on the live server? Is your database setup correctly? (do you check for SQL errors?)
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

@ Apollo, Yes it did work on local server!!! No database errors.
I tested everything and double checked! Just tried it now and it still does works!!!!
Strange ha??
I hope it doesn't give you nightmares hehehehe.

I dont use md5 in any class function, and it works well that way localy, so i dont see the relevance of posting my entire code.
Do I need to pass the $hash_val variable to the class Login and insert functions in order to work in remote server?
Thanks,
Mike Spider
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

Hey, I just went through everythin in my remote server, and guess what???
I found the problem.
it was in my database "password" field. in order for md5 to work the varchar field should be not less than 32 characters.
I had 16, that's why it wasn't working.
It's working now.

thanks for your replies anyways.

@ apollo, if you say that storing any password in database is a risk then how do you authenticate users then?
If you know of a better way than storing values in DB, please share it.

Many thanks,

Mike Spider
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: md5 encryption and decrypt Not working well on remote ho

Post by Apollo »

MikeSpider wrote:@ Apollo, Yes it did work on local server!!! No database errors.
I tested everything and double checked! Just tried it now and it still does works!!!!
Strange ha??
I hope it doesn't give you nightmares hehehehe.
Well, I'm quite sure you made a mistake somewhere or misinterpreted a result. No md5 checksums are ever 'hashed back to real values', really.

It's the same as reverting a string length (i.e. an integer such as 6) back to the original value (i.e. a string such as 'secret').
@ apollo, if you say that storing any password in database is a risk then how do you authenticate users then?
If you know of a better way than storing values in DB, please share it.
You don't store passwords in your database (or anywhere), you only store their hashes.

Upon login, you take the hash from whatever password they fill in, and compare that against the hash in your database. If it's a match, you can safely assume they entered the correct password.

For security purposes, don't use md5($password) to hash a password, but something like hash( 'sha512' , $password.'vLh4*m3p8-7xj8unG#1rF4jd'.$userId )
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

Thanks for all the help,

@Apollo, are you calling me mad? lol >>>
I'm telling that it DID HASH BACK!!

what I mean is : MY SCRIPT ABOVE DOES WORK!

it hashes the pwd user inputs when he registers, the hash is stored in DB. I TRIPLE CHECKED, AND THERE ARE ONLY
32 DIGITS HASHES IN DB !!!

then to login again , I copied the hashed value from database and inserted in the password login area,
and it does not work, because I used the md5 to hashed back in login function area, so he needs to put the real password which the script will compare with the equivalente hashed value in db. only the user knows the password.

why dont you give it a try>> b4 saying that i must have made a mistake.

It does work!!!!!

cheers
Mike
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

ah, just a reminder,
never be too sure, always test the possibilities, and triple check!
:)
i'm gone,
Mike
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: md5 encryption and decrypt Not working well on remote ho

Post by Celauran »

Nobody can try it because you haven't posted the code. Nobody is saying your code doesn't work because, again, we can't see it. Your insistence that you've somehow 'decrypted' the md5 hash is what's being called into question.
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

ok here is the code:

Code: Select all

//mY CLASS

class Registration {
  public $db;
  public $data;
  private $sucess = false; 

    //constructor
    public function  __construct() {
          $this->db = new DB();
    }

    // Register/insert new user

     public function insert($user,$pwd,$email,$name,$surname,$country,$image,$previledges)
    {
      try{

          $_user = $this->db->mysqli->real_escape_string($user);
          $_pwd = $this->db->mysqli->real_escape_string($pwd);
          $_email = $this->db->mysqli->real_escape_string($email);
          $_name = $this->db->mysqli->real_escape_string($name);
          $_surname = $this->db->mysqli->real_escape_string($surname);
          $_country = $this->db->mysqli->real_escape_string($country);
          $_previledges = $this->db->mysqli->real_escape_string($previledges);

          //Check to see it the user already exists

          $sql = "SELECT COUNT(*) AS regist_count FROM registration WHERE email='{$_email}' OR user='{$_user}'";
          $result = $this->db->mysqli->query($sql);

          if(!$result){
                throw new Exception("Query failed: " . $sql . " - " . $this->db->mysqli->error);

          }else{

              $this->data[] = $result->fetch_assoc();
              if( 0 == $this->data['regist_count']){
                  
                 if( "" != $image['picture']['name'] && 0 != $image['picture']['size'] ){
                        // file to upload
                        $file_upload = true;
                        $img_name = time() . $image['picture']['name'];
                    } else {
                        // no file to upload
                        $img_name = 'noimage2.jpg';
                    }

                  $sql = "INSERT into registration VALUES(NULL,'{$_user}','{$_pwd}','{$_email}','{$_name}','{$_surname}','{$_country}','{$img_name}','{$_previledges}', NOW())";

                  $result = $this->db->mysqli->query($sql);

                  if(!$result){

                      throw new Exception("Query failed: " . $sql . " - " . $this->db->mysqli->error);

                   }else{
                        // check for upload
                        if( true == $file_upload ){
                            move_uploaded_file($image['picture']['tmp_name'], 'images/registration/' . $img_name);
                        }
                       
                        $this->success = true;
                  }

              }
                
          }

      } catch(Exception $e){
           echo("");
        }
    }

    //Login function for registered user

    public function Login($user,$pwd)
    {
        try{         

           $_user = $this->db->mysqli->real_escape_string($user);
           $_pwd = $this->db->mysqli->real_escape_string($pwd);

           $sql = "SELECT COUNT(*) AS user_count FROM registration WHERE user='{$_user}' AND pwd='{$_pwd}'";
           $result = $this->db->mysqli->query($sql);
           
           if(!$result){

                   throw new Exception("Query failed: " . $sql . " - " . $this->db->mysqli->error);

           }else{

               $count = $result->fetch_assoc();

               if(1 == $count['user_count'] )
               {
                   $this->success=true;
               }               
           }

    } catch(Exception $e){
       echo("Message: " . $e->getMessage());
    }
    }

// function to help access the return value from login function

    public function Success()
    {
        return $this->success;
    }

}

Code: Select all


//register.php  page

//load inc ..... etc

if("Register" == $_POST['submit']){

    $_user =FilterData($_POST['user']);
     $_pwd =FilterData($_POST['pwd']);
      $_pwd2 =FilterData($_POST['pwd2']);
       $_email =FilterData($_POST['email']);
        $_name =FilterData($_POST['name']);
         $_surname =FilterData($_POST['surname']);
         $_country =FilterData($_POST['country']);
           $_nospam = FilterData($_POST['6_letters_code']);
             $_previledges =FilterData($_POST['previledges']);


       //error handling
            

     //all fields are required

         if("" != $_user && "" != $_pwd && "" != $_pwd2 && "" != $_email && "" != $_name && "" != $_surname && "" != $_country  && "" != $_nospam){

// cheking the captcha(security random number validation) for valid input
  if(empty($_SESSION['6_letters_code'] ) ||
	  strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
	{
	$message_spam= "\n The security code does not match!";

                

        }elseif($_pwd == $_pwd2){

                //Filter email and check for valid email
            if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_email)) {

                $hash_val = md5($_pwd);
                 $register = new Registration();
                 $register->insert($_user, $hash_val, $_email, $_name, $_surname, $_country, $_FILES, $_previledges);

                 if(true == $register->Success()){
                  $_SESSION['temp_user'] = $_user;
                  header("location: registration-confirm.php");


                 }else{

                     $message_regis ="This email/user already exists in our database,
                         Please <a style='color:blue'href='login.php'>Login </a>or try again";
                     //timer for message readability


                     }}
                    else {
                      $message_email = "Invalid email address.";
                    }

             }if($_pwd != $_pwd2){

         $message_pwd = "passwords don't match!";

       }if("" == $_country){

           $message_country = "Please select country!";
       }
       
        // $regist = new Registration();
         //$regist->insert($_user, $_pwd, $_email, $_name, $_surname);


       }else{

           $message_empty = "Please check required fields!";
       }


}

?>

form .....

// My Login.php page

<?php

//load include (inc) file
require_once 'inc.php';

/*page logic */

if("Login" == $_POST['submit'])
{
$_user = FilterData($_POST['name']);
$_pwd = FilterData($_POST['pwd']);


//check for required fields
if( "" != $_user && "" != $_pwd )
{
$hash_val = md5($_pwd);
//compare field values with database values
$auth = new Registration();
$auth->Login($_user, $hash_val);

if(true == $auth->Success())
{

$_SESSION['regis_user'] = $_user;

//redirect to home page
header("location:index.php");
exit();

}else{
$warning = "wrong details";
}


}else{
$warning = "check required fields!";
}

}

?>
<div id="main_content">
<fieldset id="login_box">

<legend>Login</legend>
<br><br>

<?php if($warning){ echo("<p class='error_msg'>{$warning}</p>");}?>

<form id="login_form"method="post" action="<?php echo($_SERVER['PHP_SELF']);?>">
<ul>
<label for="name" class="required"><b style="color: red;font-size: 20px">*</b>Name:</label>
<li style="padding-left:10%"> <!-- this fixes i.e. -->

<input type="text" name="name" id="name" size="19" value="<?php echo($_user)?>"/>
</li>
<label for="pwd" class="required"><b style="color: red;font-size: 20px">*</b>Password :</label>
<li>
<input type="password" name="pwd" id="pwd" size="20" >
</li>
<li class="log_btn">

<input type="submit" name="submit" value="Login" class="button">

</li>
</ul>


</form>


</div>
<?php Footer();?>

[/syntax]

This is it.

Mike Spider
Last edited by MikeSpider on Sun Oct 23, 2011 12:58 pm, edited 2 times in total.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: md5 encryption and decrypt Not working well on remote ho

Post by Apollo »

MikeSpider wrote:Thanks for all the help,

@Apollo, are you calling me mad? lol >>>
I'm telling that it DID HASH BACK!!
And I'm telling you it didn't :)

But hey, I'd be happy to be proven wrong, cause that would open all sorts of possibilities. I'm willing to bet a million dollars you can't "hash back" this password: 723bef2aca80a2cd494a930951a84881 (and this is not a random bogus checksum to fool you, it's a legit md5 hash of a real string). If you hash it back, PM me your bank account and I'll wire the money!

Anyway, looking at your code you are actually taking the md5 hash of whatever password they enter when logging in, and compare that to the md5 hash you have in your database.
So you're just comparing hashes (which is good). That's something different than "hashing back to real values". You will NOT be able to restore the real (as in original, actual) password from an md5 hash.
why dont you give it a try>> b4 saying that i must have made a mistake.
I know how md5 works. Really. Otherwise I wouldn't be putting a million dollars on the line :)

This also means your script is basically OK in the sense that you don't store any actual passwords anywhere, except you need to use a better hash (sha512 or whirlpool instead of md5) and you need to add salt & pepper (so that different users will have different hashes, even if they happen to have the same password).
MikeSpider
Forum Commoner
Posts: 25
Joined: Sat Oct 22, 2011 6:45 pm

Re: md5 encryption and decrypt Not working well on remote ho

Post by MikeSpider »

@ Apollo, Ok.

I think there was a missunderstanding about the term "hashing back".
What i meant was to use the md5 again in the login part to get the equivalent value to the hashed value stored in DB.

Thanks for the help and sorry about all missunderstanding hehehe.

I will investigate further about more secure ways of hashing.
And when you say "giving different users diferent hashes" how can I do that?
would a use of a random in an array containing different types of hashing work??

just an ideia.

@ Celauran,
No errors as I said b4 everything now is working great!

Thanks, Mike.
Post Reply