How to verify that a file is a password protected ZIP file using C #

Given the file path, how can I check if the file is a password protected zip file?

ie, how would I implement this function?

bool IsPasswordProtectedZipFile(string pathToFile)

I do not need to unzip the file - I just need to verify that it is ZIP and has been password protected.

thanks

+3
source share
4 answers

Using SharpZipLib , the following code works. And by works, I mean it entry.IsCryptedreturns true or false based on whether there is a password for the first entry in the zip file.

var file = @"c:\testfile.zip";
FileStream fileStreamIn = new FileStream(file, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
ZipEntry entry = zipInStream.GetNextEntry();
Console.WriteLine("IsCrypted: " + entry.IsCrypted);

A simple tutorial on using SharpZipLib on CodeProject .

, :

public static bool IsPasswordProtectedZipFile(string path)
{
    using (FileStream fileStreamIn = new FileStream(path, FileMode.Open, FileAccess.Read))
    using (ZipInputStream zipInStream = new ZipInputStream(fileStreamIn))
    {
        ZipEntry entry = zipInStream.GetNextEntry();
        return entry.IsCrypted;
    }
}

, - ...

+3

ZIP- , . , , . DotNetZip:

int encryptedEntries = 0;
using (var zip = ZipFile.Read(nameOfZipFile)) 
{
    // check a specific, named entry: 
    if (zip["nameOfEntry.doc"].UsesEncryption)
       Console.WriteLine("Entry 'nameOfEntry.doc' uses encryption"); 

    // check all entries: 
    foreach (var e in zip)
    {
       if (e.UsesEncryption)
       {
           Console.WriteLine("Entry {0} uses encryption", e.FileName); 
           encryptedEntries++; 
       }
    }
}

if (encryptedEntries > 0) 
    Console.WriteLine("That zip file uses encryption on {0} entrie(s)", encryptedEntries); 

, LINQ:

private bool ZipUsesEncryption(string archiveToRead)
{
    using (var zip = ZipFile.Read(archiveToRead))
    {
        var selection = from e in zip.Entries
            where e.UsesEncryption
            select e;

        return selection.Count > 0;
    }
}
+3

.NET Framework . , Google. Microsoft Codeplex DotNetZip. , " ".

+1

There is no 100% correct way to check if all zip entries are encrypted. each zipfile entry is independent and may have its own password / encrypted method.

In most cases, the zipfile is encrypted with some software, this software ensures that every entry in the zipfile has a common password and an encrypted method.

So, using the first zipentry (and not the directory) to check if this zipfile is encrypted can cover most cases.

0
source

Source: https://habr.com/ru/post/1721343/


All Articles