Search code examples
phpmysqlencryption

Encrypting/Decrypting Passwords to and from a MySQL database


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?


Solution

  • 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";
    
    }