0 votes
by (210 points)
edited

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
by (72.7k points)
edited

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
by (210 points)
edited

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

0 votes
by (15.2k points)
edited

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.

...