Zip - Password Protect an Existing Archive

0 votes
asked Sep 22, 2012 by tltabor (210 points)
edited Dec 6, 2013

How would I go about password protecting an existing archive w/o extracting and rezipping?

Thank you.

Applies to: Rebex ZIP

3 Answers

0 votes
answered Sep 23, 2012 by Lukas Matyska (56,670 points)
edited Aug 2, 2013

Unfortunately, adding password protection to an existing Zip archive without extracting and rezipping it is not possible with the current version. If you miss this feature, you can create/vote for it at rebex.uservoice.com

Here is the code how to do it with rezipping:

string sourcePath = "source.zip";
string targetPath = "target.zip";
string password = "pwd";

using (ZipArchive source = new ZipArchive(sourcePath),
        target = new ZipArchive(targetPath, ArchiveOpenMode.Create))
{
    // set encryption values for target archive
    target.EncryptionAlgorithm = EncryptionAlgorithm.Aes256;
    target.Password = password;

    // iterate through all items in archive
    foreach (ZipItem item in source.GetItems("*", TraversalMode.Recursive))
    {
        // check if the item can be extracted
        if (!item.CanExtract)
            new ApplicationException(string.Format("Item {0} cannot be extracted.", item.Path));

        if (item.IsDirectory)
        {
            // create directory to persist empty directories also
            target.CreateDirectory(item.Path);
        }
        else
        {
            // get stream to read decompressed data of the file
            using (Stream file = item.Open())
            {
                target.AddFile(file, item.Path);
            }
        }
    }
}
0 votes
answered Sep 23, 2012 by tltabor (210 points)
edited Sep 23, 2012

Yes, I will vote for that. In the meantime, this is a VERY classy reply. Thank you Lukas.

0 votes
answered Dec 6, 2013 by Pavel Matyska (13,340 points)
edited Dec 6, 2013

From Version 2013 R3 you can protect your existing ZIP archive with password using single line of code.

ZipArchive.Encrypt("zipFile", "encryptedZipFile", "password", EncryptionAlgorithm.Aes256);

It takes zipFile and directly encrypts its entries to new encryptedZipFile using the specified password and EncryptionAlgorithm. It is faster than the approach above because there is no need to decompress and compress entries again.

...