tags:

views:

150

answers:

2

I'm planning on storing the passwords as a sha1, so I need a way to validate that it is a sha1 at another point in my website. I was planning on using preg_match, but I do not know how to make regex patterns. Could someone help me out with one?

Thanks

Edit: I am not trying to see if two hashes match.

+6  A: 

Actually, you can use preg_match() to make sure it's a 40 characters hexadecimal string as such:

function is_sha1($str) {
    return (bool) preg_match('/^[0-9a-f]{40}$/i', $str);
}

To explain the pattern:

/        Opening Delimiter
^        Start Of String Anchor
[0-9a-f] Any of the following characters: 0123456789abcdef
{40}     Repeated 40 times
$        End Of String Anchor
/        Closing Delimiter
i        Modifier: Case-Insensitive Search


If you are trying to make sure that the sha1() hash matches the password the user provider, you simply rehash like this:

if($db_hash == sha1($user_provider-pass))
   echo "Password is correct!";
Andrew Moore
Thank you. You not only gave me the pattern that I needed, but you also explained what each bit meant.
SGWebsNow
Or you could use [`ctype_xdigit`](http://php.net/ctype_xdigit) (to check for hexadecimal digits only) and [`strlen`](http://php.net/strlen) (to check for the string length).
salathe
A: 

When comparing two SHA1 hashes, and you know that the first one is one (because it comes out of the database), then just assume that the second is a SHA1 value as well. You are only interested if two hashes match or not. If one of the compared values is not a possible SHA1 value, then it's particulary not the same as the one in the database. And that's all you need to know.

poke