Skip to content

Instantly share code, notes, and snippets.

@vishwarajanand
Created August 10, 2023 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishwarajanand/3e5c610222a30468805cbc618860428d to your computer and use it in GitHub Desktop.
Save vishwarajanand/3e5c610222a30468805cbc618860428d to your computer and use it in GitHub Desktop.
Product CRC32C in Pure PHP7.4+
<?php
use Google\CRC32\CRC32;
use GuzzleHttp\Psr7\Utils;
include __DIR__.'/vendor/autoload.php';
$filePath = __DIR__.'/tests/System/data/5mb.txt';
## USAGE:
# Paste the file into https://github.com/googleapis/google-cloud-php/tree/main/Storage
# Run using this command: `php crcTest.php`
# Tests the crc32c hash function for this PR: https://github.com/googleapis/google-cloud-php/pull/6532
$stream = Utils::streamFor(fopen($filePath, 'r'));
$crc32c = CRC32::create(CRC32::CASTAGNOLI);
$crc32c->update((string) $stream);
$hash = ($crc32c->hash(true));
echo $hash.PHP_EOL;
function fileToHash($filePath, $bufferSize = 1048576)
{
$fp = fopen($filePath, "r");
$ctx = hash_init('crc32c');
while (!feof($fp)) {
$buffer = fgets($fp, $bufferSize);
hash_update($ctx, $buffer);
}
fclose($fp);
$hash = hash_final($ctx, true);
return $hash;
}
$hash = fileToHash($filePath);
echo base64_encode($hash).PHP_EOL;
// hash a different buffer window size
$hash = fileToHash($filePath, 65536);
echo base64_encode($hash).PHP_EOL;
// hash full file in one go
$data = file_get_contents($filePath);
$hash = hash('crc32c', $data, true);
echo base64_encode($hash).PHP_EOL;
@vishwarajanand
Copy link
Author

It printed: egbghQ== (the same hash four times, which means we can safely migrate the hash function)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment