Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if string is sha1 in PHP

Tags:

php

sha1

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.

like image 288
Leagsaidh Gordon Avatar asked Jun 05 '10 20:06

Leagsaidh Gordon


People also ask

What is PHP sha1?

The sha1() function calculates the SHA-1 hash of a string. The sha1() function uses the US Secure Hash Algorithm 1. From RFC 3174 - The US Secure Hash Algorithm 1: "SHA-1 produces a 160-bit output called a message digest.


2 Answers

ctype_xdigit is much faster. I typically use hashes for lookups and find it very useful.

like image 42
Kristopher Ives Avatar answered Oct 14 '22 20:10

Kristopher Ives


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_provided_pass))
   echo "Password is correct!";
like image 128
Andrew Moore Avatar answered Oct 14 '22 19:10

Andrew Moore