我有一个运行 PHP 的服务器,我可以在管理面板中使用自定义表单上传 zip 档案。当我上传一个 zip 存档时,我会计算它的 CRC32 校验和,并将其插入到我的数据库中以供将来进行下载完整性检查:
$zipchecksum = strtoupper(hash_file('crc32', $zippath));
$mysqli->query("INSERT INTO files VALUES (NULL, '$zipname', '$zippath')");
当我使用 C# 客户端向服务器查询要下载的可用文件时,我还会在响应中收到该校验和,如果有新文件可用,我会下载它:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.URLDownload);
request.Accept = "application/octet-stream";
request.ContentType = "application/x-www-form-urlencoded";
request.Method = WebRequestMethods.Http.Post;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (MemoryStream memoryStream = new MemoryStream())
{
responseStream.CopyTo(memoryStream);
Crc32 crc = new Crc32();
crc.Update(memoryStream.GetBuffer());
if (crc.Value.ToString("X") != m_ServerData.CRC)
throw new Exception("Malformed zip file received!");
ZipFile file = new ZipFile(memoryStream);
// ...
}
这是我的回应:
header('Cache-Control: must-revalidate, pre-check=0, post-check=0');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="'.$zipname.'"');
header('Content-Length: '.filesize($filepath));
header('Content-Transfer-Encoding: binary');
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Pragma: public');
readfile($zippath);
现在,完整性检查来了。PHP 计算的 CRC32 校验和与我在客户端使用 ICSharpCode.SharpZipLib 中的 Crc32 类计算的校验和完全不同。例如:
PHP 服务器 -> CF83A609
C# 客户端 -> 3FB78619
我还尝试使用另一个 PHP 函数:
$zipcontents = file_get_contents($zippath);
$crc = crc32($zipcontents);
$zipchecksum = strtoupper(dechex(crc32($zipcontents)));
$mysqli->query("INSERT INTO files VALUES (NULL, '$zipname', '$zippath')");
但结果再次不同。
PHP 服务器 -> A6A642D0
C# 客户端 -> 3FB78619
因此,PHP 用于计算校验和的缓冲区似乎与客户端从服务器接收的缓冲区不同。嗯...有人有解决方案吗?