lithium\security\Hash::calculate()
Uses PHP's hashing functions to calculate a hash over the data provided, using the options specified. The default hash algorithm is SHA-512.
Examples:
// Calculates a secure hash over string `'foo'`.
Hash::calculate('foo');
// It is possible to hash non-scalar data, too.
Hash::calculate(['foo' => 'bar']); // serializes before hashing
Hash::calculate(new Foo()); // -- " --
Hash::calculate(function() { return 'bar'; }); // uses `spl_object_hash()`
// Also allows for quick - non secure - hashing of arbitrary data.
Hash::calculate(['foo' => 'bar'], ['type' => 'crc32b']);
Parameters
-
mixed
$data
The arbitrary data to hash. Non-scalar data will be serialized, before being hashed. For anonymous functions the object hash will be used.
-
array
$options
Supported options:
'type'
string: Any valid hashing algorithm. See thehash_algos()
function to determine which are available on your system.'salt'
string: A salt value which, if specified, will be prepended to the data.'key'
string: If specified generates a keyed hash usinghash_hmac()
instead ofhash()
, with'key'
being used as the message key.'raw'
boolean: Iftrue
, outputs the raw binary result of the hash operation. Defaults tofalse
.
Returns
stringReturns a hash calculated over given data.
Links
Source
public static function calculate($data, array $options = []) {
if (!is_scalar($data)) {
$data = ($data instanceof Closure) ? spl_object_hash($data) : serialize($data);
}
$defaults = [
'type' => 'sha512',
'salt' => false,
'key' => false,
'raw' => false
];
$options += $defaults;
if ($options['salt']) {
$data = "{$options['salt']}{$data}";
}
if ($options['key']) {
return hash_hmac($options['type'], $data, $options['key'], $options['raw']);
}
return hash($options['type'], $data, $options['raw']);
}