sodcalculator

08 Everyday Math

Zip File Header: Structure, Purpose & How It Works

Guide 08-72273 · Updated · Step by step

The ZIP file header is a 30-byte local file header (plus optional 4-byte data descriptor) that begins each compressed file within a ZIP archive, signaling metadata like filename, compression method, timestamps, and uncompressed size before the actual compressed data begins.

Background and Origin

The ZIP file format was created by Phil Katz in 1989 for his PKZIP utility, building on earlier archive formats like ARJ and TAR but adding patent-free, widely supported compression via the DEFLATE algorithm. Its design prioritized simplicity, cross-platform compatibility, and efficient storage—especially important in the era of floppies and dial-up modems. The header structure was defined in PKWARE’s APPNOTE.TXT specification, which has been publicly available since the 1990s and updated regularly as new features (like AES encryption and ZIP64 extensions) were added. Unlike some formats that embed all metadata in a central directory at the end, ZIP uses a hybrid model: each file has a local header at its start (for streaming or partial extraction), and a central directory header later (for fast listing and random access). This dual-header approach balances sequential read efficiency with random access performance.

Every ZIP file begins with a 4-byte signature (0x04034b50, ASCII “PK”) that marks the start of a local file header. This signature is critical for recovery tools and file-type detection, since it’s unique and unlikely to appear by chance in compressed data. The header that follows contains fixed-size fields, ensuring parsers can reliably skip to the next file even if one entry is corrupted.

How the Local File Header Works

The local file header is exactly 30 bytes long (excluding optional data descriptors) and consists of 16 fields. Here’s a breakdown of its structure:

  • Local file header signature (4 bytes): Always 0x04034b50
  • Version needed to extract (2 bytes): Minimum PKZIP version required (e.g., 20 = 2.0, 45 = 4.5 for AES encryption)
  • General purpose flag (2 bytes): Bit flags indicating encryption, compression options, and data descriptor usage
  • Compression method (2 bytes): 0 = stored (no compression), 8 = DEFLATE, 9 = DEFLATE64, 12 = BZIP2, 14 = LZMA, 99 = AES encryption
  • Last mod file time (2 bytes): DOS time format (hours:5, minutes:6, seconds:5)
  • Last mod file date (2 bytes): DOS date format (year:7, month:4, day:5)
  • CRC-32 (4 bytes): Checksum of uncompressed data for integrity verification
  • Compressed size (4 bytes): Size of compressed data in bytes
  • Uncompressed size (4 bytes): Original file size before compression
  • Filename length (2 bytes): Length of the filename field (in bytes)
  • Extra field length (2 bytes): Length of optional metadata (e.g., Unicode paths, timestamps)
  • Filename (variable): Raw bytes of the filename, typically UTF-8 or OEM-encoded
  • Extra field (variable): Additional data like NTFS timestamps, Unix permissions, or ZIP64 extensions

The filename and extra field lengths determine where the actual compressed data begins—immediately after these variable-length fields. For example, a 12-byte filename and 20-byte extra field add 32 bytes to the base 30-byte header, so compressed data starts at byte 62.

ZIP64 and Large-File Extensions

ZIP’s original 4-byte size and offset fields limit archives to 4 GB and 4.3 billion files—problematic today. ZIP64 solves this by extending headers when needed: if any size or offset exceeds 32 bits, the main header sets those fields to 0xFFFFFFFF and appends a ZIP64 extended information extra field (ID 0x0001) in the extra field section. This extra field contains 8-byte versions of the missing values (compressed/uncompressed size, relative header offset). ZIP64 support is now universal in modern tools (7-Zip, WinZip, macOS Archive Utility), but legacy software (pre-2001) may fail or ignore ZIP64 archives silently. Always verify extraction behavior if targeting older systems.

How to Inspect a ZIP Header

You can examine headers directly using command-line tools or hex editors. On Linux/macOS, hexdump -C archive.zip | head -n 10 shows the first bytes; the first four should be 50 4b 03 04 (hex for “PK”). Tools like zipinfo (part of Info-ZIP) list headers without decompressing: zipinfo -v archive.zip prints verbose header details, including compression method and timestamps. For Windows, 7-Zip’s GUI shows header info when right-clicking → “7-Zip → Test archive” (non-destructive), or use 7z l -v archive.zip in the CLI. Python’s zipfile module can parse headers programmatically:

import zipfile
with zipfile.ZipFile('archive.zip') as zf:
for info in zf.infolist():
print(f"{info.filename}: {info.compress_type}, CRC={info.CRC:08x}")

Common mistakes include confusing the local header with the central directory header (which starts with 0x02014b50) or missing that some tools hide headers behind metadata overlays. Always verify with raw hex or verbose commands for accuracy.

Common Problems and Fixes

Corrupted headers are the #1 cause of “invalid ZIP” errors. Here are frequent issues and solutions:

  • Missing or corrupted PK signature: Often due to incomplete downloads or disk errors. Try zip -FF archive.zip --out repaired.zip (Info-ZIP’s fix flag) or 7-Zip’s “Test archive” → “Repair” feature.
  • CRC mismatch: Indicates compressed data was altered or truncated. If the header CRC is wrong, extraction may still succeed using the central directory’s CRC (if intact).
  • ZIP64 errors on large files: If a ZIP exceeds 4 GB but lacks ZIP64 extensions, tools like WinZip may error. Recreate the archive with ZIP64 enabled (check “Use ZIP64 extensions” in 7-Zip or WinRAR options).
  • Filename encoding issues: UTF-8 filenames may appear garbled on Windows if the general purpose flag bit 11 isn’t set. Modern tools handle this, but legacy systems may misread accents or non-Latin characters.

A critical misconception: “Corrupted header = unrecoverable.” In reality, if the central directory is intact (often at the end), tools like QuickPar or WinRAR’s repair mode can rebuild the local header using central directory data.

Compression Methods and Header Indicators

Header compression method codes directly impact compatibility and performance:

  • 0 (STORED): No compression; header shows compressed_size == uncompressed_size. Used for already-compressed files (e.g., JPEG, MP3) where compression wastes time.
  • 8 (DEFLATE): Default for most archives; balances speed and ratio. Requires zlib library support.
  • 14 (LZMA): Higher compression (e.g., 7z’s .7z format uses this), but slower. ZIP supports it via method 14, though few tools default to it.
  • 99 (AES): Indicates AES encryption (128/256-bit). The header includes a 2-byte “encryption strength” field (0x0001 = 128-bit, 0x0002 = 256-bit).

Example: A header with method 8, compressed_size=1024, uncompressed_size=2048 means the file was halved in size via DEFLATE. If CRC is 0x12345678, extraction tools compute the checksum post-decompression and compare it to this value.

Security Considerations

ZIP headers themselves aren’t a security risk, but they enable attacks if misused:

  • Zip bombs: Archives with tiny compressed headers pointing to massive uncompressed data (e.g., 42 KB header → 4.5 PB). Modern tools limit extraction depth or size.
  • Path traversal: Filenames like “../../etc/passwd” in the header can overwrite system files during extraction. Tools like 7-Zip now warn or block such paths by default.
  • Metadata leakage: Timestamps and filenames in headers reveal sensitive info. For privacy, strip headers using zip --encrypt --password=xxx --move archive.zip (removes original) or tools like zipcleaner.

Never extract ZIPs from untrusted sources without scanning. Most OSes (Windows, macOS) now quarantine ZIPs by default, requiring explicit user action to open.

Comparing ZIP Headers to Other Formats

How ZIP’s header design stacks up against alternatives:

  • TAR: No compression header; uses 512-byte block headers with POSIX metadata (owner, permissions, timestamps). Simpler but less self-contained.
  • GZIP: Single-file format; header is 10 bytes (ID1-ID2, compression method, flags, mtime, extra flags, OS). Too minimal for multi-file archives.
  • 7z: Uses a complex, extensible header system with codec IDs, solid-block sizes, and encrypted headers. More powerful but less universally supported.

ZIP’s strength is its balance: headers are compact enough for fast reads, flexible for extensions (ZIP64, AES), and standardized across decades of software. TAR+GZ is common in Unix but requires two tools; 7z offers better ratios but isn’t native on macOS/Windows.

Frequently Asked Questions

Q: Can I open a ZIP file without a header?
No—without the local file header (signature 0x04034b50), the file isn’t a valid ZIP. Some misnamed archives (e.g., .jar, .apk) use ZIP internally but start with a different header (e.g., APKs begin with 0x504b0506 for the central directory). Tools like file command detect them by scanning for ZIP signatures anywhere in the file.

Q: Why does my ZIP show “invalid compressed data” even with a valid header?
The header may be intact, but the compressed data stream could be truncated or corrupted. Check the CRC in the header against the computed value after decompression. If they differ, the data is damaged. Use zip -T archive.zip to verify integrity.

Q: How do I change the compression method in the header?
You can’t edit headers directly without risking corruption. Instead, recreate the archive: in 7-Zip, select “Add to archive”, choose “ZIP” format, and set compression method (e.g., DEFLATE, LZMA2). The new archive will have updated header values reflecting your choice.

Q: Are ZIP headers encrypted when I password-protect a file?
Only if using AES encryption (method 99). Legacy ZIP encryption (method 1, “traditional”) encrypts only the data, leaving filenames/timestamps visible in headers—a major flaw. Always prefer AES (check “Encrypt file names” in WinRAR or 7-Zip) to protect metadata.

Q: What’s the difference between the local header and central directory header?
The local header (0x04034b50) starts each file’s data for sequential reading. The central directory header (0x02014b50) appears at the end, listing all files for fast directory views. If the central directory is lost, recovery is harder—local headers alone don’t indicate archive boundaries. ZIP64 extends both with 8-byte fields when needed.

Q: Can headers store file permissions like Unix rwx?
Not natively in the standard header. Unix permissions are stored in the extra field as NTFS or Unix extensions (e.g., 0x000d for Unix timestamps, 0x7855 fortar). Tools like Info-ZIP preserve these when archiving on Unix-like systems, but Windows may ignore them. Always extract on the same OS type for full permission fidelity.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Everyday Math bed →