Viewed   83 times

I am creating an application that will store passwords, which the user can retrieve and see. The passwords are for a hardware device, so checking against hashes are out of the question.

What I need to know is:

  1. How do I encrypt and decrypt a password in PHP?

  2. What is the safest algorithm to encrypt the passwords with?

  3. Where do I store the private key?

  4. Instead of storing the private key, is it a good idea to require users to enter the private key any time they need a password decrypted? (Users of this application can be trusted)

  5. In what ways can the password be stolen and decrypted? What do I need to be aware of?

 Answers

4

Personally, I would use mcrypt like others posted. But there is much more to note...

  1. How do I encrypt and decrypt a password in PHP?

    See below for a strong class that takes care of everything for you:

  2. What is the safest algorithm to encrypt the passwords with?

    safest? any of them. The safest method if you're going to encrypt is to protect against information disclosure vulnerabilities (XSS, remote inclusion, etc). If it gets out, the attacker can eventually crack the encryption (no encryption is 100% un-reversible without the key - As @NullUserException points out this is not entirely true. There are some encryption schemes that are impossible to crack such as OneTimePad).

  3. Where do I store the private key?

    What I would do is use 3 keys. One is user supplied, one is application specific and the other is user specific (like a salt). The application specific key can be stored anywhere (in a config file outside of the web-root, in an environmental variable, etc). The user specific one would be stored in a column in the db next to the encrypted password. The user supplied one would not be stored. Then, you'd do something like this:

    $key = $userKey . $serverKey . $userSuppliedKey;
    

    The benefit there, is that any 2 of the keys can be compromised without the data being compromised. If there's a SQL Injection attack, they can get the $userKey, but not the other 2. If there's a local server exploit, they can get $userKey and $serverKey, but not the third $userSuppliedKey. If they go beat the user with a wrench, they can get the $userSuppliedKey, but not the other 2 (but then again, if the user is beaten with a wrench, you're too late anyway).

  4. Instead of storing the private key, is it a good idea to require users to enter the private key any time they need a password decrypted? (Users of this application can be trusted)

    Absolutely. In fact, that's the only way I would do it. Otherwise you'd need to store an unencrypted version in a durable storage format (shared memory such as APC or memcached, or in a session file). That's exposing yourself to additional compromises. Never store the unencrypted version of the password in anything except a local variable.

  5. In what ways can the password be stolen and decrypted? What do I need to be aware of?

    Any form of compromise of your systems will let them view encrypted data. If they can inject code or get to your filesystem, they can view decrypted data (since they can edit the files that decrypt the data). Any form of Replay or MITM attack will also give them full access to the keys involved. Sniffing the raw HTTP traffic will also give them the keys.

    Use SSL for all traffic. And make sure nothing on the server has any kind of vulnerabilities (CSRF, XSS, SQL Injection, Privilege Escalation, Remote Code Execution, etc).

Edit: Here's a PHP class implementation of a strong encryption method:

/**
 * A class to handle secure encryption and decryption of arbitrary data
 *
 * Note that this is not just straight encryption.  It also has a few other
 *  features in it to make the encrypted data far more secure.  Note that any
 *  other implementations used to decrypt data will have to do the same exact
 *  operations.  
 *
 * Security Benefits:
 *
 * - Uses Key stretching
 * - Hides the Initialization Vector
 * - Does HMAC verification of source data
 *
 */
class Encryption {

    /**
     * @var string $cipher The mcrypt cipher to use for this instance
     */
    protected $cipher = '';

    /**
     * @var int $mode The mcrypt cipher mode to use
     */
    protected $mode = '';

    /**
     * @var int $rounds The number of rounds to feed into PBKDF2 for key generation
     */
    protected $rounds = 100;

    /**
     * Constructor!
     *
     * @param string $cipher The MCRYPT_* cypher to use for this instance
     * @param int    $mode   The MCRYPT_MODE_* mode to use for this instance
     * @param int    $rounds The number of PBKDF2 rounds to do on the key
     */
    public function __construct($cipher, $mode, $rounds = 100) {
        $this->cipher = $cipher;
        $this->mode = $mode;
        $this->rounds = (int) $rounds;
    }

    /**
     * Decrypt the data with the provided key
     *
     * @param string $data The encrypted datat to decrypt
     * @param string $key  The key to use for decryption
     * 
     * @returns string|false The returned string if decryption is successful
     *                           false if it is not
     */
    public function decrypt($data, $key) {
        $salt = substr($data, 0, 128);
        $enc = substr($data, 128, -64);
        $mac = substr($data, -64);

        list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key);

        if (!hash_equals(hash_hmac('sha512', $enc, $macKey, true), $mac)) {
             return false;
        }

        $dec = mcrypt_decrypt($this->cipher, $cipherKey, $enc, $this->mode, $iv);

        $data = $this->unpad($dec);

        return $data;
    }

    /**
     * Encrypt the supplied data using the supplied key
     * 
     * @param string $data The data to encrypt
     * @param string $key  The key to encrypt with
     *
     * @returns string The encrypted data
     */
    public function encrypt($data, $key) {
        $salt = mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);
        list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key);

        $data = $this->pad($data);

        $enc = mcrypt_encrypt($this->cipher, $cipherKey, $data, $this->mode, $iv);

        $mac = hash_hmac('sha512', $enc, $macKey, true);
        return $salt . $enc . $mac;
    }

    /**
     * Generates a set of keys given a random salt and a master key
     *
     * @param string $salt A random string to change the keys each encryption
     * @param string $key  The supplied key to encrypt with
     *
     * @returns array An array of keys (a cipher key, a mac key, and a IV)
     */
    protected function getKeys($salt, $key) {
        $ivSize = mcrypt_get_iv_size($this->cipher, $this->mode);
        $keySize = mcrypt_get_key_size($this->cipher, $this->mode);
        $length = 2 * $keySize + $ivSize;

        $key = $this->pbkdf2('sha512', $key, $salt, $this->rounds, $length);

        $cipherKey = substr($key, 0, $keySize);
        $macKey = substr($key, $keySize, $keySize);
        $iv = substr($key, 2 * $keySize);
        return array($cipherKey, $macKey, $iv);
    }

    /**
     * Stretch the key using the PBKDF2 algorithm
     *
     * @see http://en.wikipedia.org/wiki/PBKDF2
     *
     * @param string $algo   The algorithm to use
     * @param string $key    The key to stretch
     * @param string $salt   A random salt
     * @param int    $rounds The number of rounds to derive
     * @param int    $length The length of the output key
     *
     * @returns string The derived key.
     */
    protected function pbkdf2($algo, $key, $salt, $rounds, $length) {
        $size   = strlen(hash($algo, '', true));
        $len    = ceil($length / $size);
        $result = '';
        for ($i = 1; $i <= $len; $i++) {
            $tmp = hash_hmac($algo, $salt . pack('N', $i), $key, true);
            $res = $tmp;
            for ($j = 1; $j < $rounds; $j++) {
                 $tmp  = hash_hmac($algo, $tmp, $key, true);
                 $res ^= $tmp;
            }
            $result .= $res;
        }
        return substr($result, 0, $length);
    }

    protected function pad($data) {
        $length = mcrypt_get_block_size($this->cipher, $this->mode);
        $padAmount = $length - strlen($data) % $length;
        if ($padAmount == 0) {
            $padAmount = $length;
        }
        return $data . str_repeat(chr($padAmount), $padAmount);
    }

    protected function unpad($data) {
        $length = mcrypt_get_block_size($this->cipher, $this->mode);
        $last = ord($data[strlen($data) - 1]);
        if ($last > $length) return false;
        if (substr($data, -1 * $last) !== str_repeat(chr($last), $last)) {
            return false;
        }
        return substr($data, 0, -1 * $last);
    }
}

Note that I'm using a function added in PHP 5.6: hash_equals. If you're on lower than 5.6, you can use this substitute function which implements a timing-safe comparison function using double HMAC verification:

function hash_equals($a, $b) {
    $key = mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);
    return hash_hmac('sha512', $a, $key) === hash_hmac('sha512', $b, $key);
}

Usage:

$e = new Encryption(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$encryptedData = $e->encrypt($data, $key);

Then, to decrypt:

$e2 = new Encryption(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$data = $e2->decrypt($encryptedData, $key);

Note that I used $e2 the second time to show you different instances will still properly decrypt the data.

Now, how does it work/why use it over another solution:

  1. Keys

    • The keys are not directly used. Instead, the key is stretched by a standard PBKDF2 derivation.

    • The key used for encryption is unique for every encrypted block of text. The supplied key therefore becomes a "master key". This class therefore provides key rotation for cipher and auth keys.

    • IMPORTANT NOTE, the $rounds parameter is configured for true random keys of sufficient strength (128 bits of Cryptographically Secure random at a minimum). If you are going to use a password, or non-random key (or less random then 128 bits of CS random), you must increase this parameter. I would suggest a minimum of 10000 for passwords (the more you can afford, the better, but it will add to the runtime)...

  2. Data Integrity

    • The updated version uses ENCRYPT-THEN-MAC, which is a far better method for ensuring the authenticity of the encrypted data.
  3. Encryption:

    • It uses mcrypt to actually perform the encryption. I would suggest using either MCRYPT_BLOWFISH or MCRYPT_RIJNDAEL_128 cyphers and MCRYPT_MODE_CBC for the mode. It's strong enough, and still fairly fast (an encryption and decryption cycle takes about 1/2 second on my machine).

Now, as to point 3 from the first list, what that would give you is a function like this:

function makeKey($userKey, $serverKey, $userSuppliedKey) {
    $key = hash_hmac('sha512', $userKey, $serverKey);
    $key = hash_hmac('sha512', $key, $userSuppliedKey);
    return $key;
}

You could stretch it in the makeKey() function, but since it's going to be stretched later, there's not really a huge point to doing so.

As far as the storage size, it depends on the plain text. Blowfish uses a 8 byte block size, so you'll have:

  • 16 bytes for the salt
  • 64 bytes for the hmac
  • data length
  • Padding so that data length % 8 == 0

So for a 16 character data source, there will be 16 characters of data to be encrypted. So that means the actual encrypted data size is 16 bytes due to padding. Then add the 16 bytes for the salt and 64 bytes for the hmac and the total stored size is 96 bytes. So there's at best a 80 character overhead, and at worst a 87 character overhead...

I hope that helps...

Note: 12/11/12: I just updated this class with a MUCH better encryption method, using better derived keys, and fixing the MAC generation...

Sunday, November 27, 2022
2

First question about bcrypt and salt: salt is contained inside the result string as well as the cost, along with the hashed string. Each of three strings has constant length and thus can be retrieved easily thereafter.

For a more thorough explanation, see this answer.


scrypt is a newer version of bcrypt that requires more RAM to operate. The reason behind the RAM requirements is that CPU cycle based encryption (I/O based) is easily brute-forced using a modern GPU, multiple cores, etc. RAM on the other side is not so easy to scale, so a combination of increased RAM + multiple operations is theoretically a safer way.

Read more about this in this great answer.

Wednesday, August 10, 2022
 
klimat
 
1

You should store passwords hashed (and properly salted).

There is no excuse in the world that is good enough to break this rule.

Currently, using crypt, with CRYPT_BLOWFISH is the best practice.
CRYPT_BLOWFISH in PHP is an implementation of the Bcrypt hash. Bcrypt is based on the Blowfish block cipher.

  • If your client tries to login, you hash the entered password and compare it to the hash stored in the DB. if they match, access is granted.

  • If your client wants to change the password, they will need to do it trough some little script, that properly hashes the new password and stores it into the DB.

  • If your client wants to recover a password, a new random password should be generated and send to your client. The hash of the new password is stored in the DB

  • If your clients want to look up the current password, they are out of luck. And that is exactly the point of hashing password: the system does not know the password, so it can never be 'looked up'/stolen.

Jeff blogged about it: You're Probably Storing Passwords Incorrectly

If you want to use a standard library, you could take a look at: Portable PHP password hashing framework and make sure you use the CRYPT_BLOWFISH algorithm.

(Generally speaking, messing around with the records in your database directly is asking for trouble.
Many people -including very experienced DB administrators- have found that out the hard way.)

Friday, September 2, 2022
 
5

First you create a salt.

Note examples are written in PHP

// Setup a salt, this isn't "random" but it doesn't really have to be
$salt = sha1(microtime());

Then salt the password

// First we hash the password, then XOR it with the salt hashing the result
$hash = sha1(sha1($password) ^ $salt);

Store the $hash and $salt in the database.

When the user enters a password compare it to the hash

if(sha1(sha1($entered_password) ^ $salt) == $hash)
    // Correct password

Never store passwords in a reversible format. Also I would advise against using MD5 as a hash.

Edit: Other than passwords, in a user system, what else should be encrypted as a good practice? Do they encrypt usernames or anything else?

Passwords aren't encrypted, they are hashed. Picture a hash (very simplistic) as something that takes a number and multiplies it by ten. Say I want to hash the number 30. I would say 30*10 and get 300 as my "hash" for 30. Note that you cannot derive 30 from 300 without knowing how the hash function works.

That's a very simplistic "hash" and if you know it always multiplies by ten then you could easily reverse it. Now take a look at the SHA1 hash function. It's much more complicated. It can't simply be reversed.

You will find that rarely is anything except the password hashed, and nothing is encrypted. The amount of overhead you would have with encrypting your database would be enormous.

I suppose you could apply a similar salt / hash pattern to the username, but then you have pitfalls. What if you want to use that username somewhere in your code? What if you want to check to make sure it's unique to the table?

2nd Edit: What is a one-way hash? I mean, technically, can I not reverse engineer my source code? Maybe this is a bad question because I do not know much about one-way hashing.

See above (or click here). A one way hash is just that. One way mapping. A => B and nothing else. B !=> A, and A can't be anything except B.

Someone mentioned the performance of an XOR operation. While I feel performance is largely negligible I ran a quick test.

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

Now run

$start_time = $this->microtime_float();

for($i = 0; $i < 100000; $i++)
{
 $sha = sha1(sha1(microtime()) . sha1(microtime()));
}

$end_time = $this->microtime_float();

echo "1000 in " . ($end_time-$start_time) . " for CATn";


$start_time = $this->microtime_float();

for($i = 0; $i < 100000; $i++)
{
 $sha = sha1(sha1(microtime()) ^ sha1(microtime()));
}

$end_time = $this->microtime_float();

echo "1000 in " . ($end_time-$start_time) . " for XORn";

Repeat as much as you want. The initial writeup uses the error log and I got the following results:

1000 in 0.468002796173 XOR
1000 in 0.465842008591 XOR
1000 in 0.466115951538 XOR
1000 in 0.498080968857 CAT
1000 in 0.506876945496 CAT
1000 in 0.500174045563 CAT
Monday, October 10, 2022
1

Encryption (or encoder) schemes try to hide your code as an encrypted file. Obviously, the code has to be decrypted at execution time, which adds useless overhead. Some of these also insist that the host system install special routines, which the hosters intensely dislike, because they don't want to set up special configurations just for you. But the bad part is that they contain the seeds of their own undoing: to run on the target host, they must contain the decryption software. So if you use one, you deliver the very decryptor necessary to get at your code. Its only a matter of locating it; once found, your code is completely decryptable and exposed. These simply aren't safe.

Obfuscation schemes scramble the names of identifiers, remove comments and formatting. But the obfuscated code runs exactly like the original, with no overhead and no special runtime support needed. Obfuscators depend on the inherent difficulty in understanding programs in general. Programs are hard enough to understand when they are well designed, names are well chosen, and there are good comments in the code. We all hope our programs are well designed, but if the names are bad and the comments are gone, they're pretty hard to understand. Examine your own experience with other people's code.

People will say, "but anybody can inspect obfuscated code and understand it". That's true if you have a tiny application. If your application has any scale (tens of pages of code) it is extremely hard to understand what it is doing when all the variable names are scrambled. The bigger your code, the better obfuscation is at protecting it.

If you want to see examples of what one PHP obfuscator does, see our Thicket PHP Obfuscator.

Friday, December 16, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :