473,327 Members | 2,090 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 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 39920
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 "JOHN" with these asymetrics keys. With the...
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 provided by the user ? ...
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 application. At first, I tought I was going to store...
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 enybody tell how to do this ?
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 database linked, i assumed that the database has been...
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 right) and the number of places to shift (should they...
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 installer, allowing a user to install it and then...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.