Lodhart
Lodhart

Reputation: 225

PHP how to secure password in database

I'm using data from another server (not my server) and I need to login to this server. So I need to know password for every user account. I need to send this password to the server through HTTP request (no problem). But the server expect unsecure password.

So if the password is '123456' I have to send POST request with data:

"username=user&password=123456"

I can not use md5 function because after it I am not able to get back the password so my question is how can I encode this password? Is exists some common PHP function for this? For example:

$securePassword = php_encode("123456", "mykey")
php_decode($securePassword, "mykey")

Because I just do not want to store to my database "123456"

Upvotes: 0

Views: 447

Answers (6)

user399666
user399666

Reputation: 19879

If you have PHP >5.5, you can use the function password_hash. If you have a lower version that is bigger than PHP 5.3.7, you should use password compat.

Upvotes: 1

azz
azz

Reputation: 5930

There is a reason passwords are hashed instead of encrypted. You cannot decrypt a hash. Generally the convention is to do the following:

Create Password

  1. Send the new password to the server
  2. Hash the password
  3. Store the hash in the database

Check Password

  1. Send the password to the server
  2. Hash the password
  3. Check if the hash matches the hash stored in the database

For this you should use something like SHA256:

// check password
$hash = hash('sha256', $password);
$db_hash = db_get_password($username, ...);
if ($hash == $db_hash) { 
    // correct password
}

Upvotes: 0

woz
woz

Reputation: 10994

The point of a hash is that you can't un-encrypt it. To check if someone entered a correct password, hash what they typed in and compare it to the hash of their password in the database. If it matches, the password is right; otherwise, it's wrong. Also, as long as you use SSL and a decent hash algorithm, you should be secure.

Upvotes: 1

pratim_b
pratim_b

Reputation: 1190

Use mcrypt_encrypt() and mcrypt_decrypt()
for more info SO POST

Upvotes: 1

Scott Helme
Scott Helme

Reputation: 4799

What you are looking for is not how to secure the password but how to secure the transport of the password. You do this using Transport Layer Security, aka TLS aka SSL.

That said, transmitting a password in this fashion isn't really advised and a better mechanism should probably be devised. If you encrypt or hash the password and transmit the cipher text this offers no protection at all because an attacker would simply send cipher text just as you would.

You need to encrypt the data in transit. Get SSL setup on your site.

Upvotes: 0

Related Questions