Our organistation would like to hash large file paths to asssign to a specific object. To prevent hash collisions, I thought we can use the same sort of technique as we use to prevent rainbow tables in password hashes. When you hash the value 'sample data' we will first prepend an IV, which will be used as hmac secret to verify the hash.
function makeHash($data,$algo='sha256',$ivKey=null) {
if(empty($ivKey)) {
$ivKey = openssl_random_pseudo_bytes(16);
}
$result = $ivKey.hash_hmac($algo,$data,$ivKey,true);
return base64_encode($result);
}
function verifyHash($data,$hash,$algo='sha256') {
$result = base64_decode($hash);
$ivKey = mb_substr($result,0,16,'8bit');
$dataHash = makeHash($data,$algo,$ivKey);
return $hash == $dataHash;
}
Usage example:
$hash = makeHash('sample data');
echo $hash;
var_dump(verifyHash('sample data',$hash));
/**
Output:
I9Kl9Mkq/6ee3xQixrDn3YImRAywz0rhmBBxRjrfRWiGeRuBrIkREirgKBDr8Gzh
bool(true)
*/
Would this be a good way to prevent collisions?