python check if compressed file is password-protected with just a small part of a file

39 views Asked by At

I want to check if some .rar or .zip files are password-protected or not. There are packages (zipfile, rarfile) with some specific methods (testzip, tetrar) that can check if the file is password-protected or not. I also found this code snippets and they work fine:

import zipfile
import rarfile

def is_zip_password_protected(file_path):
    try:
        with zipfile.ZipFile(file_path) as zf:
            zf.testzip()
            return False
    except RuntimeError as e:
        if "encrypted" in str(e):
            return True
        else:
            raise e
    except zipfile.BadZipFile:
        return False

def is_rar_password_protected(file_path):
    try:
        with rarfile.RarFile(file_path) as rf:
            rf.testrar()
            return False
    except rarfile.NeedFirstVolume:
        return False
    except rarfile.BadRarFile:
        return False
    except rarfile.PasswordRequired:
        return True

# Example usage:
zip_file_path = "example.zip"
rar_file_path = "example.rar"

print(f"{zip_file_path} is password protected:", is_zip_password_protected(zip_file_path))
print(f"{rar_file_path} is password protected:", is_rar_password_protected(rar_file_path))

The problem is that these packages need to access the whole file to check it. I have an uploader project on a server that takes some local files and uploads them into some cloud-storage like thing. To deal with large compressed files, I need to check them with only a small part of those files (like stream a few kilobytes of the file).

Is there any way to check files with just a small part of them?

0

There are 0 answers