← ZIP archive
ZIP·Guide
All tools

ZIP archives

APKs, IPAs, JARs, AARs, XAPKs, App Bundles, Office documents and EPUBs are all ZIP archives. The tool shows what an archive holds and how it is laid out, checks it, searches inside its files and lets you change it. The reading, editing and writing code is a library you can use in your own pages.

Contents

  1. The format
  2. The tool
  3. The ZIP library
  4. Entries
  5. Editing
  6. The contents tree and search, for other pages

1The format

entrieslocal header + data, each
central directoryone record per entry
end recordwhere the directory is

Readers start from the end record at the end of the file, which says where the central directory is; the directory lists every entry with its name, sizes, CRC-32 and the offset of its local header. Entries are stored or deflated. Archives over 4 GB or 65,535 entries use ZIP64 records.

Things worth a look in a security review: names with ../ or an absolute path (zip slip), the same name twice (readers disagree on which copy wins), data before the first entry (a file of another kind with a ZIP appended), and entries whose local header disagrees with the directory.

Android requires stored entries in an APK to start on a 4-byte boundary, and native libraries on a 16 KB one (zipalign), so they can be mapped straight from the file.

2The tool

3The ZIP library

lib/compression/zip.js is a JavaScript module with no dependencies and no user interface. It exports one class, ZipArchive: an instance is an opened (or new) archive, and the static methods read, write and identify archives. It works in a page and in a Web Worker.

<script type="module">
	import { ZipArchive } from "../../lib/compression/zip.js";

	const archive = await ZipArchive.open(file);   // a File, Blob, ArrayBuffer or Uint8Array
	for (const entry of archive.entries) {
		console.log(entry.name, entry.size, entry.methodName);
	}
	const manifest = await archive.read("AndroidManifest.xml", { verify: true });

	const blob = await ZipArchive.build([
		{ name: "hello.txt", data: "Hello" },
		{ name: "lib/" },
		{ name: "AndroidManifest.xml", copy: { blob: archive.blob, entry: archive.get("AndroidManifest.xml") } },
	], { align: true });
</script>

Reading uses ranged reads on the Blob: only the central directory is read when the archive opens, and each entry when it is asked for, so archives of several gigabytes open at once.

Method / propertyReturnsWhat it does
await ZipArchive.open(input, options)an archiveReads the directory. Throws if the input isn't a ZipArchive. options.maxDirectory limits the directory size read (512 MB).
archive.entriesarrayThe entries, in directory order (next section).
archive.get(name)entry or nullAn entry by name; the last one when a name repeats.
archive.infoobject{ size, declaredEntries, directoryOffset, directorySize, endRecordOffset, zip64, comment, firstEntryOffset }
archive.errorsarray of stringsProblems found in the directory. The archive is still usable.
archive.kind{ id, name } or nullZipArchive.identify() of the archive as it was opened.
archive.blobBlobThe data the archive was opened from.
await archive.read(entryOrName, options)Uint8ArrayThe entry's bytes, inflated. max: at most this many bytes (1 GB), more throws; prefix: return the first max bytes instead; verify: check the size and CRC-32; buffer: return an ArrayBuffer.
await archive.stream(entryOrName)ReadableStreamThe inflated bytes as a stream.
await archive.range(entryOrName){ start, end }Where the entry's compressed data is in the file.
ZipArchive.readEntry / streamEntry / dataRange (blob, entry, …)The same three, for any Blob and an entry from its directory.
await ZipArchive.build(files, options)BlobWrites an archive. Each file is { name, data, time, compress } (data: Uint8Array, ArrayBuffer, Blob or string; names ending in / are folders; deflated unless compress: false or it doesn't help) or { name, copy: { blob, entry } } to copy an entry of another archive without inflating it. options.align aligns stored entries as zipalign does.
ZipArchive.identify(archive){ id, name } or nullRecognizes APK, AAR, IPA, AAB, APKS, XAPK, DOCX, XLSX, PPTX, EPUB, OpenDocument, WAR and JAR by the entries they must have.
await ZipArchive.isZip(blob)booleanWhether it starts like a ZipArchive.
ZipArchive.crc32(bytes, previous)numberCRC-32, optionally continuing from a previous value.
ZipArchive.METHODSobjectCompression method numbers to names.
Only stored and deflated entries can be read (that covers app packages). The writer doesn't produce ZIP64, so archives stay under 4 GB and 65,535 entries.

4Entries

FieldMeaning
index, name, dirPosition in the directory, path (UTF-8, or code page 437 for old archives), whether it is a folder.
size, compressedSizeSizes in bytes (from ZIP64 extra fields when needed).
method, methodNameCompression method number and name (with the encryption, if any).
crc, timeCRC-32 and the modification time (a Date, or null).
headerOffsetWhere its local header is.
flags, encrypted, aes, utf8The general-purpose flags and what they say.
mode, symlinkUnix permissions (archives made on Unix), and whether it is a symbolic link.
unsafe, duplicateA path that leaves the folder it's extracted to; a name that appears more than once.
comment, extraThe entry's comment; its extra fields as [{ id, size }].

5Editing

An opened archive (or a new one from ZipArchive.create()) can be changed in place; archive.entries always lists what it holds now, and archive.build() writes it.

const archive = await ZipArchive.open(file);
archive.renameFile(archive.get("assets/config.json"), "config.old.json");
archive.addFiles("assets", [new File(['{"debug":true}'], "config.json")]);
archive.deleteFolder("META-INF");
const result = await archive.build();     // a Blob
Method / propertyWhat it does
ZipArchive.create()A new, empty archive.
archive.dirtyTrue once anything changed.
archive.addFolder(path)A new empty folder; returns its entry.
archive.renameFolder(path, newName), archive.deleteFolder(path)Rename a folder (everything in it moves) or remove it with its contents.
archive.renameFile(entry, newName), archive.deleteFile(entry)Rename or remove one file.
archive.planUpload(folder, files){ plan, existing }: where each file would go and which are already there, without changing anything.
archive.addFiles(folder, files, { replace })Adds File or Blob objects; a folder upload's relative paths are kept. Returns { added, replaced }.
archive.isTaken(path, except), archive.entriesUnder(folder)Look up what is at a path, or inside a folder.
await archive.build({ align })The archive as a Blob. Unchanged entries are copied as they are; align defaults to true for APK and AAR.
ZipArchive.checkName, ZipArchive.parentOf, ZipArchive.joinPathPath helpers.

Added entries have data (their Blob) and no headerOffset; renamed ones keep their old path in originalName. A change that isn't possible (a name already taken, a name with /) throws an Error with a readable message and changes nothing.

6The contents tree and the contents search, for other pages

The Contents and Search contents sections are shared by the archive pages (ZIP tool, IPA and APK tools). They are user-interface modules in common/ (with common/archive-contents.css), built on common/common.js; the matching itself is lib/search.js.

import { ArchiveContents } from "../../common/archive-contents.js";
import { ArchiveSearch } from "../../common/archive-search.js";

const contents = new ArchiveContents({
	entries: () => archive.entries,
	viewers: (entry) => [{ url: "../../json/json.html", button: "JSON", label: "JSON tool" }],
	open: (entry, viewer) => sendToTool(viewer.url, entry.name, archive.read(entry, { buffer: true })),
	download: (entry) => saveEntry(entry),
	columns: ["method", "size", "compressed", "modified", "crc32"],
});
main.append(contents.section);           // registers its "Contents" section chip

const search = new ArchiveSearch({
	entries: archive.entries,
	extract: (entry, maxBytes) => archive.read(entry, { max: maxBytes }),
	buttons: (entry, offset) => [/* buttons; one with the class "hexbtn" is also shown on each match */],
});
section.append(search.element);
Class / memberWhat it does
new ArchiveContents(options)The virtualized tree of entries. Options: entries(), viewers(entry) → [{ url, button, label }] (a Hex tool button is always added), open(entry, viewer), download(entry), and optionally downloadFolder(path), columns, flags(entry) → badges, rowButtons(row) → extra buttons (row.type is "dir" or "file", row.path, row.entry), before (elements above the list), expanded (a Set of open folder paths), autoOpenSingleFolder.
contents.sectionThe <section id="sec-contents"> to add to the page.
contents.refresh()Rebuilds the tree after the entries changed.
contents.showPath(path)Searches for a path and scrolls to the list.
ArchiveContents.formatTime(date), ArchiveContents.HEX_VIEWERThe "modified" column's date format; the Hex tool's { url, button, label }.
new ArchiveSearch({ entries, extract, buttons })The search box: text (UTF-8 and UTF-16), case-sensitive text, hex bytes or a regular expression, file by file (files over 64 MB are skipped). entries is read at each search, so the page can keep that array up to date.
search.elementThe box to add to the page.

lib/search.js exports ByteSearch, documented in the Hex tool guide: ByteSearch.compile(query, mode), ByteSearch.find(bytes, pattern, limit) and ByteSearch.context(bytes, offset, length) are what the contents search uses.