检查Zip文件是否使用PHP加密或密码保护



我正在编写一个扫描程序,它将查找可能被黑客入侵/恶意软件的文件。一个要求是使用某些PHP函数检查zip(或任何压缩)文件是否受密码保护。

我不想添加任何额外的软件要求,所以应该使用 PHP 5.3+ 在多台服务器上工作。(是的,我知道 5.3 是旧的,但该过程可能需要在较旧的 PHP 安装上运行。如果此检测在较新的 PHP 版本中可用,那么我可能拥有仅在较新的 PHP 版本上运行的代码。

我可以使用file_get_contents()函数将文件的内容读入字符串。如何检查该字符串是否指示 zip 文件受密码保护?请注意,我不想解压缩文件,只需检查它是否有密码保护。

谢谢。

此代码似乎有效,但可能会有所改进。

该过程似乎涉及两个步骤:

  • 使用 zip_open 打开文件,返回资源。没有资源,无法打开 zip,因此可能是密码

  • 使用zip_read读取 zip 中的文件。如果失败,则可能是密码

在这两种情况下,返回 true,指示 zip 文件上可能存在的密码。

// try to open a zip file; if it fails, probably password-protected
function check_zip_password($zip_file = '') {
/*
open/read a zip file
return true if passworded
*/
if (!$zip_file) { // file not specified
return false;
}
$zip = zip_open($zip_file);     // open the file
if (is_resource($zip)) {        // file opened OK
$zipfile = zip_read($zip);  // try read of zip file contents
if (!$zipfile) { // couldn't read inside, so passworded
return true;
} 
else 
{ // file opened and read, so not passworded
return false;
}
} else { // couldn't open the file, might be passworded
return true;
}
return false; // file exists, but not password protected
}

请注意,该代码仅确定无法访问 zip 中的文件,因此它们可能受密码保护。该代码不会尝试对 zip 中的文件进行任何处理。

最新更新