SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    Level 8 Chinese guy Archbob's Avatar
    Join Date
    Sep 2001
    Location
    Somewhere in this vast universe
    Posts
    3,741
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP password Encryption

    I was wondering how to encrypt passwords better with PHP. Up til now, I used MD5 and SHA1 but both now have online decryptors that work fast. Is there a better function?

  2. #2
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,272
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    The way those decrypters work is by amassing a large database of strings along with the hash value of those strings. So they're not "decrypting" in the traditional sense, but rather just looking up the hash in a dictionary of precomputed hashes. Every hash algorithm is vulnerable to this kind of exploit, so no matter which algorithm you use, it's standard practice to add random data to the string before you hash it. We call that technique "salting the hash." The databases of precomputed hashes can't actually store every possible hash -- there are more than 10^38 of them -- so instead they store only the hashes of common passwords. By adding random data to each password before we hash it, we ensure that the hash we get back won't be in one of those databases.

    However, even though neither MD5 nor SHA1 are specially vulnerable to this trick, that doesn't mean you shouldn't still use a better algorithm. The most popular choice at the moment is SHA-256.

    There are other standard tricks we can do, such as hashing the string repeatedly, perhaps 1000 times, in order to make it take longer to compute the hash. That makes it harder for an attacker to guess the password, because every guess would take 1000x more compute time.

    Doing all this correctly may be more hassle than you want to deal with, so you may want to let a library do the work for you. I've seen many smart people here recommend phpass, and it's certainly worth checking out. Although, personally, I'm underwhelmed by the code quality in that library.

    Otherwise, you could do this:

    PHP Code:
    $salt uniqid(mt_rand(), true);
    $hashedPassword hash_pbkdf2('sha256'$password$salt1000); 
    You'll need to store both the hash and the salt in your database.
    "First make it work. Then make it better."


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •