472,328 Members | 1,629 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,328 software developers and data experts.

How to encrypt and decrypt password in php

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

thanks
Aug 17 '09 #1
19 39763
code green
1,726 Expert 1GB
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.
Aug 17 '09 #2
The PHP's OpenSSL interface has everything you may ever want from encryption/decryption/hashing and even an awsome RNG.

See php.net/openssl
Aug 17 '09 #3
Dheeraj Joshi
1,123 Expert 1GB
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.(Though 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.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. $len = 16;
  4.  
  5. $base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
  6.  
  7. $max=strlen($base)-1;
  8.  
  9. $activatecode='';
  10.  
  11. mt_srand((double)microtime()*1000000);
  12.  
  13. while (strlen($activatecode)<$len+1)
  14.  
  15.   $activatecode.=$base{mt_rand(0,$max)};
  16.  
  17.  
  18.  
  19. echo $activatecode;
  20.  
  21. ?>
  22.  
This is how salt look like.

Regards
Dheeraj Joshi
Aug 17 '09 #4
Dheeraj Joshi
1,123 Expert 1GB
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
Aug 17 '09 #5
@dheerajjoshim
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.
Aug 17 '09 #6
Dheeraj Joshi
1,123 Expert 1GB
Unauthorized is right...

MD5 is outdated...

Go for something else.

Regards
Dheeraj Joshi
Aug 17 '09 #7
gopan
41
you can use base64_encode() and base64_decode() for encrypting and later decrypting the string...

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $str = 'This is a top secret...';
  3. $enc = base64_encode($str);
  4. $dec = base64_decode($enc);
  5.  
  6. echo "Encoded String";
  7. echo $enc;
  8. echo "Decoded String";
  9. echo $dec;
  10. ?>
  11.  
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....
Aug 17 '09 #8
bbosh
4
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:

Expand|Select|Wrap|Line Numbers
  1. $salt = md5(uniqid(mt_rand(), true), true);
  2. $hashed_pass = md5 ( $pass . $salt, true);
  3.  
-Brendon.
Aug 19 '09 #9
dlite922
1,584 Expert 1GB
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
Aug 19 '09 #10
@dlite922
Why bruteforce when you can just use one of the freely available rainbow tables on the net and "crack" stuff in seconds?
Aug 19 '09 #11
bbosh
4
@dlite922
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)
Aug 19 '09 #12
dreamy
29
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

Expand|Select|Wrap|Line Numbers
  1. <?
  2. session_start(); 
  3.  
  4. $username= $_POST['username'];
  5. $password= $_POST['password'];
  6.  
  7. if($username && $password)
  8. {
  9.     $connect = mysql_connect("localhost","root","") or die ("Couldn't connect!");
  10.     $select = mysql_select_db("phplogin") or die ("Couldn't find db");
  11.  
  12. $query = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."' ");
  13.  
  14. $result= mysql_num_rows($query);
  15. if ($result !=0)
  16. {
  17.     while ($row = mysql_fetch_assoc($query))
  18.     {
  19.         $dbusername =$row ['username'];
  20.         $dbpassword = $row ['password'];
  21.  
  22.     }
  23.     // check to see if they match
  24.     if ($username = $dbusername && $password = $dbpassword)
  25.     {
  26.         echo"You are in! <a href ='member1.php'> Click </a> here to enter member page.";
  27.         $_SESSION['username'] = $dbusername ;
  28.  
  29.     }
  30.     else "incorrect password";
  31.  
  32.  
  33. }
  34. else die("User not exist!");
  35.  
  36.  
  37. }
  38. else
  39. die ("Please enter username and password!");
  40. ?>
Aug 20 '09 #13
dreamy
29
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


Expand|Select|Wrap|Line Numbers
  1. <? 
  2. session_start();
  3.  
  4. $user = $_SESSION['username'];
  5.  
  6. if ($user)
  7. {
  8.     //user is logged in
  9.     if (@$_POST['submit'])
  10.     {
  11.     //check fields
  12.     $oldpassword = md5($_POST['oldpassword']);
  13.     $newpassword = md5($_POST['newpassword']);
  14.     $repeatnewpassword = md5($_POST['repeatnewpassword']);
  15.     $old = md5($oldpassword);
  16.     $new =md5($newpassword);
  17.     $repeatnew=md5($repeatnewpassword);
  18.  
  19.     //check password against db
  20.  
  21.     //connect db
  22.     $connect = mysql_connect("localhost","root","") or die ("Couldn't connect!");
  23.     $select = mysql_select_db("phplogin") or die ("Couldn't find db");
  24.     $queryget = mysql_query ("SELECT password FROM users WHERE username='$user'") or die("    Query didn't work");
  25.     $row = mysql_fetch_assoc($queryget);
  26.  
  27.     $oldpassworddb =$row ['password'];
  28.  
  29.     //check password
  30.  
  31.     if($old = $oldpassworddb)
  32.     {
  33.     //check 2 new password
  34.         echo "$old<br>";
  35.     echo "$new<br>";
  36.     echo "$repeatnew<br>";
  37.     echo "$oldpassword<br>";
  38.     echo "$newpassword<br>";
  39.     echo "$repeatnewpassword<br>";
  40.     if ($new == $repeatnew)
  41.     {
  42.         //success
  43.         //change pswd in db
  44.         $querychange = mysql_query ("UPDATE users SET password = '$newpassword' WHERE username='$user'");
  45.         session_destroy();
  46.         die ("Your password has been changed. <a href = 'index1.php'> Return </a> t main page");
  47.  
  48.     }
  49.     else
  50.     die ("New password don't match!");
  51.     }
  52.     else 
  53.     die("Old password doesn't match");
  54.     }
  55.     else
  56.     {
  57.     echo"
  58.     <form action='changepassword.php' method='POST'> 
  59.     <p>Old password: <input type='text' name='oldpassword'></p>
  60.     New password: <input type='text' name='newpassword'><br />
  61.     <p>Repeat new password: <input type='text' name='repeatnewpassword'></p>
  62.     <input type ='submit' name='submit' value='Submit'> 
  63.     </form>";
  64.  
  65. }
  66. }
  67. else
  68. die ("You must be logged in to change your password!");
  69. ?>
Aug 20 '09 #14
Dheeraj Joshi
1,123 Expert 1GB
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
Aug 20 '09 #15
Dheeraj Joshi
1,123 Expert 1GB
And please use code tags..

Regards
Dheeraj Joshi
Aug 20 '09 #16
bbosh
4
Your current script is a bit over-complicated and is wrong (you are using = assignment rather than ==, === or, even better, strcmp). And your script is open to SQL injection. Here's something I have used before, adapted:

Expand|Select|Wrap|Line Numbers
  1. session_start();
  2.  
  3. $username = isset($_POST['username']) ? $_POST['username'] : NULL;
  4. $password = isset($_POST['password'])  ? $_POST['password']  : NULL;
  5.  
  6. $sql = "SELECT salt, pass_hash FROM users WHERE username = '%s'";
  7. $sql = sprintf( $sql, mysql_real_escape_string($username) );
  8.  
  9. $result = mysql_query( $sql );
  10.  
  11. if (!mysql_num_rows($result)) {
  12.     /* incorrect username */
  13. } else {
  14.     $row = mysql_fetch_row($result);
  15.     $pass_hash = pack( "H*", md5($password . $row[0]) );
  16.     if ( strcmp($pass_hash, $row[1]) === 0 ) {
  17.         $_SESSION['username'] = $username;
  18.         header("Location: account.php");
  19.         exit;
  20.     } else {
  21.         /* Incorrect password */
  22.     }
  23. }
  24.  
  25.  
Aug 20 '09 #17
dreamy
29
ok thanks,
but there is an error
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource,
can i know how to fixed it.thx
Aug 20 '09 #18
dreamy
29
is that the pass_hash, salt as a field in database?

And strcmp is for?

Thz

but why that any user which not in database also can login?
Aug 20 '09 #19
bbosh
4
@dreamy
There is probably a mysql error (echo mysql_error() to see), probably due to those fields missing

@dreamy
Yes, `pass_hash` and `salt` are BINARY(16) fields in the database.pass_salt is the result of

Expand|Select|Wrap|Line Numbers
  1.  $pass_salt = md5 ( $pass . $salt, true ); 
$salt could be, for example:

Expand|Select|Wrap|Line Numbers
  1. $salt = md5(uniqid(mt_rand(), true), true);
strcmp is binary-safe string comparison: it returns 0 if they match (see php.net). We need this because values may be mis-represented in a normal string comparison (I think/am sure).
Aug 20 '09 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Benoît | last post by:
Hi, I have generated two keys : "C:>openssl req -nodes -new -x509 -keyout ben.key -out ben.crt -days 3650" I try to encrypt/decrypt a string like...
0
by: Aaron | last post by:
Is the native Encrypt/Decrypt functionality with .NET PGP compatible?
4
by: Hrvoje Voda | last post by:
Does anyone knows a good example of how to encrypt/decrypt a string? Hrcko
3
by: Alex Nitulescu | last post by:
Hi. I am writing an app which stores usernames/passwords and email addresses in a database table. The question is how can I encrypt the password...
7
by: Jean Christophe Avard | last post by:
Hi! I am designing an application wich comes with image file. These images are copyrighted and they have to be accessible only from within the...
6
by: Ripendra007 | last post by:
hi,everyone i m creating a login page and i want to encrypt the password before insert that in to database and decrypt it before verification can...
3
Paul NIcolai Sunga
by: Paul NIcolai Sunga | last post by:
.i need your help guys,. thanks, i just want to know how to encrypt the password that have been submit to the database. /* $lik refers to the...
2
bferguson94
by: bferguson94 | last post by:
Design a program that allows the user to encrypt or decrypt a file. This means you will need to ask the user the direction to shift (left or...
2
by: Rich Howard | last post by:
I'm working on an application that works as a remote client for integrating with corporate services. It's packaged as a downloadable Windows...
0
by: tammygombez | last post by:
Hey fellow JavaFX developers, I'm currently working on a project that involves using a ComboBox in JavaFX, and I've run into a bit of an issue....
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.