Click the Castor logo or press Ctrl Alt T to change theme.
# Generic hashing Generic hashing gives you a fixed-size fingerprint for bytes. Castor Crypto uses libsodium's BLAKE2b implementation through `Hash`. Use it for file integrity, content addressing, cache keys, and keyed internal identifiers. Do not use it to store passwords; use [Password hashing](password-hashing.html). ## Fingerprint an uploaded file Hashing can be streamed, so large files do not need to be loaded into memory. ```php <?php use Castor\Crypto\Hash; $hash = Hash::new(); $handle = fopen($_FILES['upload']['tmp_name'], 'rb'); while (!feof($handle)) { $hash->write(fread($handle, 8192)); } $fingerprint = $hash->sum()->toHex(); ``` Store the fingerprint with the file metadata. Later, hash the file again and compare the decoded value with `equals()`. ## Cache keys from structured data A digest can turn long structured inputs into a compact key. ```php $hash = Hash::new(); $hash->write('report:v1:'); $hash->write(json_encode($filters, JSON_THROW_ON_ERROR)); $cacheKey = 'reports:'.$hash->sum(length: 16)->toHex(); ``` Include a prefix or version string so that unrelated features do not accidentally share the same hash namespace. ## Keyed hashes for internal identifiers A keyed hash acts like a message authentication code for small internal values. It lets you create identifiers that outsiders cannot predict without the key. ```php $hash = Hash::new(key: $_ENV['INTERNAL_HASH_KEY'], length: 32); $hash->write('user-download:'.$userId.':'.$fileId); $id = $hash->sum(length: 16)->toBase64(); ``` This can be useful for non-secret lookup tokens. If the token grants access, still enforce authorization on the server; do not rely on obscurity alone. ## Tradeoffs and attack vectors Hashes are not encryption. Anyone with the original data can compute the same digest. If the input comes from a small set, attackers can guess it offline. Plain hashes do not prove authorship. If you need to prove your app created a value, use [Signed data](signed-data.html) or a keyed hash with a carefully managed secret key. Hash comparisons should use `equals()` when both values are `SecretText`. Avoid leaking timing differences in security-sensitive comparisons.
Castor ecosystem