Encrypting/Decrypting Passwords to and from a MySQL database

24,545

Solution 1

Passwords should be hashed, not encrypted. That is, you should not be able to decrpyt the password. Instead, you should compare hashes.

  1. User sets password $password = 'hX4)1z'
  2. You get hash of password and store to DB:

#

$pw = hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']);
mysql_query('INSERT INTO passwords (pw) VALUES ('$pw');
  1. Customer comes back later. They put in their password, and you compare it:

#

mysql_query('SELECT pw FROM passwords WHERE user_id = ?');
//$pw = fetch

if ($pw == hash_hmac('sha512', 'salt' . $_REQUEST['password'], $_SERVER['site_key']) {

   echo "Logged in";

}

Solution 2

PHP has some built-in has functions, such as md5(). When I was learning I found IBM's primer very useful - I'd highly recommend looking at that.

As an aside, I would advise against being able to decrypt a password. The only person who should know their password is a user! This is why we store hashed versions of passwords which we can check against, rather than storing encrypted passwords which can be decrypted..

Solution 3

I notice people make huge deals about storing passwords.

Agreed you shouldn't store passwords as plain texts, but if you store the one way hash and get rid of the password, hackers can still using algorithms to hack a hash hashing strings and comparing.

Also, if you encrypt with an algorithm that you can decrypt later, that can also be hacked by figuring out the algorithm of the encryption.

I think as long as no one can see the users' passwords outright and you simply make it difficult for hackers you're good, but people say you shouldn't encrypt because it can be decrypted but that's not fair because anything can be hacked.

Solution 4

Use md5 instead

http://php.net/manual/en/function.md5.php

http://en.wikipedia.org/wiki/Md5

Solution 5

You can use md5 or better hashing technique like sha1 See password hashing http://phpsec.org/articles/2005/password-hashing.html for more details.

Share:
24,545
AKor
Author by

AKor

Updated on June 07, 2020

Comments

  • AKor
    AKor almost 4 years

    I'm starting to create a user system for my website, and what I want to do is to have the passwords encrypted, rather than plaintext. I'm using PHP/MySQL, so I figured crypt() is a good place to start. However, I'm brand new to cryptography like this, and I'm having trouble understanding exactly how it works. Does anybody know how to implement, at the simplest level, a way for passwords to be stored as an encrypted string, but always be able to be decrypted, without a security issue?