Hash method on multiple values?
Occasionally, I find I need to sort some objects, grouping them by multiple values. I usually accomplish this by concatenating the values together, with an underscore or other delineator in between, and then use that as an array index.
// group all 开发者_Python百科objects with a common parent_id, date, and type
foreach ($objects as $obj) {
$hash = $obj->parent_id . '_' . $obj->date . '_' . $obj->type;
$sorted_objects[$hash][] = $obj;
}
...ick! There's got to be a better way than abusing PHP's loose typing and string concatenation. Is there any way to perform a hash on multiple values? It seems I should be able to just do something like this:
$hash = sha1_multiple($obj->parent-id, $obj->date, $obj->type);
Am I already using the best method, or is there a better way?
Using PHP's serialization makes it a bit neater, but less efficient:
function sha1_multiple() {
$args = func_get_args();
return sha1(serialize($args));
}
Since hash keys are strings you're probably doing it the best way already, via a hash of the string concatenation - that's how I've performed similar functions when I've needed to in the past.
In concat-then-hash, the hash of "Jim" and "Fisher" is the hash of "JimFisher". Reversing the inputs produces the hash of "FisherJim", a distinct string, so this is not vulnerable to an attack by reordering inputs. Is concat-then-hash then invulnerable to a second-preimage attack? Can you find an example of another input which collides with hash2_concat_then_hash("Jim", "Fisher")? Again, you don’t need to brute-force it! One example is hash2_concat_then_hash("Ji", "mFisher"), because "Ji" and "mFisher" also concatenate to "JimFisher".
For more info, take a look at how-to-hash-multiple-values
精彩评论