Created
August 10, 2023 13:53
-
-
Save vishwarajanand/3e5c610222a30468805cbc618860428d to your computer and use it in GitHub Desktop.
Product CRC32C in Pure PHP7.4+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It printed:
egbghQ==
(the same hash four times, which means we can safely migrate the hash function)