I am reading the code in this page where the author is generating random token. I understand everything except from “line 29” where he divides the token into chunks and hash them with md5. My questions are::
1) Why didn’t he hash the whole token but divided them and hashing them in chunks?
2) Will hashing them in chunks deliver the same results as hashing the undivided token ?
3) On “line 36″ also he does some substring which i think MAY reduce the number of characters. In doing so can the hashed token be reconstructed to the original unhashed token?
Here is the most important part of the code ::
# Array indice friendly number of chars; empty token string
$numChars = count($chars) - 1; $token = '';
# Create random token at the specified length
for ( $i=0; $i<$len; $i++ )
$token .= $chars[ mt_rand(0, $numChars) ];
# Should token be run through md5?
if ( $md5 ) {
# Number of 32 char chunks
$chunks = ceil( strlen($token) / 32 ); $md5token = '';
# Run each chunk through md5
for ( $i=1; $i<=$chunks; $i++ )
$md5token .= md5( substr($token, $i * 32 - 32, 32) );
# Trim the token
$token = substr($md5token, 0, $len);
} return $token;
}
I hope someone will help me get a little understanding. Thanks
EDIT
4) Why did he used 32 inside the substr() function?
md5()is a one-way hash algorithm. Meaning it cannot be reconstructed into its original form.To answer question 1, it creates a more secure hash. Common strings can be matched to their known hash values. This helps prevent that from happening.
And your edit for number 4, the third parameter (32) sets the length of the returned string. I suggest you look through the PHP manual. It’s a great resource.