How to encrypt and decrypt password in php

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dreamy
    New Member
    • Jul 2009
    • 29

    How to encrypt and decrypt password in php

    can i ask
    how to encrypt an password in php code?
    then how to decrpty it after encrypt?

    thanks
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    To do this you need to write your own encrypting algorithm.
    The system supplied functions sha_1 and md5 are "un-decryptable".
    This all makes sense really because if there were publicly available functions that encrypted and decrypted it would make them fairly useless.

    Comment

    • unauthorized
      New Member
      • May 2009
      • 81

      #3
      The PHP's OpenSSL interface has everything you may ever want from encryption/decryption/hashing and even an awsome RNG.

      See php.net/openssl

      Comment

      • Dheeraj Joshi
        Recognized Expert Top Contributor
        • Jul 2009
        • 1129

        #4
        Basically... Do md5 on the password for encryption..

        But 50% of worlds password are "password", so doing on the frequency analysis one can guess the password.(Thoug h it require some work).

        So you better to add some salt(string of random characters 16characters or 8 characters) for password of each user.

        So now md5 the password and salt and then validate it against database.

        So even if the passwords for various users are same your salt(unique for each user) make the passwords different.(So no same patterns in the database basically).

        For validating

        Take password from user and for his username fetch the salt.
        do md5 on both of them and check against the database.

        Code:
        <?php
        
        $len = 16;
        
        $base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
        
        $max=strlen($base)-1;
        
        $activatecode='';
        
        mt_srand((double)microtime()*1000000);
        
        while (strlen($activatecode)<$len+1)
        
          $activatecode.=$base{mt_rand(0,$max)};
        
          
        
        echo $activatecode;
        
        ?>
        This is how salt look like.

        Regards
        Dheeraj Joshi

        Comment

        • Dheeraj Joshi
          Recognized Expert Top Contributor
          • Jul 2009
          • 1129

          #5
          MD5 is basically one way.

          You can encrypt but can not decrypt..(I mean to say you can not get back the actual text from the encrypted text.)

          Regards
          Dheeraj Joshi

          Comment

          • unauthorized
            New Member
            • May 2009
            • 81

            #6
            Originally posted by dheerajjoshim
            MD5 is basically one way.

            You can encrypt but can not decrypt..(I mean to say you can not get back the actual text from the encrypted text.)

            Regards
            Dheeraj Joshi
            That's called "hashing". Encryption is always reversible e.g. encrypted text can be decrypted if you have the right key(s).

            Ontopic, I would avoid md5() which is very outdated and easy to crack if I were you. If you want secure passwords, the best way would be to use some very resilient hashing algorithm (RipeMD is a great choice) with 6+ character salt. Encryption is slightly more problematic since the attacker only has to break the encryption key to access the data which means you will have to devise some method to protect the encryption keys (which is often done through hashing a password...). It's not worth all this hassle only to allow users to recover their password IMO.

            Comment

            • Dheeraj Joshi
              Recognized Expert Top Contributor
              • Jul 2009
              • 1129

              #7
              Unauthorized is right...

              MD5 is outdated...

              Go for something else.

              Regards
              Dheeraj Joshi

              Comment

              • gopan
                New Member
                • Apr 2009
                • 41

                #8
                you can use base64_encode() and base64_decode() for encrypting and later decrypting the string...

                Code:
                <?php
                $str = 'This is a top secret...';
                $enc = base64_encode($str);
                $dec = base64_decode($enc);
                
                echo "Encoded String";
                echo $enc;
                echo "Decoded String";
                echo $dec;
                ?>
                but its only 64 bit and not secure enough...

                you may use hashing algorithms like MD5 and SHA1 to make a hash of your password and store it in the db..
                later when the user enters the password... you just make the hash of the entered password and compare it with the hashed value from db with a strcmp()

                Hope this will help you....

                Comment

                • bbosh
                  New Member
                  • Aug 2009
                  • 4

                  #9
                  base64_*() are not encryption algorithms; they are encoding algorithms. They convert from one form to another (like converting binary and decimal). By "64 bits" you mean "64 characters" and "not secure enough" should be "not secure at all".

                  You should take a look at mcrypt: http://uk.php.net/manual/en/function.mcrypt-encrypt.php

                  I'm not entirely sure, but I think MD5 is a fairly secure algorithm; SHA-1 is securer, I think. I wouldn't judge its strength by its age. Although it may be susceptible to brute force attacks, simple rate limiting on a production site can eliminate this risk.

                  As for salts, this is probably easier:

                  Code:
                  $salt = md5(uniqid(mt_rand(), true), true);
                  $hashed_pass = md5 ( $pass . $salt, true);
                  -Brendon.

                  Comment

                  • dlite922
                    Recognized Expert Top Contributor
                    • Dec 2007
                    • 1586

                    #10
                    I cracked md5.

                    I have the code at home if you don't believe me.

                    It cracked a 4 letter password in half an hour. In a couple of days I could probably 5 or 6 letters.

                    I'd go with SHA-1 as a bare minimum with a good salt.



                    Dan

                    Comment

                    • unauthorized
                      New Member
                      • May 2009
                      • 81

                      #11
                      Originally posted by dlite922
                      I cracked md5.

                      I have the code at home if you don't believe me.

                      It cracked a 4 letter password in half an hour. In a couple of days I could probably 5 or 6 letters.

                      I'd go with SHA-1 as a bare minimum with a good salt.



                      Dan
                      Why bruteforce when you can just use one of the freely available rainbow tables on the net and "crack" stuff in seconds?

                      Comment

                      • bbosh
                        New Member
                        • Aug 2009
                        • 4

                        #12
                        Originally posted by dlite922
                        I cracked md5.

                        I have the code at home if you don't believe me.

                        It cracked a 4 letter password in half an hour. In a couple of days I could probably 5 or 6 letters.

                        I'd go with SHA-1 as a bare minimum with a good salt.



                        Dan
                        I suspect all 4 letter passwords are on ready-available rainbow tables, and many 5 and 6 letter passwords are probably there too. And that goes for SHA-1, as well.

                        (Edit: beat to it)

                        Comment

                        • dreamy
                          New Member
                          • Jul 2009
                          • 29

                          #13
                          if that my string in database there is already encryted,
                          and how i retrieve it out?

                          this is my ori login code without the adding any encypt

                          Code:
                          <?
                          session_start(); 
                          
                          $username= $_POST['username'];
                          $password= $_POST['password'];
                          
                          if($username && $password)
                          {
                          	$connect = mysql_connect("localhost","root","") or die ("Couldn't connect!");
                          	$select = mysql_select_db("phplogin") or die ("Couldn't find db");
                          	
                          $query = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."' ");
                          
                          $result= mysql_num_rows($query);
                          if ($result !=0)
                          {
                          	while ($row = mysql_fetch_assoc($query))
                          	{
                          		$dbusername =$row ['username'];
                          		$dbpassword = $row ['password'];
                          		
                          	}
                          	// check to see if they match
                          	if ($username = $dbusername && $password = $dbpassword)
                          	{
                          		echo"You are in! <a href ='member1.php'> Click </a> here to enter member page.";
                          		$_SESSION['username'] = $dbusername ;
                          		
                          	}
                          	else "incorrect password";
                          	
                          	
                          }
                          else die("User not exist!");
                          
                          
                          }
                          else
                          die ("Please enter username and password!");
                          ?>

                          Comment

                          • dreamy
                            New Member
                            • Jul 2009
                            • 29

                            #14
                            And this is my changing password part.
                            Can some 1 help me? thz..

                            how i log in with the changing password than i hv change, which aldy encryted.

                            thz


                            Code:
                            <? 
                            session_start();
                            
                            $user = $_SESSION['username'];
                            
                            if ($user)
                            {
                            	//user is logged in
                            	if (@$_POST['submit'])
                            	{
                            	//check fields
                            	$oldpassword = md5($_POST['oldpassword']);
                            	$newpassword = md5($_POST['newpassword']);
                            	$repeatnewpassword = md5($_POST['repeatnewpassword']);
                            	$old = md5($oldpassword);
                            	$new =md5($newpassword);
                            	$repeatnew=md5($repeatnewpassword);
                            	
                            	//check password against db
                            	
                            	//connect db
                            	$connect = mysql_connect("localhost","root","") or die ("Couldn't connect!");
                            	$select = mysql_select_db("phplogin") or die ("Couldn't find db");
                            	$queryget = mysql_query ("SELECT password FROM users WHERE username='$user'") or die("	Query didn't work");
                            	$row = mysql_fetch_assoc($queryget);
                            	
                            	$oldpassworddb =$row ['password'];
                            	
                            	//check password
                            	
                            	if($old = $oldpassworddb)
                            	{
                            	//check 2 new password
                            		echo "$old<br>";
                            	echo "$new<br>";
                            	echo "$repeatnew<br>";
                            	echo "$oldpassword<br>";
                            	echo "$newpassword<br>";
                            	echo "$repeatnewpassword<br>";
                            	if ($new == $repeatnew)
                            	{
                            		//success
                            		//change pswd in db
                            		$querychange = mysql_query ("UPDATE users SET password = '$newpassword' WHERE username='$user'");
                            		session_destroy();
                            		die ("Your password has been changed. <a href = 'index1.php'> Return </a> t main page");
                            									
                            	}
                            	else
                            	die ("New password don't match!");
                            	}
                            	else 
                            	die("Old password doesn't match");
                            	}
                            	else
                            	{
                            	echo"
                            	<form action='changepassword.php' method='POST'> 
                            	<p>Old password: <input type='text' name='oldpassword'></p>
                            	New password: <input type='text' name='newpassword'><br />
                            	<p>Repeat new password: <input type='text' name='repeatnewpassword'></p>
                            	<input type ='submit' name='submit' value='Submit'> 
                            	</form>";
                            
                            }
                            }
                            else
                            die ("You must be logged in to change your password!");
                            ?>
                            Last edited by Dormilich; Aug 20 '09, 05:59 AM. Reason: Please use [code] tags when posting code

                            Comment

                            • Dheeraj Joshi
                              Recognized Expert Top Contributor
                              • Jul 2009
                              • 1129

                              #15
                              What i would have done is,

                              When user sign up for the firs time i will give a unique character string to user(salt) and store it in db... when he gives password. i will do md5 or something else for password and salt and store it in db.

                              On next login check user name then fetch salt and fetch encrypted password from db.
                              Now take password from form do md5 or something on password and salt.. so the resultant encrypted string will be same as encrypted password from db


                              Note: This is an idea, there may be some security issues you need o consider.

                              Regards
                              Dheeraj Joshi

                              Comment

                              Working...