cgwebprojects
cgwebprojects

Reputation: 3472

Sha 1 php, possible variations and regex

First,

Is it possible for a sha1 hash to be all numbers or letters,

And second is there any need for the start and end delimiters when using a regex to check for a sha 1 hash, ie,

/^[0-9a-f]{40}$/i

inplace of

/[0-9a-f]{40}/i

Is there any need to use the delimeters?

I ask as should I check if the pattern has at least one number and at least one letter, or does this not matter?

Upvotes: 1

Views: 511

Answers (1)

Corbin
Corbin

Reputation: 33437

A sha1 hash is a 160 bit value that can be between all 0s and all 1s. This means that yes, in theory it can be all numbers or all letters (more specifically, the hex representation of it can be).

As for the beginning and ending markers, they are required unless you check the string in other ways. The two patterns you posted are not equivalent:

/^[0-9a-f]{40}$/i

A string that consists of and only of 40 character in 0-9 or a-f.

/[0-9a-f]{40}/i

A string that contains 40 character in 0-9 or a-f in a row.

In other words, the first pattern would consider this invalid whereas the second would not:

|0000000000000000000000000000000000000000|

The second pattern would match the 40 valid characters in the middle and not care about the rest of it.

You could effectively turn the second pattern into the first if you also used strlen to verify that the string is exactly 40 characters. This would be a bit redundant though, as you'd essentially then have a pattern of:

A string that: (contains 40 characters in 0-9 or a-f in a row) and (is exactly 40 characters).

The first version expresses it more compactly, though the second is a bit more obvious.

Upvotes: 3

Related Questions