Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string is a valid sha256 hash in PHP?

How do I manage to identify a sha256 hash using PHP? Also, is there any way to identify if the string is a sha256 hash even if it was salted?

I don't need to know the real value of the hash (I know that is impossible), but I need only to validate the string, so I can work in a way if the string is a sha256 hash and work another way if it isn't.

like image 392
Felipe Francisco Avatar asked Jun 01 '13 17:06

Felipe Francisco


2 Answers

I do not understand what you mean when you say: "even if it was salted". Salting happens before hashing, it offers some protection against rainbow table attacks and users using the same password on multiple sites. Depending on the base a simple regex can tell you if a particular string is a sha256 hash. i think most times we encounter hashes in base16, in that case this would work:

   if (preg_match("/^([a-f0-9]{64})$/", $hash) == 1) {
      return true;
   } else {
      return false;
   }
like image 200
MerlinTheMagic Avatar answered Oct 13 '22 19:10

MerlinTheMagic


The only way to check if a hash is a valid SHA-256 hash is to check 256 bits in it- if it does, then yes some input CAN possibly generate that output.

Hashes are one way meaning I can give you a hash and you can never decrypt it (this is the difference between hashing and an encryption). This is good for storing passwords and such where the plain text value is irrelevant.

like image 8
Hans Avatar answered Oct 13 '22 20:10

Hans