Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream DEFLATED

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream DEFLATED

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream DEFLATED.

Prototype

int DEFLATED

To view the source code for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream DEFLATED.

Click Source Link

Document

Compression method for deflated entries.

Usage

From source file:cz.muni.fi.xklinec.zipstream.Mallory.java

/**
 * Returns true if given file name should be postponed (is modified in tampering process).
 * @param ze //from  w  w  w .j a  va 2 s. c  o  m
 * @return  
 */
public boolean isPostponed(ZipArchiveEntry ze) {
    final String curName = ze.getName();
    if (curName.startsWith(META_INF) || CLASSES.equalsIgnoreCase(curName)
            || ANDROID_MANIFEST.equalsIgnoreCase(curName) || RESOURCES.equalsIgnoreCase(curName)
            || curName.endsWith(".xml")
            || (ze.getMethod() == ZipArchiveOutputStream.DEFLATED && curName.endsWith(".png"))) {
        return true;
    }

    if (exclude != null && !exclude.isEmpty()) {
        for (String regex : exclude) {
            if (curName.matches(regex)) {
                return true;
            }
        }
    }

    return false;
}

From source file:cz.muni.fi.xklinec.zipstream.Mallory.java

/**
 * Reads tampered APK file (zip object is prepared for this file prior 
 * this function call).//from   www .j  a v a  2  s . co  m
 * 
 * If a) file differs or b) file is new, it is added to the output zip stream.
 * 
 * Method also handles padding to a given size. Attribute padlen is used,
 * if addPadding is true, padlen bytes are distributed to {new, modiffied} 
 * files in extra field in central directory. 
 * 
 * @param addPadding
 * @throws IOException 
 */
public void mergeTamperedApk(boolean addPadding, boolean forReal) throws IOException {
    // Read the tampered archive
    ZipArchiveEntry ze = zip.getNextZipEntry();

    Set<String> files = new HashSet<String>();
    long padlenLeft = padlen;
    while (ze != null) {

        // Data for entry
        byte[] byteData = Utils.readAll(zip);
        byte[] deflData = new byte[0];
        int defl = 0;

        long padd2add = -1;
        if (addPadding) {
            padd2add = compPadding(padlenLeft);
        }

        // If method is deflated, get the raw data (compress again).
        if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) {
            def.reset();
            def.setInput(byteData);
            def.finish();

            byte[] deflDataTmp = new byte[byteData.length * 2];
            defl = def.deflate(deflDataTmp);

            deflData = new byte[defl];
            System.arraycopy(deflDataTmp, 0, deflData, 0, defl);
        }

        final String curName = ze.getName();
        PostponedEntry al = new PostponedEntry(ze, byteData, deflData);

        files.add(curName);

        // Compare posponed entry with entry in previous
        if (alMap.containsKey(curName) == false || alMap.get(curName) == null) {
            // This element is not in the archive at all! 
            // Add it to the zop
            if (!quiet)
                System.err.println(
                        "Detected newly added file [" + curName + "] written prior dump: " + zop.getWritten());

            // Apply padding
            if (padd2add > 0) {
                addExtraPadding(al.ze, (int) padd2add);
                padlenLeft -= padd2add;
                if (!quiet)
                    System.err.println("  Added padding: " + padd2add + "; left: " + padlenLeft);
            }

            al.dump(zop, recomputeCrc);

        } else {
            // Check the entry against the old entry hash
            // All files are read linary from the new APK file
            // thus it will be put to the archive in the right order.
            PostponedEntry oldEntry = alMap.get(curName);
            boolean wasPostponed = isPostponed(oldEntry.ze);
            if ((oldEntry.hashByte == null && al.hashByte != null)
                    || (oldEntry.hashByte != null && oldEntry.hashByte.equals(al.hashByte) == false)
                    || (defl > 0 && (oldEntry.hashDefl == null && al.hashDefl != null)) || (defl > 0
                            && (oldEntry.hashDefl != null && oldEntry.hashDefl.equals(al.hashDefl) == false))) {
                // Element was changed, add it to the zop 
                // 
                if (!quiet) {
                    System.err.println(
                            "Detected modified file [" + curName + "] written prior dump: " + zop.getWritten());
                    System.err.println("  t1=" + oldEntry.hashByte.equals(al.hashByte) + "; t2="
                            + oldEntry.hashDefl.equals(al.hashDefl));
                }

                if (!wasPostponed && !quiet) {
                    System.err.println(
                            "  Warning: This file was already sent to the victim (file was not postponed) !!!");
                }

                // Apply padding
                if (padd2add > 0) {
                    addExtraPadding(al.ze, (int) padd2add);
                    padlenLeft -= padd2add;
                    if (!quiet)
                        System.err.println("  Added padding: " + padd2add + "; left: " + padlenLeft);
                }

                al.dump(zop, recomputeCrc);

            } else if (wasPostponed) {
                // File was not modified but is one of the postponed files, thus has to 
                // be flushed also.
                if (!quiet)
                    System.err.println("Postponed file not modified [" + curName + "] written prior dump: "
                            + zop.getWritten());

                // Apply padding
                if (padd2add > 0) {
                    addExtraPadding(al.ze, (int) padd2add);
                    padlenLeft -= padd2add;
                    if (!quiet)
                        System.err.println("  Added padding: " + padd2add + "; left: " + padlenLeft);
                }

                al.dump(zop, recomputeCrc);
            }
        }

        ze = zip.getNextZipEntry();
    }

    // Check if some file from the original file is not in the modified file.
    if (forReal && !quiet) {
        // Iterate over map files and lookup the same among modified files.
        for (String oldFile : alMap.keySet()) {
            if (files.contains(oldFile) == false) {
                if (sentFiles.contains(oldFile)) {
                    System.err.println("Warning: File from original file [" + oldFile
                            + "] was not found in tampered file and file was already sent!!!");
                } else {
                    System.err.println("Warning: File from original file [" + oldFile
                            + "] was not found in tampered file!");
                }
            }
        }
    }

    // If omitMissing is specified, remove ZIP entries from ZOP that are not present
    // in tampered file (no signature for them).
    if (omitMissing) {
        List<ZipArchiveEntry> entries = zop.getEntries();

        // Iterate over map files and lookup the same among modified files.
        for (String oldFile : alMap.keySet()) {
            if (files.contains(oldFile) == false) {
                if (!sentFiles.contains(oldFile)) {
                    continue;
                }

                // Remove from ZOP entries list - will be not added to central directory
                if (alMap.containsKey(oldFile) == false) {
                    if (!quiet) {
                        System.err.println("Warning: File from original file [" + oldFile
                                + "] was not found in tampered file and file was already sent, no ZIP entry!!!");
                    }

                    continue;
                }

                boolean deleted = false;

                // Delete file based on filename (do not rely on .equals()).
                Iterator<ZipArchiveEntry> it = entries.iterator();
                while (it.hasNext()) {
                    ZipArchiveEntry tmpZe = it.next();
                    if (tmpZe.getName().equals(oldFile)) {
                        it.remove();
                        deleted = true;
                        break;
                    }
                }

                if (!quiet) {
                    System.err.println(
                            "Removed [" + deleted + "] File [" + oldFile + "] remove from zip entries.");
                }
            }
        }
    }

    if (!quiet && addPadding && padlenLeft > 0) {
        System.err.println("Warning! Not enough modified files to add required padding. Left: " + padlenLeft
                + "/" + padlen);
    }
}

From source file:no.difi.sdp.client.asice.archive.CreateZip.java

public Archive zipIt(List<AsicEAttachable> files) {
    ByteArrayOutputStream archive = null;
    ZipArchiveOutputStream zipOutputStream = null;
    try {//from   w w w.  ja va2s . co  m
        archive = new ByteArrayOutputStream();
        zipOutputStream = new ZipArchiveOutputStream(archive);
        zipOutputStream.setEncoding(Charsets.UTF_8.name());
        zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
        for (AsicEAttachable file : files) {
            log.trace("Adding " + file.getFileName() + " to archive. Size in bytes before compression: "
                    + file.getBytes().length);
            ZipArchiveEntry zipEntry = new ZipArchiveEntry(file.getFileName());
            zipEntry.setSize(file.getBytes().length);

            zipOutputStream.putArchiveEntry(zipEntry);
            IOUtils.copy(new ByteArrayInputStream(file.getBytes()), zipOutputStream);
            zipOutputStream.closeArchiveEntry();
        }
        zipOutputStream.finish();
        zipOutputStream.close();

        return new Archive(archive.toByteArray());
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    } finally {
        IOUtils.closeQuietly(archive);
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:org.codehaus.plexus.archiver.jar.JarArchiver.java

/**
 *//* ww w  . ja  v a  2 s. com*/
protected boolean createEmptyZip(File zipFile) throws ArchiverException {
    if (!createEmpty) {
        return true;
    }

    try {
        getLogger().debug("Building MANIFEST-only jar: " + getDestFile().getAbsolutePath());
        zipArchiveOutputStream = new ZipArchiveOutputStream(
                bufferedOutputStream(fileOutputStream(getDestFile(), "jar")));

        zipArchiveOutputStream.setEncoding(getEncoding());
        if (isCompress()) {
            zipArchiveOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
        } else {
            zipArchiveOutputStream.setMethod(ZipArchiveOutputStream.STORED);
        }
        ConcurrentJarCreator ps = new ConcurrentJarCreator(Runtime.getRuntime().availableProcessors());
        initZipOutputStream(ps);
        finalizeZipOutputStream(ps);
    } catch (IOException ioe) {
        throw new ArchiverException("Could not create almost empty JAR archive (" + ioe.getMessage() + ")",
                ioe);
    } finally {
        // Close the output stream.
        //IOUtil.close( zOut );
        createEmpty = false;
    }
    return true;
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipArchiver.java

private void createArchiveMain() throws ArchiverException, IOException {
    //noinspection deprecation
    if (!Archiver.DUPLICATES_SKIP.equals(duplicate)) {
        //noinspection deprecation
        setDuplicateBehavior(duplicate);
    }/*  www  . ja v a2  s  . co  m*/

    ResourceIterator iter = getResources();
    if (!iter.hasNext() && !hasVirtualFiles()) {
        throw new ArchiverException("You must set at least one file.");
    }

    zipFile = getDestFile();

    if (zipFile == null) {
        throw new ArchiverException("You must set the destination " + archiveType + "file.");
    }

    if (zipFile.exists() && !zipFile.isFile()) {
        throw new ArchiverException(zipFile + " isn't a file.");
    }

    if (zipFile.exists() && !zipFile.canWrite()) {
        throw new ArchiverException(zipFile + " is read-only.");
    }

    // Whether or not an actual update is required -
    // we don't need to update if the original file doesn't exist

    addingNewFiles = true;

    if (doUpdate && !zipFile.exists()) {
        doUpdate = false;
        getLogger().debug("ignoring update attribute as " + archiveType + " doesn't exist.");
    }

    success = false;

    if (doUpdate) {
        renamedFile = FileUtils.createTempFile("zip", ".tmp", zipFile.getParentFile());
        renamedFile.deleteOnExit();

        try {
            FileUtils.rename(zipFile, renamedFile);
        } catch (SecurityException e) {
            getLogger().debug(e.toString());
            throw new ArchiverException(
                    "Not allowed to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e);
        } catch (IOException e) {
            getLogger().debug(e.toString());
            throw new ArchiverException(
                    "Unable to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e);
        }
    }

    String action = doUpdate ? "Updating " : "Building ";

    getLogger().info(action + archiveType + ": " + zipFile.getAbsolutePath());

    if (!skipWriting) {
        zipArchiveOutputStream = new ZipArchiveOutputStream(
                bufferedOutputStream(fileOutputStream(zipFile, "zip")));
        zipArchiveOutputStream.setEncoding(encoding);
        zipArchiveOutputStream
                .setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NOT_ENCODEABLE);
        zipArchiveOutputStream
                .setMethod(doCompress ? ZipArchiveOutputStream.DEFLATED : ZipArchiveOutputStream.STORED);

        zOut = new ConcurrentJarCreator(Runtime.getRuntime().availableProcessors());
    }
    initZipOutputStream(zOut);

    // Add the new files to the archive.
    addResources(iter, zOut);

    // If we've been successful on an update, delete the
    // temporary file
    if (doUpdate) {
        if (!renamedFile.delete()) {
            getLogger().warn("Warning: unable to delete temporary file " + renamedFile.getName());
        }
    }
    success = true;
}