User Contributed Notes 31 notes

The suggestion below to double-hash your password is not a good idea. You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).

Double hashing is *worse* security than a regular hash. What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant. You have not increased security at all.

Thanks for the feedback. This should do the trick, I hope.I think that I haven't understood this sentence completely "In this case you will need the salt to reside in the database along with the username and password." As in, were you refering to previous method, this method or this function.Salt already resides in database along with username, password, or any string you decide to hash. This function just scrambles it depending on length of string (password) user enters so that attacker has trouble finding out what is salt and what is hash, if attacker even suspects that there is salt (reasons behind $keepLength, or defining $hSLength where you could set it to 24 leading attacker to believe he's facing sha256, not sha1).

check out these randomized sha1 password storage functions, they output a string of 50 characters, the first 40 characters being a sha1 output based on the last 10 characters - those being a random seed

to encode a password run pw_encode with the password, it'll return a different pseudo-random string every time - store this value.

to check a password run pw_check with the password attempt and the stored value, it'll return true on a match and false otherwise

these functions eliminate the pesky problem of dictionary matches being run on your password lists

I've noticed websites are now starting to require passwords of a certain length that MUST contain at least 1 non-alphanumeric character. This in itself makes dictionary attacks kind of useless. My web site requires that as well. It uses md5, and appends a site code into the md5 as well. And the include file that contains that site key is outside the public folders. I sure hope I've done enough to keep the bad boys out.

It is very useful for client-authentication. see also http://cookies.lcs.mit.edu/pubs/webauth:tr.pdfOptionally you can change $hashfunc to 'md5' to make this an HMAC-MD5 function ;-)If you want raw or base64 output instead of hexadecimal, just change the last return line.

Cheers,Mark

p.s. the "$hmac =" line used to be 1 line but I had to cut it up in order to fit it here ;)

I've been getting few requests to explain how it's used so, this might be little long.

Problems:1. In most solutions with hash and salt, you were bound to have one extra row in your database that would state, preferably random, salt for that hashed data. If attacker would manage to get drop of your database he would get hashed data and salt that is used with plain data to make it obscure, and then cracking that hashed data would be same as if you didn't add any salt to it.2. I stumbled upon some functions that would hash data, then input salt into random places in hash and store it in database, but they would still have to write down random parameter used to scramble salt so they could reuse it when validating data. Getting simple database drop wouldn't help much here, but if they would manage to get their hands on obscuring function too, they could easily see what is salt and what hash.

Solutions:1. Why use extra row to store salt when you can input it in hash. I'm not sure how attackers determine what type of hash are they facing, but I guess it has connection to hash length. In that case, why make attackers job easier and store in database data_hash+salt where they could assume just by it's length it has salt in there.Reason behind $keepLength. If it's set to 1, strlen of hashed data plus salt would be equal to strlen of hashed data leading attacker to believe there is no salt.If you leave $keepLength on NULL, strlen of final result would be strlen(used_hash_algorithm)+$hSLength.$minhPass is there to reserve enough place for string that has to be hashed, so someone using this function wouldn't accidentally delete it by setting too high salt length ($hSLength), for example... if you set it 30000 it will keep working normal.

2. If you think about it, constant, but variable value when making input would be same data that is being input.In case we're trying to hash password, and have user A with password "notme", password strlen equals to 5, and if we use default parameters of the function, with $keepLength set to 1, process would be:random salt, hash it, add first 5 characters of hashed_salt at beginning of plain password, add last 5 characters of hashed_salt at end of plain password, hash it. Replace first 5 characters of hashed_password with first 5 character of hashed_salt, do same with last 5 characters of hashed_password, return hashed_password.In case that string is longer than 10 characters function would use simple mathematics to reduce it to numbers lower than 10, well... lower than number that is stated in $hSLength.And good thing is that every time user enters correct password it has same length so it's not necessary to write it anywhere.

So what is achieved in the end?1. Attacker might not know that hash is salted, and you don't have that extra row in your database stating THIS IS SALT FOR THIS HASH.2. If he does find out that it is, he wouldn't know what is hashed password and what is salt.3. If he manages to get access to obscure function, only thing that might help him is value of $hSLength, where if $hSLength is set to 10 he would have to crack 10 variations of hashed string since he doesn't know how long password of user he's trying to crack is.For example first variation would be hashed_password without last 10 characters, second variation would be hashed_password without first character and last 9 characters...4. Even in case he has enough power to crack all 10 variations, resulting string that he might get doesn't necessarily has to be exactly long as password of original user in which case, attacker fails again.

Another solution to the salted hash with salt included directly in the hash, while keeping the same length of the result. If you want to generate a hash, call the function without the second argument. If you want to check a password against a hash, use the hash as the second argument. In this case, the function returns the hash itself on success, or boolean false on failure. You can also specify a hash algorithm as the third argument (otherwise SHA-1 will be used).

It uses a random, variable length salt, depending on the length of the password. The functions __scramble() and __harvest() are used to place salt into the hash or pull it out respectively. You can write your own, and of course the strength of the result greatly depends on them. They can be relatively simple yet still quite secure:

I believe this offers best amount of protection using a random salt, that has to be stored so it can be used later for verification.

If no salt is given (which can be retrieved by halving the output and taking the first half), then it will generate a random salt, hash it, place it in a position relative to the length of password (between 0 and length of hash type(sha1? md5?)) within the hashed password, and then hash the complete string.

This results in a password hash using a salt that is dynamically placed dependant on password length. The salt used is then appended to the front of the finished hash so it can be retrieved later on for verifying.

Seeing as users will choose a typical password of between 5 and say 15 characters long, this gives them an extra 10 times the amount of dictionary attacks to try out with the hash as it could be placed in any position, because this is a random generated salt too, it means at least 10 dictionary attacks (with possiblity of upto 40) for each instance a password is created, to try and work out your sha1 encrypted password.

If you change your password say every month, even if someone gets a look in at your file through a local exploit, the amount of time to work out your password would far outweigh the frequency at which you change it.

Nothing is secure, but this should take them longer to work out then the time you change it. That is at least by todays technologies.

It should be noted that sha1("") does not return an empty string. This means that if you are running a system that does not require users to have a password, the following code will not work as expected:

<?php if ($StoredPassword == sha1($NewPassword)) // Password good?>

If $StoredPassword and $NewPassword are both blank, then the password should be treated as good, but because sha1("") != "" it will be treated as bad. To get the correct behaviour you need to use:

About the complexity of sha1, sha1 generates a code a different code each 1,4615016373309029182036848327163e+48 (2 ^ 160 bits). So the chances of the use of the same hash is really small.

The "problem" of sha1 (and md5) is the speed of the generation. However, the speed is proportional with the length of the text to encrypt.

However, using a SALT, it increases tenfold times the security, even for a weak password.

In gross terms, a password of 6 characters can be hacked in a minute (if its store in md5 or sha). However, a password of 7 characters takes an hour, a password of 8 a year and a password of more than 8 character is virtually inviable of hack.

However, if we used an SALT (a secret salt btw), then even a password of 3 characters will be really safe.

sha1('SALT SECRET TEXT!!@@@aaa0000'.'123');

And a double sha1 will ensure more safety

sha1(sha1('SALT SECRET TEXT'.'123',false),false)

It will require a rainbow table of 20 characters, enough big to be absurdly safe even for a thousand of servers running during a year.

Regarding the twistSTR - the problem is that currently it is relatively easy to generate a collision for any alphanumeric plaintext of a given, short length via e.g. a rainbow table. You're bettter off using a sufficiently lengthy and random salt.

It's not amazingly difficult to reverse engineer the actual output, but then again, that's not the point. The point is that when a password is entered into one of those databases, they are going to enter for example "thisandthat", not "tathnhidast".

// Determine the length of the password.
$password_length = strlen($password);

// Determine the maximum length of password. This is only needed if
// the user enters a very long password. In any case, the salt will
// be a maximum of half the end result. The longer the hash, the
// longer the password/salt can be.
$password_max_length = $hash_length / 2;

// If we add the salt to the hashed password, we would get a hash that
// is longer than a normally hashed password. We don't want that; it
// would give away hints to an attacker. Because the password and the
// length of the password are known, we can just throw away the first
// couple of characters of the salted password. That way the salt and
// the salted password together are the same length as a normally
// hashed password without salt.
$used_chars = ($hash_length - $salt_length) * -1;
$final_result = $salt . substr($salted_password, $used_chars);

The phrase: "To get the correct behaviour", would perhaps be better off if it read: "To get the wanted (but not recommended) behaviour".

Always honor the expected data types for functions: sha1 expects a string as input, and returns a string on exit. NULL, TRUE and FALSE are not string data types. The string "" is a string as good as "any". By following the "logic" that sha1("") should return "", then what should sha1("a") return? "b"? "c"?

An authentication system that allows for blank passwords is not really an authentication system in the first place. What you are describing is merely a way to tell the application that you want to see data in some specific context, like sorted by user name, etc. Create other tools for this purpose and leave the authentication system to deal with what it is supposed to do: Granting users access to restricted data and blocking other users from seeing the same data.

Don't store passwords in clear text, but salt and encrypt them. That way it makes perfect sense having <?php $sStoredPwd === sha1($sStoredSalt . $_POST["sTypedPwd"]); ?>, even with a blank "password". No other person than the user itself, not even the programmer, should know the password or be able to guess it. If the user forgets the password, a new one must be generated.

Actually, the post by Helpful Harry won't improve your security except for the most simple break in attempts. Since the random seed is attached to the end of the password hash, if you steal the hashed password, you steal the seed.

That means you can write a simple php program to call the pw_check function Harry included from a loop, feeding it dictionary words or random characters.

Of course, if you modified the program to use the seed in a more complicated way, "they" would have to know the new function's operation. But then again, if someone can steal your password database, they can probably steal your website code (or guess it).

Append this to the your sha1lib file to make it more portable. If your version of php does support sha1() then it will try to use Mhash or else it will use the sha1lib. Use $sha1 if you want to display which is being used.

Heres an SHA1 function that will work on it's own completely. This is for users who are using below PHP 4.3.0. it works same as PHP5 ( being able to return raw output ).

<?php

/*** Date modified: 1st October 2004 20:09 GMT*** PHP implementation of the Secure Hash Algorithm ( SHA-1 )*** This code is available under the GNU Lesser General Public License:** http://www.gnu.org/licenses/lgpl.txt*** Based on the PHP implementation by Marcus Campbell** http://www.tecknik.net/sha-1/*** This is a slightly modified version by me Jerome Clarke ( sinatosk@gmail.com )** because I feel more comfortable with this*/

Sometimes you want the digest in both readable notation (such as hexadecimal) and raw binary. At other times you want the digest in a notation other than hexadecimal.

The following getDigestNotation() function takes a binary string and returns it in base 2, 4, 8, 16, 32, or 64 notation. It works with sha1(), md5(), hash(), or anything else that can output a raw binary string.

It works similar to the session.hash_bits_per_character php.ini configuration option.

You can specify which characters to use for each position, or use the default, which matches session.hash_bits_per_character (0-9, a-z, A-Z, "-", ","). The practical range of bits to use per character ($bitsPerCharacter) is 1 to 6; you may use more, but you will have to provide your own base character string ($chars) that is at least pow(2, $bitsPerCharacter) characters long. So even with 7 bits per character you need to specify a value for $chars that is 128 characters long, which exceeds the number of printable ASCII characters.

Lastly, depending on the digest length, there may be fewer bits remaining for the last character than $bitsPerCharacter, so the last character will be smaller. The same thing happens with PHP's session ID generator, when 5 or 6 is used for session.hash_bits_per_character.