首页 > 解决方案 > 在 PHP 中为 Google Cloud Storage 对象计算 md5Hash 或 crc32

问题描述

我无法计算此处记录的 Google Cloud Storage 对象的文件哈希。

我试过crc32($filepath),hash_file('crc32b', $filepath)和 md5 等价物,但没有什么能与他们想出的东西相匹配。我也尝试过对结果进行 base64 编码,但当时我只是在猜测。

如何根据此文件在 PHP 中获取以下哈希值?https://storage.googleapis.com/hashing-test/0067142-0.png

crc32c:wPjVCQ==

md5哈希:SNsMU2l0FHH+BE3Fg79Vew==

标签: phpgoogle-cloud-storage

解决方案


我在谷歌库源代码中找到了答案。以下返回一个与对象信息中创建的字符串相同的字符串。

use Google\CRC32\CRC32;

function getCrc32($content) {
  $crc32c = CRC32::create(CRC32::CASTAGNOLI);
  $crc32c->update($content);
  return base64_encode($crc32c->hash(true));
}

$hash = getCrc32(file_get_contents('/path/to/foo.png'));

推荐阅读