Skip to content

Out of the Stone Age: Crypt for password storage

The stone age in the Web 2.0 era really is anything more than 6 months old. While going through the Yii blog tutorial, I was caught off guard reading the following line of code (names changed for clarity):

if ($passwordHash === crypt($password, $passwordHash))...}

My last foray into passwords relied on comparing 32 character md5 hashes using:


After a quick look at the php manual on crypt, I found it a little odd that the hash of the password was both (a) the salt used for the password, but then also (b) the resulting output of the hash! Why does this work? As discussed here, the return value of crypt is the string concatenation of the salt value and the hashed string.┬áThis concatenated value can then be stored in the database, without compromising password integrity. The benefit of a salted hash of course, is the added complexity of cracking the password. These days there are md5 hash dictionaries online that you can quickly lookup the value of any md5 hashed string. A dictionary attack for these salted hashes are probably few and far between. A password hacker would have to rely on brute force methods to crack a password… And this would only provide them with one password, since each password relies on a different salt..

crypt('EgzamplPassword', '<strong>$2a$10$1qAz2wSx3eDc4rFv5tGb5t</strong>')
    >> '<strong>$2a$10$1qAz2wSx3eDc4rFv5t</strong>Gb5e4jVuld5/KF2Kpy.B8D2XoC031sReFGi'
crypt('EgzamplPassword', '<strong>$2a$10$1qAz2wSx3eDc4rFv5t</strong>Gb5tGb5e4jVuld5/KF2Kpy.B8D2XoC031sReFGi')
    >> '<strong>$2a$10$1qAz2wSx3eDc4rFv5t</strong>Gb5e4jVuld5/KF2Kpy.B8D2XoC031sReFGi'

If you look at the output of the crypt function, the inputed salt is included in the output. Since crypt ignores the excess characters in the salt string, using crypt to store and compare password values is pretty sweet. If you are having problems with crypt (or any function for that matter), always remember to RTM (Read the Manual). If the output for crypt() is less than 13 characters, you have an error. It could be a bad salt or an unsupported php/hash library. Make sure you are running php 5.3.0 or newer and use a hash salt generator.

Posted in PHP. Tagged with , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK


(required, but never shared)

or, reply to this post via trackback.